nombaone 0.1.1

Official Rust SDK for the NombaOne subscription-billing API — recurring billing for Nigeria over card, direct debit, and bank transfer.
Documentation

nombaone

The official Rust SDK for the Nomba One subscription-billing API — recurring billing for Nigeria over card, direct debit, bank transfer, and more, with dunning that recovers and a ledger that never loses a kobo.

[dependencies]
nombaone = "0.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Async-first (built on tokio and reqwest + rustls), with an optional blocking feature for synchronous callers. Requires Rust 1.85+. Zero unsafe.

Quickstart

Grab a sandbox key (nbo_sandbox_…) from the dashboard, set it as NOMBAONE_API_KEY, and you are three objects away from a live subscription:

use nombaone::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let nombaone = Nombaone::from_env()?;

    let plan = nombaone.plans().create(PlanCreateParams { name: "Pro".into(), ..Default::default() }).await?;
    let price = nombaone
        .plans()
        .prices()
        .create(&plan.id, PriceCreateParams::new(250_000, PriceInterval::Month)) // ₦2,500.00 / month
        .await?;
    let customer = nombaone
        .customers()
        .create(CustomerCreateParams { email: "ada@example.com".into(), name: "Ada Lovelace".into(), ..Default::default() })
        .await?;

    // Sandbox: mint a deterministic test card, then subscribe.
    let method = nombaone
        .sandbox()
        .create_payment_method(SandboxPaymentMethodParams { customer_id: customer.id.clone(), ..Default::default() })
        .await?;
    let subscription = nombaone
        .subscriptions()
        .create(SubscriptionCreateParams {
            customer_id: customer.id,
            price_id: price.id,
            payment_method_id: Some(method.id),
            ..Default::default()
        })
        .await?;

    println!("{}", subscription.status); // "active"
    Ok(())
}

The client derives its host from your key prefix — nbo_sandbox_… talks to https://sandbox.api.nombaone.xyz, nbo_live_… to https://api.nombaone.xyz. Server-side only; there is no publishable key to leak.

Sandbox first

The sandbox runs the real billing engine. nombaone.sandbox() gives you the levers to make a month happen in a second:

# use nombaone::*;
# async fn run(nombaone: Nombaone, customer_id: String, subscription_id: String) -> Result<(), Error> {
// A card that declines like a thin balance does — "not yet", not "no".
nombaone.sandbox().create_payment_method(SandboxPaymentMethodParams {
    customer_id,
    behavior: Some(SandboxPaymentMethodBehavior::DeclineInsufficientFunds),
    ..Default::default()
}).await?;

// The test clock: force the next billing cycle through the real engine.
let cycle = nombaone.sandbox().advance_cycle(&subscription_id).await?;
println!("{}", cycle.outcome); // "paid" | "past_due" | …

// Fire a real, signed webhook at your registered endpoints.
nombaone.sandbox().simulate_webhook(SandboxSimulateWebhookParams {
    event_type: "invoice.payment_failed".into(),
    ..Default::default()
}).await?;
# Ok(())
# }

These methods fail locally, before any network call, if used with a live key.

Money is integer kobo

Every amount in the API is an integer in kobo: ₦1.00 = 100. 250_000 is ₦2,500 — not ₦250,000. No floats, no decimal strings; currency is always "NGN". Multiply naira by 100 exactly once, at the edge of your system. Every money field is named ..._in_kobo and typed [Kobo] (an i64), so a mix-up is hard to write.

Pagination

Every list returns a [Paginator]. Await it for one [Page], stream every item with cursors handled for you, or (with the blocking feature) iterate synchronously:

# use nombaone::*;
# async fn run(nombaone: Nombaone) -> Result<(), Error> {
use futures_util::TryStreamExt;

// One page + its cursor block.
let page = nombaone.invoices().list(InvoiceListParams { status: Some(InvoiceListStatus::Open), ..Default::default() }).await?;
let _ = (page.data(), page.pagination().has_more, &page.pagination().next_cursor);

// Every item across every page — the SDK threads the cursors.
let mut open = nombaone.invoices().list(InvoiceListParams { status: Some(InvoiceListStatus::Open), ..Default::default() }).stream();
while let Some(invoice) = open.try_next().await? {
    println!("{}", invoice.id);
}
# Ok(())
# }
// With the `blocking` feature — no async runtime needed:
for invoice in nombaone.invoices().list(InvoiceListParams::default()).iter() {
    println!("{}", invoice?.id);
}

Errors are a feature

Every failure is a typed [Error]. API failures are Error::Api([ApiError]), carrying the stable code to branch on, a hint telling you exactly what to do next, a doc_url into the error reference, per-field validation details, and the request_id to quote to support. Classify by HTTP class with [ApiError::kind]:

# use nombaone::*;
# async fn run(nombaone: Nombaone, customer_id: String, price_id: String) {
match nombaone.subscriptions().create(SubscriptionCreateParams { customer_id, price_id, ..Default::default() }).await {
    Ok(subscription) => println!("{}", subscription.status),
    Err(Error::Api(e)) if e.code == ErrorCode::CUSTOMER_NOT_FOUND => { /* … */ }
    Err(Error::Api(e)) if e.kind() == ApiErrorKind::RateLimit => {
        let _retry_after = e.retry_after; // seconds
    }
    Err(Error::Api(e)) if e.kind() == ApiErrorKind::Validation => {
        let _fields = e.fields; // per-field messages
    }
    Err(other) => eprintln!("{other}"),
}
# }
Kind ([ApiErrorKind]) Status Notes
BadRequest 400 malformed request
Authentication 401 missing/invalid/wrong-environment key
PermissionDenied 403 missing scope, foreign resource
NotFound 404 wrong id or wrong environment
Conflict 409 state conflicts, idempotency reuse
Validation 422 error.fields has the per-field messages
RateLimit 429 retry_after, rate_limit, rate_remaining
Server 5xx safe to retry (the SDK already did)

