Skip to Content
SubscriptionsCharging & Dunning

Charging

A charge attempt is one try at collecting one billing period. The scheduler (every five minutes) runs due attempts, the provider settles them, and webhooks report the outcome. Usually you call nothing. This page covers what you control and how to read failures.

Who gets charged, and how

SetupAt nextBillingAt
automatic with a saved cardStored authorization is charged silently.
standing_orderVectaPay charges nothing. Safaricom debits on the mandate’s schedule.
customer_approval, customer has a phoneM-Pesa prompt sent.
customer_approval, email but no phoneAttempt stays pending. You start a card checkout.
Neither phone nor emailAttempt fails; nobody to ask.

An email-only attempt is never picked up by the worker. If nobody starts a checkout, the hourly sweep fails it about two hours after nextBillingAt and the subscription enters recovery.

A card-only subscription needs a checkout each period until a reusable card is captured. After the first successful reusable card charge it becomes automatic. If the provider returns the card as non-reusable, it stays on customer_approval; that is the provider’s call, not a setting.

Starting a charge yourself

Use initiateCharge() to collect now instead of at the scheduled date, or to start a card checkout.

const charge = await vectapay.subscriptions.initiateCharge(subscriptionId, { method: "card", email: "amina@example.com", returnUrl: "https://your-app.example.com/billing/return", idempotencyKey: "charge-2026-11-16", }); if (charge.chargeStatus === "pending" && charge.checkoutRedirectUrl) { redirect(charge.checkoutRedirectUrl); // the outcome arrives by webhook }
FieldRequiredNotes
methodYescard or mobile_money.
emailFor cardWhere checkout and receipts go.
phoneFor mobile_moneyReceives the M-Pesa prompt.
returnUrlNoAbsolute http(s) URL for the browser after checkout.
providerAccountIdNoPin a provider account instead of letting routing choose.
idempotencyKeyNoMax 120 chars. A replay with a different phone, email, provider account, returnUrl, or method is rejected.

The call looks at the latest attempt:

  • processing: returns it, does nothing else.
  • pending: moves it to now.
  • failed or abandoned: creates a new attempt for the same period with retryNumber + 1.

Then card runs through hosted checkout (the response may already be succeeded, or pending with a checkoutRedirectUrl), and mobile_money sends the prompt and returns pending.

It works on trialing, active, and past_due subscriptions and cannot run on paused, canceled, or expired. It also needs a latest attempt that is pending, processing, failed, or abandoned. If the latest is succeeded or voided (after cancel-at-period-end or a scheduled end, or on a standing-order subscription), the call is rejected with no failed subscription payment to retry.

On a trialing subscription it charges immediately and ends the trial. It is not a preview or an authorization check.

Retrying overdue money

retryCharge() is for a subscription that is already past_due.

await vectapay.subscriptions.retryCharge(subscriptionId, { reason: "Customer says the M-Pesa prompt never arrived", // 8–240 chars, recorded on the ledger idempotencyKey: "retry-2026-11-17", });

Attempt handling is the same as above. Both calls dispatch subscription.retry_scheduled. Both responses carry idempotent: true means the key replayed a recorded request and no second charge was started. A retry that creates a new attempt consumes a retry slot, so if it fails, the next automatic retry follows from the next offset and attemptsLeft is lower.

retryCharge()initiateCharge()
Subscription statepast_due onlytrialing, active, past_due
Cancel-at-period-endRefusedRejected in practice (the cancel voids the pending attempt)
reasonRequiredNot accepted
Payment methodThe subscription’s existing railYou choose card or mobile_money
Use forRecovering an overdue periodCharging early, or starting a checkout

What a failure does

A failure moves the subscription to past_due, sets dunningStartedAt and graceEndsAt, increments failedAttempts, and schedules the next retry. Offsets count from the first failure, not the previous attempt: failure at T+0 retries at T+24h; if that fails, the next is T+48h. A late retry whose slot has passed runs as soon as it is queued, which can look like two prompts in quick succession.

Webhook fieldMeaning
attemptNumberThis attempt, counting the initial charge as 1.
attemptsLeftAutomatic retries remaining.
totalAttemptsInitial charge plus every configured retry.
retryAtNext retry, or null when none remains.
graceEndsAtWhen recovery closes.

When no retry remains, subscription.dunning_exhausted is sent, and subscription.expired follows the hourly sweep after graceEndsAt (so up to an hour late).

Standing orders differ. A failed Ratiba debit enters the same recovery state, but VectaPay schedules no retry (it cannot charge the mandate) and sends no dunning_exhausted. A later Safaricom occurrence is processed as a new attempt.

Underpayment, overpayment, mismatch

A provider can report success with the wrong amount. That is not a renewal.

SituationAttemptSubscriptionRetry
Paid lessfailed, UNDERPAIDpast_dueNone; manual review
Amount missing or unreadablefailed, AMOUNT_UNVERIFIEDpast_dueNone; manual review
Different currencyfailed, CURRENCY_MISMATCHpast_dueNone; manual review. This is a provider-side safety net — subscriptions only accept KES, so this triggers when a provider reports a different currency in its callback.
Paid moresucceededRenewedn/a

Overpayment is not refunded; the excess is in overpaidAmount on subscription.charge_succeeded. The three failures carry expectedAmount, paidAmount, shortfallAmount, and requiresManualReview: true; an STK charge’s payload carries only the attempt, payment, failure code, and those money fields, with no retry counters or failureReason. Handle that flag. The customer was charged, so a human must decide to refund, ask for the balance, or let them go.

Other codes: RATIBA_NO_OCCURRENCE (no Safaricom debit within two hours of a standing order’s billing date), IDEMPOTENCY_CONFLICT (key replayed with different details), and provider codes passed through.

Settling a charge

The initiateCharge() response says what was started, not the outcome. Settlement arrives as webhooks, usually the subscription.* event first and payment.* alongside.

subscription.charge_succeeded carries, in eventPayload:

FieldWhat it is
chargeAttemptIdThe attempt that won.
paymentIdThe underlying payment.
checkoutRequestIdThe period charge key, stable across retries.
receiptNumberProvider receipt, when supplied.
expectedAmount, paidAmountMoney objects.
overpaidAmountMoney object or null.

The subscription’s own price is data.amount, outside eventPayload. A standing-order success carries amount and amountVerified: true instead of the expected/paid fields and checkoutRequestId.

subscription.charge_failed carries chargeAttemptId, paymentId, failureCode, failureReason, retryAt, graceEndsAt, the counters above, and checkoutRequestId.

Correlation IDs are not interchangeable:

  • checkoutRequestId: the period charge (subscription + billing anchor + amount); same on every retry and used as the payment idempotency key. Match on it for “has this period been paid at all?”.
  • chargeAttemptId: one attempt; changes on every retry. Match on it for a dashboard row.
  • paymentId: one payment; each retry creates another.

Never grant access from payment.succeeded. A payment can succeed while the attempt is failed (underpayment, currency mismatch). Also, a subscription.charge_succeeded with attributedToPeriod: false or requiresManualReview: true is not a renewal: it is a duplicate payment for a paid period, or a payment that settled after its attempt was voided by a lifecycle change (pause, cancel, billing-date change). Grant only when the period-level event has neither.

One attempt settles per period. Duplicates are recorded for review and never extend the subscription twice; a late callback on a closed or paused subscription is recorded without changing its state.

Looking up one charge

chargeStatus() answers “what happened to this period charge?” without waiting for a webhook.

const status = await vectapay.subscriptions.chargeStatus(subscriptionId, charge.checkoutRequestId!); if (status.isFinal) { // isSuccessful, failureCode, receiptNumber, nextBillingAt are now meaningful. }

Pass the checkoutRequestId from initiateCharge(), retryCharge(), or a charge webhook, not the paymentId.

  • No matching payment returns an empty shell with status: null, not a 404.
  • A pending or initiated payment triggers a live provider query, so it is slower than a database read.
  • Throttled to 12 requests per minute. It is a support tool, not a polling target.
  • isFinal means the payment settled; isSuccessful is the money outcome, not the subscription status.

For the return page after card checkout, use the public status endpoint. It needs the subscription ID, the checkoutRequestId, and the statusToken returned by initiateCharge() (the default return URL carries it as token). The token is signed server-side, so a checkoutRequestId alone is not enough. It is throttled to 60 requests per minute. Keep it in the browser; from your backend use your API key and chargeStatus(). Pattern: redirect with checkoutRequestId and statusToken in your own URL, call the public endpoint once on load, and let the webhook be the definitive answer.

What the customer is told

If the customer has an email, the platform sends its own messages for: an upcoming charge (a daily job covers charges due within three days, skipped when cancelling at period end), success, failure (with the next retry date), dunning exhausted, underpayment, pause, resume, cancellation, and expiry. Don’t duplicate them; if you send your own, add something useful, such as a link to their account page. A customer with no email gets nothing, even on failure, so keep an email on the record.

Last updated on