@smarthivelabs-devs/payments
v1.10.0
Published
Official Node.js SDK for SmartHive Payments — multi-provider payment processing
Readme
@smarthivelabs-devs/payments
Official Node.js SDK for SmartHive Payments — multi-provider payment processing for Africa and beyond (Paystack, Hubtel, Moolre, Seevcash, Stripe, Adyen, Checkout.com). Pass a country; SmartHive picks the currency and the provider.
Installation
npm install @smarthivelabs-devs/paymentsRequires Node.js 18+
Quick Start
import { SmartHivePayments } from '@smarthivelabs-devs/payments';
const smarthive = new SmartHivePayments({
apiKey: process.env.SMARTHIVE_PAYMENTS_API_KEY!,
baseUrl: process.env.SMARTHIVE_PAYMENTS_BASE_URL!,
mode: 'sandbox', // default mode; override per-call with mode: 'live'
});Environment Variables
| Variable | Required | Description |
|---|---|---|
| SMARTHIVE_PAYMENTS_API_KEY | Yes | Your API key (sk_test_... or sk_live_...) |
| SMARTHIVE_PAYMENTS_BASE_URL | Yes | SmartHive Payments API base URL |
| SMARTHIVE_PAYMENTS_WEBHOOK_SECRET | Yes (webhooks) | Your webhook secret (whsec_...) |
Sandbox vs Live Mode
Pass mode on each call — or set a default in the constructor and override per-call.
| Mode | Value | Use |
|---|---|---|
| Sandbox | 'sandbox' | Testing. No real money moves. |
| Live | 'live' | Production. Real transactions. |
// Use sandbox globally, override to live for specific calls
const smarthive = new SmartHivePayments({ apiKey: '...', baseUrl: '...', mode: 'sandbox' });
// This call uses the default (sandbox)
const session = await smarthive.checkout.createSession({ amount: '5000', currency: 'GHS', ... });
// Override to live
const liveSession = await smarthive.checkout.createSession({ ..., mode: 'live' });API Key Prefix & Database Routing
SmartHive uses the API key prefix to route every request to the correct database. This is enforced server-side — it cannot be bypassed by the client.
| Key prefix | Routes to | Required mode |
|---|---|---|
| sk_test_... | Sandbox database | 'sandbox' |
| sk_live_... | Live database | 'live' |
The mode on each call must match the key prefix. Mixing them returns 400 Bad Request:
// ✓ Correct — key prefix and mode agree
const smarthive = new SmartHivePayments({ apiKey: 'sk_test_abc123', baseUrl: '...' });
await smarthive.checkout.createSession({ amount: '5000', currency: 'GHS', mode: 'sandbox', ... });
// ✗ Error 400 — key is sk_test_ but mode says live
await smarthive.checkout.createSession({ amount: '5000', currency: 'GHS', mode: 'live', ... });Recommended pattern — derive mode from the key so they can never mismatch:
const apiKey = process.env.SMARTHIVE_PAYMENTS_API_KEY!;
const mode = apiKey.startsWith('sk_live_') ? 'live' : 'sandbox';
const smarthive = new SmartHivePayments({ apiKey, baseUrl: process.env.SMARTHIVE_PAYMENTS_BASE_URL!, mode });All transactions, subscriptions, webhooks, and idempotency records are fully isolated between sandbox and live databases. There is no data overlap.
Which Flow to Use
SmartHive Payments has two independent payment entry points. Pick one per payment — never combine them. Both keep the payment on SmartHive's own checkout — customers are never sent to a provider's page directly.
| Flow | Entry Point | Transaction created | When to use |
|---|---|---|---|
| Hosted Checkout (recommended) | checkout.createSession() | Only when the customer pays on the hosted page | You want SmartHive to handle the UI — method selection, card form, provider redirects — all on SmartHive's checkout frontend |
| API-First Charge | payments.apiCharge() | Immediately on this call | Server-side charges with no hosted page (mobile money, USSD, direct debit) |
⚠️ Never call
checkout.createSession()andpayments.apiCharge()for the same payment.Each creates independent records. Calling both will:
- Create two separate payment records for the same order
- Leave one record permanently stuck in
pending— it will never receive a webhook or become verifiable- Cause
payments.verify()andpayments.getStatus()to return results for the wrong recordPick one flow and use it exclusively end-to-end.
Country-Driven Payments (Global)
You never pick a provider or hardcode a currency. Pass the payer's country and SmartHive:
- resolves the country's currency (
GH→GHS,NG→NGN,GB→GBP, …), - picks the highest-priority provider that serves that country and method,
- fails over to the next provider if the first one can't take the payment.
const { data } = await smarthive.payments.initialize({
countryCode: 'GH', // currency defaults to GHS
amount: '5000', // GHS 50.00 in pesewas
paymentMethod: 'mobile_money',
customerEmail: '[email protected]',
callbackUrl: 'https://api.example.com/webhooks/payments',
returnUrl: 'https://example.com/paid',
});
redirect(data.checkoutUrl);- Pass
currencyonly to charge in a different currency the country accepts. - Pass
providerCodeto prefer one provider. SmartHive still falls back by priority if it's unavailable. countryandcountryCodeare interchangeable on every endpoint, includingcheckout.createSession(),payouts.*andpayments.listBanks().
Which countries and methods are available?
const { data: countries } = await smarthive.countries.list({ region: 'Africa' });
const { data: gh } = await smarthive.countries.get('GH');
gh.currency; // 'GHS'
gh.collection; // [{ method: 'mobile_money', currency: 'GHS', providers: ['paystack', 'hubtel', 'moolre', 'seev'] }, ...]
gh.payout; // [{ method: 'mobile_money', ... }, { method: 'bank_account', ... }]Use collection to decide which payment buttons to show, and payout to decide which payout options a user can set up. Provider order is managed centrally on the SmartHive dashboard (Countries page), so your code doesn't change when routing does.
Mobile money across Africa
Mobile money works the same way in every supported country — Ghana, Kenya and Nigeria, plus Benin, Burkina Faso, Cameroon, Côte d'Ivoire, DR Congo, Republic of the Congo, Ethiopia, Gabon, Lesotho, Malawi, Mozambique, Rwanda, Senegal, Sierra Leone, Tanzania, Uganda, Zambia and Zimbabwe (via pawaPay):
// Uganda: currency (UGX) comes from the country; the customer picks MTN or Airtel on the hosted page.
const { data } = await smarthive.payments.initialize({ countryCode: 'UG', amount: '50000', customerEmail, callbackUrl, returnUrl });
// Paying a host in Côte d'Ivoire: same payout steps as Ghana.
const { data: check } = await smarthive.payouts.validateDetails({
country: 'CI',
method: 'mobile_money',
details: { bankCode: 'Orange Money', accountNumber: '+225 07 34 56 78 90', name: 'Awa Koné' },
});
check.recipient; // { type: 'mobile_money', bankCode: 'orange', accountNumber: '0734567890', metadata: { phoneE164: '+2250734567890' }, ... }- Amounts are in the currency's smallest unit as always — and UGX, RWF, XOF and XAF have no decimals, so
'50000'means 50,000 UGX. - Countries that share a currency (XOF, XAF) are told apart by
countryCode, so always pass it. - DR Congo also accepts USD: pass
currency: 'USD'(andpayouts.getRequirements('CD', { currency: 'USD' })for USD payouts).
Price once, charge any country (quotes)
Price in your own currency. SmartHive picks the currency the buyer can be charged in: your price's currency if a provider in their country takes it, otherwise their local currency (market rate + FX margin), otherwise USD by card. To show the buyer the exact amount first, quote it — the rate is locked for 15 minutes and the quote can be used once:
const { data: quote } = await smarthive.payments.quote({
amount: '10000', currency: 'GHS', countryCode: 'NG', mode: 'live',
});
// quote.charge.currency → 'NGN'
// quote.methods → [{ method: 'mobile_money', provider: 'pawapay', total: '1199441', feePaidBy: 'included', ... }]
await smarthive.checkout.createSession({
amount: '10000', currency: 'GHS', countryCode: 'NG', quoteId: quote.quoteId, /* ... */
});Processing fees
By default (a per-project setting), the fee of providers that take it from you
— Paystack, pawaPay — is added to what the customer pays, so you receive your
full price: GHS 100 by card through Paystack charges GHS 101.99. Providers that
bill the customer themselves (Hubtel, Moolre) add nothing. Override per call
with passFeeToCustomer.
Because of this, amount in verify responses and payment.success webhooks is
what the provider charged. Compare orderAmount / orderCurrency with your
price, not amount.
Upgrading to 1.10
- Compare
orderAmountwith your price, notamount. With processing fees passed on (the default),amountinpayment.successwebhooks and inpayments.verify()is what the buyer was charged — GHS 101.99 for a GHS 100 card payment, or naira for a Nigerian buyer.orderAmount/orderCurrencyis your price. - Refunds are in your own currency and capped at your price: a full refund of a GHS 100 order refunds GHS 100 (the processing fee isn't refundable). A payment the buyer made in another currency is refunded at the original rate.
- Blocked countries (sanctioned countries, and Sudan) are refused with HTTP
403 and
error.code === 'COUNTRY_BLOCKED'— show the buyer the message:
try {
await smarthive.checkout.createSession({ countryCode: buyerCountry, /* ... */ });
} catch (err) {
if (err instanceof SmartHiveError && err.code === 'COUNTRY_BLOCKED') {
showMessage(err.message); // "Payments from Iran aren't supported (...)."
}
}Checkout Flow (Recommended)
The checkout flow creates a hosted payment page. The customer pays on that page; your backend receives a webhook confirming the result.
Important — understand what
createSessiondoes and does not do:
checkout.createSession()creates a pre-payment container and returns acheckoutUrl. It does not create a payment transaction. No payment exists yet after this call.A payment transaction is only created when the customer visits the
checkoutUrland submits their payment details on the hosted checkout page. Until that happens, callingpayments.verify()with any reference from the session will return a 404 — there is nothing to verify yet.The payment
referenceyou use withverify()comes from either:
- The webhook event (
event.data.reference) — recommended- The returnUrl query string (
?reference=txn_xxx) — after the customer is redirected back
Step 1 — Create the session (server-side)
const session = await smarthive.checkout.createSession({
amount: '5000', // GHS 50.00 in pesewas
currency: 'GHS',
countryCode: 'GH',
platform: 'web', // 'web' | 'mobile' | 'expo' | 'server'
customerEmail: '[email protected]',
customerName: 'Kwame Mensah',
returnUrl: 'https://yourapp.com/order/complete', // where to send the customer after payment
callbackUrl: 'https://yourapp.com/webhooks/payments', // where SmartHive posts the result
callerReference: 'ORDER-001', // optional — your own order/transaction ID
passFeeToCustomer: false, // optional — true adds provider fee on top of amount (default: false)
cardType: 'LOCAL', // optional — 'LOCAL' | 'INTERNATIONAL' for fee lookup (default: 'LOCAL')
mode: 'sandbox',
});
// session.data.checkoutUrl — send this to your frontend to redirect the customer
// session.data.sessionId — a checkout session identifier (NOT a payment reference)
// session.data.callerReference — echoed back if you passed one ('ORDER-001')
// session.data.processingFeeMinor — calculated provider fee in minor units
// session.data.netAmountMinor — amount minus fee in minor units
// session.data.passFeeToCustomer — whether the fee was added on top
//
// ⚠️ Do NOT pass session.data.sessionId to payments.verify() — it will not work.
// A payment reference is only available after the customer pays (see steps below).Step 2 — Redirect the customer
// Frontend: redirect to the checkout URL
window.location.href = session.data.checkoutUrl;
// or open in a new tab
window.open(session.data.checkoutUrl, '_blank');Step 3A — Confirm payment via webhook (recommended)
Set up a webhook handler at the callbackUrl you provided. SmartHive posts a signed event
when the customer pays. Use event.data.reference — this is the payment reference.
import express from 'express';
import { SmartHivePayments, WebhookSignatureError } from '@smarthivelabs-devs/payments';
const smarthive = new SmartHivePayments({ ... });
const app = express();
app.post(
'/webhooks/payments',
express.raw({ type: 'application/json' }), // ← raw body is required for signature verification
(req, res) => {
let event;
try {
event = smarthive.webhooks.constructEvent(
req.body,
req.headers['x-signature'] as string,
process.env.SMARTHIVE_PAYMENTS_WEBHOOK_SECRET!,
);
} catch (err) {
if (err instanceof WebhookSignatureError) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
throw err;
}
switch (event.event) {
case 'payment.success':
// event.data.reference — the payment reference
// event.data.netAmount — settled amount after provider fee (minor units)
// event.data.processingFee — provider fee deducted (minor units)
await fulfillOrder(event.data.reference, { netAmount: event.data.netAmount });
break;
case 'payment.failed':
await notifyCustomer(event.data.reference);
break;
case 'payout.success':
await recordPayout(event.data.reference);
break;
}
res.sendStatus(200);
},
);Step 3B — Confirm payment via returnUrl (alternative)
When the customer finishes on the checkout page, SmartHive redirects them to your returnUrl
with ?reference=txn_xxx&status=success appended. Extract the reference from the query string
and verify it server-side.
// Example: Express handler for GET /order/complete?reference=txn_xxx&status=success
app.get('/order/complete', async (req, res) => {
const reference = req.query.reference as string | undefined;
if (!reference) {
// Customer may have navigated here directly — show a generic order page
return res.render('order-pending');
}
// Verify with SmartHive to confirm the payment (don't trust query params alone)
const result = await smarthive.payments.verify(reference);
if (result.data.status === 'success') {
await fulfillOrder(result.data.reference);
return res.render('order-success', { reference: result.data.reference });
}
res.render('order-pending', { status: result.data.status });
});Checkout Flow — Programmatic Launch (no hosted page redirect)
If you want to initiate payment entirely server-side — skipping the hosted checkout page — use
checkout.launchSession() after createSession(). This creates the payment transaction
immediately and returns a paymentReference you can verify right away.
// Step 1: Create the session container
const session = await smarthive.checkout.createSession({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
platform: 'server',
customerEmail: '[email protected]',
returnUrl: 'https://yourapp.com/order/complete',
callbackUrl: 'https://yourapp.com/webhooks/payments',
mode: 'sandbox',
});
// Step 2: Launch the session — this creates the payment transaction
const launch = await smarthive.checkout.launchSession(session.data.sessionId, {
paymentMethod: 'card', // or 'mobile_money', 'bank_transfer', etc.
customerEmail: '[email protected]',
callbackUrl: 'https://yourapp.com/webhooks/payments',
returnUrl: 'https://yourapp.com/order/complete',
mode: 'sandbox',
});
// launch.data.paymentReference is a real payment reference — safe to verify
console.log(launch.data.paymentReference); // 'txn_xxx' — use this with payments.verify()
console.log(launch.data.checkoutUrl); // redirect the customer here to complete payment
// Step 3: After the customer pays, verify using paymentReference
const result = await smarthive.payments.verify(launch.data.paymentReference);
if (result.data.status === 'success') {
await fulfillOrder(result.data.reference);
}Verify a Payment
Call verify() only after the customer has completed payment. Pass the payment reference
from the webhook event.data.reference, the returnUrl query string ?reference=..., or
the paymentReference returned by checkout.launchSession().
// Full verification (server-side, after webhook or redirect)
const payment = await smarthive.payments.verify('txn_xxx');
console.log(payment.data.status); // 'success' | 'failed' | 'pending'
console.log(payment.data.amount); // '5000'
console.log(payment.data.paidAt); // '2026-01-01T11:45:00.000Z'
// Lightweight status check (for polling — cheaper than full verify)
const status = await smarthive.payments.getStatus('txn_xxx');
console.log(status.data.status);What reference to pass:
- After
checkout.createSession()+ customer pays on hosted page → useevent.data.referencefrom webhook or?reference=from returnUrl query string- After
checkout.createSession()withcallerReference→ you can also verify with your own reference:smarthive.payments.verify('ORDER-001')- After
checkout.launchSession()→ uselaunch.data.paymentReference- After
payments.apiCharge()withreference→ use your reference directly:smarthive.payments.verify('ORDER-001')
Webhooks
Use constructEvent to verify and parse incoming webhooks. Always use the raw request body — not parsed JSON.
Express
import express from 'express';
import { SmartHivePayments, WebhookSignatureError } from '@smarthivelabs-devs/payments';
const smarthive = new SmartHivePayments({ ... });
const app = express();
app.post(
'/webhooks/payments',
express.raw({ type: 'application/json' }), // ← raw body required
(req, res) => {
let event;
try {
event = smarthive.webhooks.constructEvent(
req.body,
req.headers['x-signature'] as string,
process.env.SMARTHIVE_PAYMENTS_WEBHOOK_SECRET!,
);
} catch (err) {
if (err instanceof WebhookSignatureError) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
throw err;
}
switch (event.event) {
case 'payment.success':
// event.data.netAmount — settled amount after provider fee (minor units)
// event.data.processingFee — provider fee deducted (minor units)
await fulfillOrder(event.data.reference, { netAmount: event.data.netAmount });
break;
case 'payment.failed':
await notifyCustomer(event.data.reference);
break;
case 'payout.success':
await recordPayout(event.data.reference);
break;
}
res.sendStatus(200);
},
);Static usage (without client instance)
import { SmartHivePayments } from '@smarthivelabs-devs/payments';
const event = SmartHivePayments.webhooks.constructEvent(rawBody, signature, secret);Webhook Event Types
| Event | Description |
|---|---|
| payment.success | Payment completed |
| payment.failed | Payment failed |
| payment.pending | Awaiting confirmation |
| payment.abandoned | Customer abandoned checkout |
| payout.success | Payout completed |
| payout.failed | Payout failed |
| mandate.approved | Direct debit mandate approved |
| mandate.declined | Mandate declined by customer |
| refund.success | Refund processed |
| coupon.redeemed | Coupon applied and usage incremented after payment |
Phone-only customer identity
Customer-facing creation calls that accept customerPhone can omit
customerEmail. The SDK supplies a deterministic placeholder before sending
the request to SmartHive Payments. Set metadata.channel and
metadata.serviceName to control the non-sensitive local part:
await smarthive.payments.apiCharge({
amount: '5000', currency: 'GHS', countryCode: 'GH',
method: 'mobile_money', customerPhone: '233244123456',
mobileMoneyProvider: 'mtn',
metadata: { channel: 'ussd', serviceName: 'instant-payment' },
});
// customerEmail sent to the API:
// [email protected]When both email and phone are absent, existing server validation still applies. A supplied email is never modified.
Direct Debit
Hubtel Direct Debit preapproval is separate from Programmable Services USSD.
Hubtel chooses USSD or OTP; submit an OTP only when requiresOtp is true.
Store the opaque authorizationId rather than the customer's wallet number:
const mandate = await smarthive.directDebit.createMandate({
amount: '100', currency: 'GHS', countryCode: 'GH',
customerPhone: '233244123456',
mobileMoneyProvider: 'mtn', providerCode: 'hubtel',
callbackUrl: 'https://example.com/payment-events',
returnUrl: 'https://example.com/billing', mode: 'live',
});
if (mandate.data.requiresOtp) {
await smarthive.directDebit.verifyMandateOtp(mandate.data.authorizationId!, {
otp: '8852', countryCode: 'GH', currency: 'GHS', mode: 'live',
});
}Charge a customer without re-entering payment details, after a one-time preapproval. Two providers are supported — they work differently:
| Provider | Method | Countries | How approval works |
|---|---|---|---|
| Paystack | Card authorization | GH, NG | Customer pays on a hosted page once; you receive a card authorizationCode |
| Hubtel | Mobile money USSD/OTP | GH | Customer approves via USSD prompt or OTP on their phone; store their MSISDN as the authorizationCode |
Hubtel note: Direct debit requires your server IP to be whitelisted by Hubtel. Contact your Retail System Engineer before going live.
Step 1 — Create Mandate
Paystack (card authorization — customer redirected to hosted page):
const mandate = await smarthive.directDebit.createMandate({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
customerEmail: '[email protected]',
callbackUrl: 'https://yourapp.com/webhooks/payments',
returnUrl: 'https://yourapp.com/direct-debit/complete',
providerCode: 'paystack',
mode: 'sandbox',
});
// Redirect customer to Paystack's authorization page
console.log(mandate.data.checkoutUrl);
// After they authorize, receive a card authorizationCode via mandate.approved webhookHubtel (mobile money USSD/OTP — no redirect, customer approves on their phone):
const mandate = await smarthive.directDebit.createMandate({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
customerEmail: '[email protected]',
customerPhone: '233244123456', // required for Hubtel
callbackUrl: 'https://yourapp.com/webhooks/payments',
returnUrl: 'https://yourapp.com/direct-debit/complete',
providerCode: 'hubtel',
metadata: { mobileMoneyProvider: 'mtn' }, // mtn | vodafone | airteltigo
mode: 'sandbox',
});
// No checkoutUrl — customer receives a USSD prompt or OTP on their phone
// Store mandate.data.rawResponse.authorizationCode (the MSISDN) for future chargesStep 2 — Wait for Webhook
When the customer approves, you receive a mandate.approved webhook. Store the authorizationCode against the customer record.
- Paystack:
event.data.authorizationCode— a card token (e.g.AUTH_xxx) - Hubtel: store
mandate.data.rawResponse.authorizationCode— the customer's MSISDN (e.g.'233244123456')
Step 3 — Charge (no interaction required)
// Paystack
const charge = await smarthive.directDebit.chargeMandate({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
customerEmail: '[email protected]',
authorizationCode: 'AUTH_xxx', // card token from webhook
providerCode: 'paystack',
reference: 'SUBSCRIPTION-JAN-2026',
mode: 'live',
});
// Hubtel
const charge = await smarthive.directDebit.chargeMandate({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
customerEmail: '[email protected]',
authorizationCode: '233244123456', // MSISDN stored from mandate creation
providerCode: 'hubtel',
metadata: { mobileMoneyProvider: 'mtn' },
reference: 'SUBSCRIPTION-JAN-2026',
mode: 'live',
});
console.log(charge.data.status); // 'success' | 'pending'Payouts
Send money to mobile wallets or bank accounts in any supported country.
Step 0 — Collect payout details (any country)
Every country needs different details. Ghana uses a mobile-money network and number, Nigeria a bank and a 10-digit NUBAN, the UK a sort code and account number, the EU an IBAN, and the US a routing number, account number and account type. SmartHive keeps that knowledge in one place. Your app only renders, validates and stores.
1. Ask what to collect
const { data: req } = await smarthive.payouts.getRequirements('GH');
for (const method of req.methods) {
method.method; // 'mobile_money' | 'bank_account'
method.label; // 'Mobile Money'
method.available; // false = details can be stored, but no provider pays out this way yet
method.fields; // what to render (below)
method.institutions; // networks / banks for select fields
}Each field tells you how to render it:
| field.type | Render |
|---|---|
| select + institutionType | A select of method.institutions (value = code, label = name) |
| select + options | A select of the fixed options |
| phone | A phone input (any format — it's normalized server-side) |
| text / number / email | A text input; pattern, example and helpText are there for hints and client-side checks |
Ghana mobile money, for example, returns:
{
"method": "mobile_money",
"recipientType": "mobile_money",
"fields": [
{ "key": "bankCode", "label": "Mobile money network", "type": "select", "institutionType": "mobile_money", "required": true },
{ "key": "accountNumber", "label": "Mobile money number", "type": "phone", "required": true, "example": "0241234567", "resolvable": true },
{ "key": "name", "label": "Registered name", "type": "text", "required": true }
],
"institutions": [
{ "code": "mtn", "name": "MTN Mobile Money" },
{ "code": "vodafone", "name": "Telecel Cash" },
{ "code": "airteltigo", "name": "AT Money" }
]
}Banks for countries like Nigeria come live from the payout provider. If you only need one list, use smarthive.payouts.listInstitutions('NG', { type: 'bank' }).
2. Validate what the user typed (server-side)
const { data: check } = await smarthive.payouts.validateDetails({
country: 'GH',
method: 'mobile_money',
details: { bankCode: 'mtn', accountNumber: '+233 24 123 4567', name: 'Ama Mensah' },
resolveName: true, // confirm the account holder's name with the provider where supported
});
if (!check.valid) {
return res.status(422).json({ errors: check.errors }); // [{ field: 'accountNumber', message: '...' }]
}
// Show check.resolvedAccountName to the user and ask them to confirm before saving.When valid, check.normalized holds the cleaned values (0241234567, digits-only account numbers, uppercase IBANs), and check.recipient is a ready-made createRecipient() payload.
3. Store the details in your database, encrypted
SmartHive does not store your users' payout details. Encrypt them at rest with your own key, for example with AES-256-GCM:
import crypto from 'crypto';
const KEY = Buffer.from(process.env.PAYOUT_DETAILS_KEY!, 'base64'); // 32 bytes
export function encryptDetails(value: unknown): string {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', KEY, iv);
const data = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);
return [iv, cipher.getAuthTag(), data].map((b) => b.toString('base64')).join('.');
}
export function decryptDetails<T>(stored: string): T {
const [iv, tag, data] = stored.split('.').map((p) => Buffer.from(p, 'base64'));
const decipher = crypto.createDecipheriv('aes-256-gcm', KEY, iv);
decipher.setAuthTag(tag);
return JSON.parse(Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8'));
}
await db.payoutAccounts.insert({
userId,
country: 'GH',
method: 'mobile_money',
label: `${check.recipient!.bankCode.toUpperCase()} •••${check.normalized.accountNumber.slice(-4)}`, // safe to show
encryptedRecipient: encryptDetails(check.recipient),
});4. At payout time, decrypt it and use it in Step 1 and Step 2 below:
const details = decryptDetails<NonNullable<typeof check.recipient>>(row.encryptedRecipient);
const recipient = await smarthive.payouts.createRecipient({ ...details, mode: 'live' });Other countries follow the same flow; only details changes:
// Nigeria: bank + NUBAN (bankCode from method.institutions)
{ country: 'NG', method: 'bank_account', details: { bankCode: '058', accountNumber: '0123456789', name: 'Chidi Okafor' }, resolveName: true }
// United Kingdom: sort code + account number
{ country: 'GB', method: 'bank_account', details: { name: 'Jane Smith', bankCode: '12-34-56', accountNumber: '12345678' } }
// Germany (any SEPA country): IBAN, BIC optional; the IBAN checksum is verified
{ country: 'DE', method: 'bank_account', details: { name: 'Lena Fischer', accountNumber: 'DE89 3704 0044 0532 0130 00' } }
// United States: routing (checksum verified) + account + type
{ country: 'US', method: 'bank_account', details: { name: 'Sam Lee', bankCode: '011000015', accountNumber: '12345678', accountType: 'checking' } }Only need a name lookup?
await smarthive.payouts.resolveAccountName({ country: 'GH', method: 'mobile_money', bankCode: 'mtn', accountNumber: '0241234567' })returns the name, ornullif it can't be confirmed.
Step 1 — Create Recipient
// Easiest: spread the `recipient` from validateDetails() (Step 0)
const recipient = await smarthive.payouts.createRecipient({ ...check.recipient!, mode: 'live' });
// Or by hand:
const recipient2 = await smarthive.payouts.createRecipient({
type: 'mobile_money', // use recipientType from getRequirements()
name: 'Kwame Mensah',
accountNumber: '0244123456',
bankCode: 'mtn', // institution code from getRequirements()
country: 'GH', // currency defaults to GHS
mode: 'live',
});
// Store recipient.data.recipientCode for future payoutsStep 2 — Send Payout
const payout = await smarthive.payouts.send({
amount: '10000', // GHS 100.00 in pesewas
currency: 'GHS',
country: 'GH',
recipientCode: recipient.data.recipientCode,
payoutMethod: 'mobile_money',
reason: 'Contest winnings',
mode: 'live',
});
console.log(payout.data.status); // 'pending' (confirmed via payout.success webhook)Step 3 — (Optional) Resilient, Multi-Provider Payouts
By default, payouts.send() is a single attempt against one provider — fine for most cases. For higher-stakes payouts (large amounts, unattended/automated triggers), opt into the resilient path by adding operationReference and authorizedAmountLimit. This gets you, for free and enforced server-side:
- A durable ceiling.
authorizedAmountLimitis recorded once peroperationReferenceand can never be silently raised by a later call — real defense-in-depth, not just a client-side check you could get wrong. - Idempotent replay. Reusing the same
operationReferenceafter a success returns the original outcome — it never re-charges. - Safe multi-provider failover (opt-in via
allowProviderFailover). If a provider definitively rejects the payout (a confirmed rejection — nothing was charged), the platform automatically retries the next eligible provider. If a provider fails ambiguously (timeout, 5xx, unknown outcome), it is never auto-retried — with any provider — until the outcome is reconciled. This is what actually makes failover safe: a network blip can never turn into a duplicate payout.
const payout = await smarthive.payouts.send({
amount: '10000', // GHS 100.00 in pesewas
currency: 'GHS',
country: 'GH',
recipientCode: recipient.data.recipientCode,
payoutMethod: 'mobile_money',
reason: 'Contest winnings',
mode: 'live',
operationReference: 'payout-order-4821', // unique per payout intent, your own id
authorizedAmountLimit: '10000', // same units as `amount` — the enforced ceiling
allowProviderFailover: true,
// Required for allowProviderFailover to actually create a recipient on a
// fallback provider — recipientCode alone is opaque to other providers.
recipientDetails: {
type: 'mobile_money',
name: 'Kwame Mensah',
accountNumber: '0244123456',
bankCode: 'MTN',
currency: 'GHS',
},
});
if (payout.data.reconciling) {
// Outcome is genuinely unknown right now (e.g. the provider timed out).
// Do NOT retry — poll status instead, on your own schedule (e.g. a
// background job), until it resolves.
} else {
console.log(payout.data.status, payout.data.providerCode, payout.data.attemptCount);
}Poll reconciliation state at any time — including after a reconciling: true response, or to check on a payout you triggered from a background job:
const status = await smarthive.payouts.getOperationStatus('payout-order-4821', { mode: 'live' });
console.log(status.data.operation.status); // 'OPEN' | 'RECONCILING' | 'COMPLETED' | 'EXHAUSTED'
console.log(status.data.operation.paidAmountMinor);
status.data.attempts.forEach((a) => {
console.log(a.attemptNumber, a.providerCode, a.status, a.errorClassification);
});EXHAUSTED means every eligible provider definitively rejected the payout — nothing was charged, and it's safe to investigate/fix and retry with a fresh operationReference. RECONCILING means the outcome is still unknown for at least one attempt — resolve that before doing anything else with this recipient/amount.
Step 4 — (Moolre only) Internal Account-to-Account Transfer
Separate from send() above: this moves funds directly from your Moolre account balance into another Moolre account/wallet — settlement infrastructure (e.g. sweeping collected funds to a platform account), not a customer-facing payout. It never touches a Mobile Money network or bank rail, so it requires a Moolre provider config on your app; other providers do not support it.
const transfer = await smarthive.payouts.moolreInternalTransfer({
currency: 'GHS',
amount: '10000', // GHS 100.00 in pesewas
receiverAccountNumber: '100000100002', // destination Moolre account number
externalRef: 'settlement-4821', // unique per transfer intent
mode: 'live',
});
if (transfer.data.otpRequired) {
// Moolre texted an OTP to the account holder's registered phone.
// Resend the exact same currency/amount/receiverAccountNumber/externalRef
// with otpCode set to complete it.
await smarthive.payouts.moolreInternalTransfer({
currency: 'GHS',
amount: '10000',
receiverAccountNumber: '100000100002',
externalRef: 'settlement-4821',
mode: 'live',
otpCode: '123456',
});
} else {
console.log(transfer.data.transactionId);
}Check status by the same externalRef at any time:
const status = await smarthive.payouts.getMoolreInternalTransferStatus('settlement-4821', { mode: 'live' });
console.log(status.data.status); // 'pending' | 'success' | 'failed' | 'reversed' | 'unknown'Bank Verification
// List available banks
const banks = await smarthive.payments.listBanks({ countryCode: 'GH', mode: 'sandbox' });
// Resolve account number → account name before initiating transfer
const account = await smarthive.payments.verifyBankAccount({
accountNumber: '0123456789',
bankCode: 'GCB',
countryCode: 'GH',
currency: 'GHS',
mode: 'sandbox',
});
console.log(account.data.accountName); // 'Kwame Mensah'API-First Charge (No Hosted Checkout)
Charge a mobile money wallet directly from your server — useful for subscription billing.
const charge = await smarthive.payments.apiCharge({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
method: 'mobile_money',
customerEmail: '[email protected]',
customerPhone: '233244123456',
mobileMoneyProvider: 'mtn', // 'mtn' | 'vodafone' | 'telecel' | 'airteltigo'
callbackUrl: 'https://yourapp.com/webhooks/payments',
returnUrl: 'https://yourapp.com/order/complete',
mode: 'sandbox',
});Idempotency
Pass an idempotencyKey to safely retry requests without double-charging:
const session = await smarthive.checkout.createSession(
{ amount: '5000', currency: 'GHS', ... },
'order-001-attempt-1', // idempotency key
);Error Handling
All errors extend SmartHiveError with statusCode, code, and optional correlationId:
import {
SmartHiveError,
AuthenticationError,
ValidationError,
RateLimitError,
NotFoundError,
PaymentError,
WebhookSignatureError,
} from '@smarthivelabs-devs/payments';
try {
const session = await smarthive.checkout.createSession({ ... });
} catch (err) {
if (err instanceof AuthenticationError) {
// Invalid or expired API key
} else if (err instanceof ValidationError) {
// Missing or invalid request fields
} else if (err instanceof RateLimitError) {
// Rate limited — err.retryAfter gives seconds to wait
console.log(`Retry after ${err.retryAfter}s`);
} else if (err instanceof NotFoundError) {
// Resource not found — if verifying, the payment may not exist yet
} else if (err instanceof PaymentError) {
// Payment-specific error (400, 402, 409, 500, 502)
console.log(err.statusCode, err.code, err.correlationId);
} else if (err instanceof SmartHiveError) {
// Any other SDK error
}
}Health Check
Verify your API key is valid:
const health = await smarthive.payments.health();
// Throws AuthenticationError if the API key is invalidTypeScript
All request params and responses are fully typed. Import types directly:
import type {
ApiChargeParams,
ApiChargeResponse,
CheckoutSessionParams, // includes passFeeToCustomer, cardType, merchantRouting (v1.4+)
CheckoutSessionResponse, // includes processingFeeMinor, netAmountMinor, passFeeToCustomer, settlementRoute (v1.4+)
CheckoutLaunchParams,
CheckoutLaunchResponse,
DirectDebitMandateParams,
DirectDebitChargeParams,
PayoutParams,
SmartHiveEvent,
SmartHiveEventType,
WebhookEventData, // includes processingFee, netAmount, passFeeToCustomer (v1.3+)
PaymentMode,
// Coupon types
CreateCouponParams,
UpdateCouponParams,
Coupon,
CouponValidateParams,
CouponValidateResponse,
CouponStatsResponse,
ListCouponsParams,
CouponDiscountType,
CouponApplicableTo,
// Merchant routing types (v1.4+)
MerchantRoutingParams,
MerchantAccountReadiness,
SettlementRoute,
PlatformFeeStatus,
} from '@smarthivelabs-devs/payments';Common Mistakes
Calling createSession and payments.apiCharge together
The most frequent integration error. See Which Flow to Use. Choose one.
Calling payments.verify() or payments.getStatus() immediately after createSession()
// ❌ WRONG — this will always return 404
const session = await smarthive.checkout.createSession({ ... });
const status = await smarthive.payments.getStatus(session.data.sessionId); // 404
// ✅ CORRECT — verify only after the customer has paid
// Get the reference from your webhook event or from ?reference= on your returnUrl
const result = await smarthive.payments.verify(referenceFromWebhookOrReturnUrl);At the time createSession() returns, no transaction exists yet. A transaction is only created when the customer visits the checkoutUrl and submits payment. Calling verify or getStatus with a session ID (chs_xxx) or any reference before that point returns 404 — there is nothing to find.
Polling getStatus() on a 404 in a retry loop
A 404 from getStatus() means the transaction does not exist — not that it is still pending. Retrying indefinitely on 404 creates an infinite loop.
// ❌ WRONG — 404 does not mean "pending, try again"
while (true) {
const status = await smarthive.payments.getStatus(reference);
if (status.data.status === 'success') break;
await sleep(3000); // loops forever if reference never existed
}
// ✅ CORRECT — stop on 404; it means the transaction was never created
import { NotFoundError } from '@smarthivelabs-devs/payments';
try {
const status = await smarthive.payments.getStatus(reference);
if (status.data.status === 'success') { /* fulfill */ }
} catch (err) {
if (err instanceof NotFoundError) {
// Transaction not found — do not retry; investigate why it was never created
}
}Passing sessionId to payments.verify()
// ❌ WRONG — session IDs (chs_xxx) are not payment references
const result = await smarthive.payments.verify(session.data.sessionId); // 404
// ✅ CORRECT — use the reference from the webhook or from ?reference= on your returnUrl
const result = await smarthive.payments.verify(event.data.reference);
// or if you passed callerReference: 'ORDER-001' to createSession:
const result = await smarthive.payments.verify('ORDER-001');Coupons
Create and manage discount codes. Discounts are always applied server-side — the checkout session stores the discounted amount so the client never controls pricing.
Create a coupon
const coupon = await smarthive.coupons.create({
name: 'Summer Sale',
discountType: 'percentage',
discountValue: 2000, // 2000 basis points = 20%
applicableTo: 'all', // 'all' | 'checkout_only' | 'subscriptions_only'
maxUses: 100, // -1 = unlimited
maxUsesPerCustomer: 1,
expiresAt: '2026-12-31T23:59:59Z',
// couponCode omitted → auto-generates e.g. "COUP_3F8A"
});
console.log(coupon.data.couponCode); // 'COUP_3F8A'Fixed-amount coupon (currency-scoped):
const fixedCoupon = await smarthive.coupons.create({
name: 'GHS 10 Off',
discountType: 'fixed',
discountValue: 1000, // GHS 10.00 in minor units
currency: 'GHS', // required for fixed-type — enforced on every redemption
applicableTo: 'checkout_only',
});Validate a coupon (dry run)
Preview the discount without incrementing usage — call this before checkout to show the customer their savings.
const preview = await smarthive.coupons.validate('SUMMER20', {
amountMinor: 5000, // GHS 50.00
currency: 'GHS',
customerId: 'user_001',
applicableTo: 'checkout',
});
// preview.data.valid — true/false
// preview.data.discountAmountMinor — 1000 (GHS 10.00 off)
// preview.data.finalAmountMinor — 4000 (GHS 40.00 to pay)Apply at checkout
Pass couponCode when creating the checkout session. The backend validates the coupon, increments usage, and stores the discounted amount on the session. The customer only pays the discounted total.
Set allowCouponInput: true to show a coupon input field on the hosted checkout page so customers can enter codes themselves. Omit it (default: false) and no coupon UI appears — only pre-applied coupons via couponCode take effect.
const session = await smarthive.checkout.createSession({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
couponCode: 'SUMMER20', // optional — pre-apply a coupon at session creation
allowCouponInput: true, // optional — show coupon input on hosted checkout page
customerEmail: '[email protected]',
returnUrl: '...',
callbackUrl: '...',
mode: 'sandbox',
});
// session.data.originalAmountMinor — '5000' (what was requested)
// session.data.discountAmountMinor — '1000' (how much was deducted)
// session.data.amountMinor is now — '4000' (what the customer pays)Apply at subscription creation:
await smarthive.subscriptions.create({
planCode: 'plan_pro_monthly',
customerId: 'user_001',
authorizationCode: 'AUTH_xxx',
couponCode: 'SUMMER20', // discount applied to first charge
mode: 'sandbox',
});CRUD operations
// List coupons (optionally filter by active state)
const list = await smarthive.coupons.list({ isActive: true, limit: 20, offset: 0 });
// Get a single coupon
const coupon = await smarthive.coupons.get('SUMMER20');
// Update (partial — code, discountType, and discountValue are immutable)
await smarthive.coupons.update('SUMMER20', {
maxUses: 200,
expiresAt: '2027-01-01T00:00:00Z',
isActive: false,
});
// Delete (soft-delete — existing redemptions are unaffected)
await smarthive.coupons.delete('SUMMER20');Stats
const stats = await smarthive.coupons.stats('SUMMER20');
// stats.data.coupon — full CouponResponse
// stats.data.totalUses — number of redemptions
// stats.data.recentUsages — last redemptions with customer + amountsCoupon webhook event
Add a coupon.redeemed handler to your webhook listener:
case 'coupon.redeemed':
// event.data.couponCode — 'SUMMER20'
// event.data.discountAmountMinor — 1000
// event.data.finalAmountMinor — 4000
// event.data.currency — 'GHS'
// event.data.sessionId — checkout session that used the coupon
await recordCouponRedemption(event.data);
break;Validation errors
The backend enforces all constraints and returns a descriptive 400 error when validation fails:
| Error | Cause |
|---|---|
| Coupon is inactive | isActive is false |
| Coupon has expired | expiresAt is in the past |
| Coupon is only valid for subscriptions | Used on checkout but applicableTo = subscriptions_only |
| Coupon currency does not match | Fixed coupon currency ≠ request currency |
| Order amount is below the minimum for this coupon | amountMinor < minOrderAmount |
| Coupon usage limit reached | currentUses >= maxUses |
| Coupon usage limit reached for your account | Per-customer maxUsesPerCustomer hit |
| Coupon has already been used | Single-use coupon already redeemed by this customer |
| Coupon is not valid for this plan | Subscription plan not in planCodes list |
TypeScript types
import type {
CreateCouponParams,
UpdateCouponParams,
Coupon,
CouponValidateParams,
CouponValidateResponse,
CouponStatsResponse,
ListCouponsParams,
CouponDiscountType, // 'percentage' | 'fixed'
CouponApplicableTo, // 'all' | 'checkout_only' | 'subscriptions_only'
} from '@smarthivelabs-devs/payments';Processing Fees
SmartHive tracks the provider processing fee on every transaction and gives you two modes to handle it.
Fee modes
| Mode | passFeeToCustomer | What happens |
|---|---|---|
| Absorb (default) | false | Customer pays the amount you specified. The provider fee is deducted from your payout. |
| Pass-through | true | The provider fee is added on top of the amount. Customer pays amount + fee. You receive the full amount after the provider takes their cut. |
Pass the fee to the customer
Set passFeeToCustomer: true when creating a checkout session. SmartHive calculates the fee for the resolved provider and inflates the charge automatically.
const session = await smarthive.checkout.createSession({
amount: '5000', // GHS 50.00 — what you want to receive
currency: 'GHS',
countryCode: 'GH',
passFeeToCustomer: true, // customer pays 50.00 + provider fee
cardType: 'LOCAL', // 'LOCAL' | 'INTERNATIONAL' — used for fee lookup (default: 'LOCAL')
customerEmail: '[email protected]',
returnUrl: '...',
callbackUrl: '...',
mode: 'sandbox',
});
// session.data.amountMinor — inflated total the customer is charged (e.g. '5085')
// session.data.processingFeeMinor — fee portion in minor units (e.g. '85')
// session.data.netAmountMinor — your base amount (e.g. '5000')
// session.data.passFeeToCustomer — trueThe hosted checkout page automatically shows a fee breakdown to the customer when passFeeToCustomer is true.
Read fee data on the webhook
When a payment succeeds, the payment.success event includes the resolved fee:
case 'payment.success':
const { reference, amount, processingFee, netAmount, passFeeToCustomer } = event.data;
// processingFee — fee charged by the provider, in minor units (e.g. '85')
// netAmount — amount - processingFee, in minor units (e.g. '4915')
// passFeeToCustomer — true if fee was passed through to the customer
//
// Credit your wallet / fulfil the order using netAmount (not amount) if you want
// to track the exact settled value after the provider takes their cut.
await fulfillOrder(reference, { netAmount, processingFee });
break;Fee rules are configured per-provider
Fee configs are stored in SmartHive's database and seeded for all supported providers:
| Provider | Currency | Card type | Rate | Flat fee | Cap | |---|---|---|---|---|---| | Paystack | NGN | LOCAL | 1.5% | ₦100 | ₦2,000 | | Paystack | NGN | INTERNATIONAL | 3.9% | ₦100 | — | | Stripe | USD | ALL | 2.9% | $0.30 | — | | Stripe | EUR | ALL | 1.4% | €0.25 | — | | Stripe | GBP | ALL | 1.4% | £0.20 | — | | Hubtel | GHS | LOCAL | 1.5% | — | — | | Hubtel | GHS | INTERNATIONAL | 3.9% | — | — | | Adyen | USD | ALL | 0.3% | $0.11 | — | | Checkout.com | USD | ALL | 1.9% | $0.20 | — |
Configs can be managed through the SmartHive Payment Dashboard → Fee Configs playground, or via the admin API (GET/POST/PUT/DELETE /admin/providers/:providerId/fee-configs).
TypeScript types
import type {
CheckoutSessionParams, // includes passFeeToCustomer, cardType
CheckoutSessionResponse, // includes processingFeeMinor, netAmountMinor, passFeeToCustomer
WebhookEventData, // includes processingFee, netAmount, passFeeToCustomer
} from '@smarthivelabs-devs/payments';Business Merchant Routing
Let an approved business workspace collect payments into their own Hubtel, Paystack, or Moolre account instead of SmartHive's central account, with SmartHive's platform fee automatically swept (Hubtel/Moolre) or split at settlement (Paystack). If the merchant account is unavailable or suspended, the payment automatically falls back to the central account — it never fails the checkout.
Step 1 — Register a merchant account
const account = await smarthive.merchantAccounts.create({
externalWorkspaceId: 'ws_123',
provider: 'hubtel', // 'hubtel' | 'paystack' | 'moolre'
});
// account.data.status — 'PENDING_VALIDATION'Step 2 — Submit credentials
await smarthive.merchantAccounts.submitCredentials(account.data.id, {
provider: 'hubtel',
secrets: {
apiId: 'HUBTEL_CLIENT_ID',
apiKey: 'HUBTEL_CLIENT_SECRET',
merchantAccountId: 'HUBTEL_MERCHANT_ACCOUNT_ID',
prepaidDepositId: 'HUBTEL_PREPAID_DEPOSIT_ID',
},
hubtelScopeConfirmed: true,
hubtelIpWhitelistConfirmed: true,
});Step 3 — Validate, then wait for staff approval
await smarthive.merchantAccounts.validate(account.data.id);
// status moves to 'PENDING_APPROVAL' — a platform staff member approves it
// from the SmartHive admin panel before it can be used.Step 4 — Set as default and route payments to it
Once ACTIVE, set it as the workspace's default and attach merchantRouting to checkout sessions or API-first charges:
await smarthive.merchantAccounts.setDefault(account.data.id);
const session = await smarthive.checkout.createSession({
amount: '5000',
currency: 'GHS',
countryCode: 'GH',
platform: 'web',
customerEmail: '[email protected]',
returnUrl: '...',
callbackUrl: '...',
merchantRouting: {
merchantAccountId: account.data.id,
externalWorkspaceId: 'ws_123',
platformFeeMinor: '250', // your platform fee, in minor units
organizerNetMinor: '4750', // what the organizer should net
transactionKind: 'order', // optional — any label your app finds useful (not interpreted by SmartHive)
centralFallback: true,
},
mode: 'live',
});
// session.data.settlementRoute — 'MERCHANT_FEE_SWEEP' | 'MERCHANT_PAYSTACK_SPLIT' | 'PLATFORM_WALLET'
// 'PLATFORM_WALLET' means the account was unavailable and it fell back automatically.merchantRouting also works on payments.apiCharge() for API-first flows (USSD/Telegram/WhatsApp) that don't go through a hosted checkout session — same shape, same fallback behavior.
Checking readiness
const accounts = await smarthive.merchantAccounts.list('ws_123');
// each entry: { status, isDefault, maskedIdentifier, capabilities, lastValidatedAt, consecutiveFeeTransferFailures }
const readiness = await smarthive.merchantAccounts.getReadiness(account.data.id);Responses never include credentials — only masked identifiers and status. Approve/reject/suspend/disable are staff-only actions performed from the SmartHive admin panel, not exposed on this client.
What never changes
- Subscriptions and any payment without
merchantRoutingalways settle to the central account (PLATFORM_WALLET) — nothing about existing integrations changes. - A successful merchant-routed payment still fulfills immediately even if the platform fee sweep/split is still
PENDING— it's an independent, auditable debt, never a blocker.
Subscriptions
Recurring billing — create plans, attach subscribers, and manage the full lifecycle from your server.
Create a plan
const plan = await smarthive.subscriptions.plans.create({
name: 'Pro Monthly',
amount: 5000, // in the smallest currency unit (kobo, pesewas, cents)
currency: 'GHS',
countryCode: 'GH',
interval: 'monthly', // daily | weekly | monthly | quarterly | yearly
trialPeriodDays: 7, // 0 = no trial
gracePeriodDays: 3, // days after failed payment before access is revoked
entitlements: ['read', 'download', 'api_access'], // named feature keys
description: 'Full access to Pro features',
mode: 'sandbox',
});
console.log(plan.data.planCode); // e.g. "plan_pro_monthly_abc123"Create a subscription
Attach a customer to a plan. Pass authorizationCode (from a prior direct-debit mandate or card authorization) so the worker can charge them automatically on each renewal.
const subscription = await smarthive.subscriptions.create({
planCode: 'plan_pro_monthly_abc123',
customerId: 'user_001', // your own user ID — used for SDK lookup
customerEmail: '[email protected]',
customerName: 'Ama Mensah',
authorizationCode: 'AUTH_xxx', // from a mandate.approved webhook
providerCode: 'paystack', // provider that issued the auth code
mode: 'sandbox',
});
console.log(subscription.data.subscriptionCode); // e.g. "sub_abc123"
console.log(subscription.data.status); // "trialing" | "active"Look up a customer's subscription
// Single plan — used by SDK hooks to gate access
const lookup = await smarthive.subscriptions.lookup({
planCode: 'plan_pro_monthly_abc123',
customerId: 'user_001',
});
// lookup.data.hasAccess — true when active, trialing, or in grace period
// lookup.data.isInGracePeriod
// lookup.data.entitlements — ['read', 'download', 'api_access']
// lookup.data.subscription — full Subscription object
// Batch — check multiple plans in one request
const batch = await smarthive.subscriptions.lookupBatch({
planCodes: ['plan_basic', 'plan_pro'],
customerId: 'user_001',
});
// batch.data['plan_pro'].hasAccess → true/falseLifecycle management
// Pause — optionally specify days; resumes automatically when pauseEndsAt passes
await smarthive.subscriptions.pause('sub_abc123', { pauseDays: 30 });
// Resume early
await smarthive.subscriptions.resume('sub_abc123');
// Cancel at end of current period (default)
await smarthive.subscriptions.cancel('sub_abc123');
// Cancel immediately
await smarthive.subscriptions.cancel('sub_abc123', { immediate: true });Charge history
const charges = await smarthive.subscriptions.charges('sub_abc123');
// charges.data — SubscriptionCharge[] with status, attemptNumber, chargedAtPlan management
// List all plans for your app
const plans = await smarthive.subscriptions.plans.list();
// Get a single plan
const plan = await smarthive.subscriptions.plans.get('plan_pro_monthly_abc123');
// Update (partial)
await smarthive.subscriptions.plans.update('plan_pro_monthly_abc123', {
gracePeriodDays: 5,
entitlements: ['read', 'download', 'api_access', 'priority_support'],
});
// Soft delete (existing subscribers are unaffected)
await smarthive.subscriptions.plans.delete('plan_pro_monthly_abc123');Webhook events
| Event | Fired when |
|---|---|
| subscription.created | New subscriber created |
| subscription.activated | Trial ended, subscription went active |
| subscription.charged | Recurring charge succeeded |
| subscription.charge_failed | Charge failed (entering grace period or retry) |
| subscription.paused | Subscription paused |
| subscription.resumed | Subscription resumed |
| subscription.cancelled | Cancelled or max retries exhausted |
| subscription.trial_ending | 72 hours before trial ends |
| subscription.trial_ended | Trial period just ended |
How automatic charging works
- When a subscription is created with an
authorizationCode, the worker stores it and setsnext_charge_atbased on the plan interval. - The
SubscriptionWorkerruns hourly and finds all subscriptions due for charge. - On success → status stays
active,next_charge_atadvances by one interval,subscription.chargedwebhook fires. - On failure →
retry_countincrements, status becomespast_due(grace period begins),subscription.charge_failedfires. AftermaxRetryCountfailures → status becomesexpired,subscription.cancelledfires.
TypeScript types
import type {
SubscriptionPlan,
Subscription,
SubscriptionCharge,
SubscriptionStatus, // 'pending' | 'trialing' | 'active' | 'past_due' | 'paused' | 'cancelled' | 'expired'
SubscriptionInterval, // 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly'
CreatePlanDto,
CreateSubscriptionDto,
LookupBatchResponse,
} from '@smarthivelabs-devs/payments';Support
Contact Smart Hive Labs or open an issue in the workspace repository.