Plus Error::Connection, Error::Timeout (transport), Error::Decode, Error::Config, and Error::WebhookVerification.

Idempotency & retries

The SDK auto-generates an Idempotency-Key for every POST and reuses it across its automatic retries (network failures, timeouts, 408/429/5xx — 2 retries by default, honoring Retry-After), so a blip can never double-charge. Per-call options chain before .await:

# use nombaone::*;
# use std::time::Duration;
# async fn run(nombaone: Nombaone) -> Result<(), Error> {
let payout = nombaone
    .settlements()
    .create_payout(PayoutCreateParams { amount_in_kobo: 5_000_000, bank_code: "058".into(), account_number: "0123456789".into() })
    .idempotency_key("payout-2026-07-05-001") // ⚠ doubles as the payout's durable merchant_tx_ref
    .timeout(Duration::from_secs(10))
    .await?;

// Need the request id or headers? Finish with `.with_response()`:
let response = nombaone.customers().retrieve(&payout.sub_account_ref).with_response().await?;
println!("request id: {}", response.request_id);
# Ok(())
# }

Payout note. On settlements().create_payout(...) the Idempotency-Key doubles as the durable merchant_tx_ref. The auto-generated key protects retries within one process; pass your own stable key so a retry from a new process can't create a second payout.

Webhooks

Verify before you parse, and dedupe on the event id — delivery is at-least-once, never exactly-once. The [webhooks] helpers are free functions that need no API key — only the endpoint's signing secret:

use nombaone::{webhooks, WebhookEventType};
use nombaone::webhook_events::WebhookEventData;

// In your handler, `raw_body` is the EXACT request bytes (never re-serialized)
// and `signature` is the `X-Nombaone-Signature` header.
fn handle(raw_body: &[u8], signature: &str, secret: &str) -> Result<(), nombaone::WebhookVerificationError> {
    let event = webhooks::construct_event(raw_body, signature, secret)?;

    // at-least-once ⇒ dedupe on event.event.id before acting
    // if already_processed(&event.event.id) { return Ok(()); }

    match event.event_type {
        WebhookEventType::InvoicePaid => { /* unlock access */ }
        WebhookEventType::InvoicePaymentFailed => {
            if let WebhookEventData::InvoicePaymentFailed(d) = &event.data {
                println!("payment failed: {}", d.reason);
            }
        }
        _ => {}
    }
    Ok(())
}

Capturing the raw body differs by framework — the one rule is do not let the framework parse and re-serialize it first:

  • axum: extract axum::body::Bytes (not Json); read the header from HeaderMap.
  • actix-web: take web::Bytes and HttpRequest.
  • warp: warp::body::bytes().
  • hyper: hyper::body::to_bytes(req.into_body()).

webhooks::generate_test_header lets you unit-test your handler without a real delivery. Manage endpoints with nombaone.webhook_endpoints() — create and rotate return the signing secret exactly once.

The full surface

customers (+ credit, discount) · plans (+ nested prices) · prices · subscriptions (pause/resume/cancel/resubscribe/change, schedule, dunning, upcoming invoice, events) · invoices · coupons · payment_methods (hosted-checkout cards, virtual accounts) · mandates (NIBSS direct debit) · settlements (escrow, refunds, payouts) · webhook_endpoints (+ deliveries, replay) · events (+ catalog) · organization (+ billing policy) · metrics · sandbox — every operation in the API reference, 1:1.

Worth knowing:

  • Mandates are asynchronous. They start consent_pending and activate when the customer's bank confirms — listen for payment_method.updated, don't poll, don't charge early.
  • Bank transfer is a push rail. payment_methods().create_virtual_account() issues a NUBAN; collection completes when the transfer arrives and reconciles.
  • past_due is not canceled. Read subscriptions().dunning().retrieve() and honor grace_access_until before cutting anyone off.

Configuration

# use nombaone::*;
# use std::time::Duration;
# fn run() -> Result<(), Error> {
let nombaone = Nombaone::builder()
    .api_key("nbo_sandbox_…")
    .base_url("https://sandbox.api.nombaone.xyz") // override the derived host
    .timeout(Duration::from_secs(30))             // per-attempt
    .max_retries(2)                               // automatic retry budget
    .default_header("x-app", "my-service")
    .build()?;
# let _ = nombaone;
# Ok(())
# }

Bring your own HTTP stack (a proxy, a tuned client, or a test double) by implementing [transport::HttpTransport] and passing it to .transport(...).

Feature flags

  • reqwest-transport (default) — the built-in async transport.
  • blocking — synchronous terminals (.send_blocking(), .iter()) mirroring the async surface.
  • test-util — a scriptable, recording MockTransport for your own tests.

Examples & development

Runnable examples live in examples/ — quickstart, pagination, the subscription lifecycle, a webhook receiver, and a sandbox dunning rehearsal:

NOMBAONE_API_KEY=nbo_sandbox_… cargo run --example 01_quickstart

Develop the SDK with cargo test; the live suite runs against a real API with NOMBAONE_INTEGRATION=1 NOMBAONE_API_KEY=… cargo test --test integration.

Requirements & versioning

Rust 1.85+. Semantic versioning; the API itself is versioned at /v1 and additive changes never break you. MIT licensed.