use crate::client::{Bachs, RequestOptions};
use crate::common::{FlexObject, Metadata, Timestamp};
use crate::error::BachsResult;
use reqwest::Method;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
pub struct ProductCartItem {
pub product_id: String,
pub quantity: u32,
}
impl ProductCartItem {
pub fn new(product_id: impl Into<String>, quantity: u32) -> Self {
Self {
product_id: product_id.into(),
quantity,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum CheckoutCustomer {
Existing { customer_id: String },
Inline {
email: String,
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<String>,
},
}
impl CheckoutCustomer {
pub fn existing(customer_id: impl Into<String>) -> Self {
Self::Existing {
customer_id: customer_id.into(),
}
}
pub fn email(email: impl Into<String>) -> Self {
Self::Inline {
email: email.into(),
name: None,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CreateCheckoutSessionRequest {
pub product_cart: Vec<ProductCartItem>,
pub customer: CheckoutCustomer,
pub return_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>,
}
impl CreateCheckoutSessionRequest {
pub fn new(
product_cart: Vec<ProductCartItem>,
customer: CheckoutCustomer,
return_url: impl Into<String>,
) -> Self {
Self {
product_cart,
customer,
return_url: return_url.into(),
cancel_url: None,
metadata: None,
}
}
pub fn cancel_url(mut self, cancel_url: impl Into<String>) -> Self {
self.cancel_url = Some(cancel_url.into());
self
}
pub fn metadata(mut self, metadata: Metadata) -> Self {
self.metadata = Some(metadata);
self
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct CheckoutSession {
pub checkout_session_id: String,
pub url: String,
#[serde(default)]
pub status: Option<String>,
#[serde(default)]
pub metadata: Metadata,
pub created_at: Timestamp,
#[serde(flatten)]
pub extra: FlexObject,
}
pub struct CheckoutSessions<'a> {
pub(crate) client: &'a Bachs,
}
impl<'a> CheckoutSessions<'a> {
pub async fn create(
&self,
req: &CreateCheckoutSessionRequest,
) -> BachsResult<CheckoutSession> {
self.create_with_options(req, None).await
}
pub async fn create_with_options(
&self,
req: &CreateCheckoutSessionRequest,
options: Option<&RequestOptions>,
) -> BachsResult<CheckoutSession> {
self.client
.send(
Method::POST,
"/v1/checkout-sessions",
Some(req),
None,
options,
)
.await
}
pub async fn get(&self, checkout_session_id: &str) -> BachsResult<CheckoutSession> {
self.client
.send::<(), _>(
Method::GET,
&format!("/v1/checkout-sessions/{checkout_session_id}"),
None,
None,
None,
)
.await
}
}