bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation

bachs-sdk

An unofficial, fully-typed Rust SDK for the Bachs API — payments and billing for internet businesses.

This mirrors the resource layout of the unofficial Node.js SDK: one client, one method per resource, async all the way down.

Community project, not published or endorsed by Bachs.

Installation

cargo add bachs-sdk

Initialization

use bachs_sdk::Bachs;

// Infers sandbox (sk_sandbox_...) vs. production (sk_live_...) from the key prefix.
let bachs = Bachs::new(std::env::var("BACHS_API_KEY")?)?;

Need to point at something else (a mock server in tests, an explicit environment)?

use bachs_sdk::{Bachs, Environment};
use std::time::Duration;

let bachs = Bachs::builder(api_key)
    .environment(Environment::Sandbox) // or Environment::Production / Environment::Custom(url)
    .timeout(Duration::from_secs(10))
    .build()?;

Usage examples

Retrieve a customer

let customer = bachs.customers().get("cust_123456").await?;
println!("{} {}", customer.email, customer.name.unwrap_or_default());

Create a checkout session

use bachs_sdk::checkout_sessions::{CheckoutCustomer, CreateCheckoutSessionRequest, ProductCartItem};

let session = bachs
    .checkout_sessions()
    .create(&CreateCheckoutSessionRequest::new(
        vec![ProductCartItem::new("prod_98765", 1)],
        CheckoutCustomer::email("user@example.com"),
        "https://your-site.com/success",
    ).cancel_url("https://your-site.com/cancel"))
    .await?;

println!("Checkout URL: {}", session.url);

For a recurring product, this same call is also how you create a subscription — there's no separate subscriptions.create.

Verify webhooks

Webhooks — not client-side checkout redirects — are the source of truth for fulfilment. Bachs signs each delivery with an HMAC-SHA256 signature and a whsec_... secret; pull the three relevant values from whatever your framework calls its webhook-id / webhook-timestamp / webhook-signature headers and pass them in:

use bachs_sdk::webhooks::{construct_event, SignatureHeaders};

async fn handle_webhook(raw_body: &[u8], id: &str, timestamp: &str, signature: &str) -> Result<(), bachs_sdk::BachsError> {
    let event = construct_event(
        raw_body,
        SignatureHeaders { id, timestamp, signature },
        "whsec_your_webhook_secret",
    )?;

    if event.event_type == "collection.succeeded" {
        let charge_id = event.data.get("charge_id").and_then(|v| v.as_str());
        println!("Payment succeeded: {charge_id:?}");
    }

    Ok(())
}

raw_body must be the exact, unparsed request bytes — the signature is computed over them, so re-serializing a parsed body won't match.

Error handling

Every fallible call returns Result<T, BachsError>. API errors carry the same shape documented across the Bachs API: a detail, an error_code, and — for 400 VALIDATION_ERROR responses — a list of field-level errors.

use bachs_sdk::{products::CreateProductRequest, products::Price, BachsError};

match bachs.products().create(&CreateProductRequest::new("", Price::fixed("XYZ", "-10"))).await {
    Ok(product) => println!("created {}", product.product_id),
    Err(BachsError::Api { status, body, .. }) => {
        println!("status: {status}, code: {}", body.error_code);
        for field_error in &body.errors {
            println!("  {}: {}", field_error.field, field_error.message);
        }
    }
    Err(other) => return Err(other.into()),
}

Idempotent retries

POST requests accept an Idempotency-Key:

use bachs_sdk::{customers::CreateCustomerRequest, RequestOptions};

let opts = RequestOptions::new().idempotency_key("retry-1234");
let customer = bachs
    .customers()
    .create_with_options(&CreateCustomerRequest::new("jane@example.com"), Some(&opts))
    .await?;

Available resources

Client method Resource
bachs.products() Manage products and pricing plans in your catalog.
bachs.checkout_sessions() Create and retrieve hosted checkout sessions.
bachs.subscriptions() Read, update, and cancel recurring billing subscriptions.
bachs.customers() Store and manage customer details and billing information.
bachs.customer_sessions() Create authenticated billing-portal sessions for customers.
bachs.payments() Read and list one-time payments and transactions.
bachs.refunds() Issue and track refunds for successful payments.
bachs.accounts() Retrieve your account's balances and settlement details.
bachs.connected_accounts() Manage sub-accounts for marketplace or platform routing.
bachs.transfers() Route funds between your platform and connected accounts.
bachs.media() Upload files and get an upload_id to attach to products.
bachs.payment_rails() List supported payment methods and networks.
bachs_sdk::webhooks Verify webhook signatures and parse events.

A note on schema coverage

This SDK is built against Bachs' public documentation, not an internal schema dump. customers, products, and checkout_sessions follow fully-specified OpenAPI schemas and are typed strictly. A few other resources (subscriptions, payments, refunds, transfers, connected_accounts, ...) are typed against the fields the docs and examples confirm, with an extra: FlexObject catch-all on each response so additional fields your API version returns are preserved rather than causing a deserialization error.

If a response doesn't match what's modeled here, please open an issue — ideally with the (secret-redacted) response body.

Contributing

See CONTRIBUTING.md.

License

MIT