bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
use crate::client::{Bachs, RequestOptions};
use crate::common::{FlexObject, Metadata, Timestamp};
use crate::error::BachsResult;
use reqwest::Method;
use serde::{Deserialize, Serialize};

/// A line item in a checkout's product cart.
#[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,
        }
    }
}

/// Identify the customer for a checkout — either an existing `customer_id`,
/// or inline details Bachs will use to find-or-create one.
#[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 {
    /// Prefixed with `chk_`.
    pub checkout_session_id: String,
    /// The hosted checkout URL to redirect (or send) the customer to.
    pub url: String,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub metadata: Metadata,
    pub created_at: Timestamp,
    /// Any additional fields your API version returns that this SDK version
    /// doesn't model explicitly yet.
    #[serde(flatten)]
    pub extra: FlexObject,
}

pub struct CheckoutSessions<'a> {
    pub(crate) client: &'a Bachs,
}

impl<'a> CheckoutSessions<'a> {
    /// Create a checkout session for a product cart and redirect the
    /// customer to `session.url`. For recurring products this is also how
    /// subscriptions get created — there's no separate create-subscription
    /// endpoint.
    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
    }
}