Create a subscription and report its payments
What you will build
You create a subscription for a customer, report the payment of its first invoice, and read the subscription's status to decide whether to give the customer access. You also learn what Black does when no payment is reported, when a payment is reported late, and when a report is repeated or wrong.
Before you start
You need a test environment, a customer, and a recurring price of that environment. You need an access token. See Authentication.
Your account collects the money itself: you take each payment from your customer outside Black, then report it to Black. The card, its update and the retry of a failed charge are therefore on your side: Black holds no card, and gives you the subscription's state, the invoice to collect and the events to act on. The account setting payment_mode is account_collects, which is its default, and a subscription's collection_method is then send_invoice. Black charges automatically only through a connected gateway: a request for charge_automatically with no active gateway connection is refused with 409 and the code gateway_not_connected.
These settings of the environment change what you read below. Read them with GET /v1/settings and change them with PATCH /v1/settings.
| Setting | Default | Allowed | What it sets |
|---|---|---|---|
days_until_due | 1 | 0 to 365 | How many days after an invoice is finalized it is due. 1 makes it due one day after it is finalized, so a renewal that you report paid within the day never reads past_due. 0 makes it due when it is finalized, so a renewal is past_due, in grace, from its first second until you report it paid. A new subscription takes the value at its creation and keeps it. An account created before the default became 1 keeps the value it had. |
unpaid_subscription_expiry_hours | 23 | 1 to 720 | How long a new subscription waits for its first payment before it expires. |
revival_days | 7 | 0 to 90 | How long after a subscription ends for an unpaid invoice a late report can still bring it back. 0 means it is never brought back. |
grace_enabled | true | true or false | Whether a subscription with an unpaid renewal enters grace (past_due) or ends at the invoice's due date. |
grace_length_days | 15 | 1 to 60 | How many days after the due date of an unpaid renewal invoice grace lasts. Black keeps the value while grace is off and does not use it. |
grace_retries | 3 | 1 to 10 | The retries in grace. Black retries nothing where your account collects the money: you take each payment and report it. |
keeps_entitlements_in_grace | true | true or false | Whether a past_due subscription keeps giving the features of its product. |
Steps
-
Create a subscription. Send a
POSTrequest to/v1/subscriptionswith thecustomerand 1 to 20items, each a recurringpriceof the environment and aquantity(1 by default). Every price has the currency and the billing interval of the first item. Send anIdempotency-Keyheader, so that you can repeat the request safely. The response holds the subscription: itsstatusisincomplete, itsstatus_labelisincomplete, and itslatest_invoiceis the ID of its first invoice.A customer holds one live subscription at a time: one that is
incomplete,activeorpast_due. A second create for that customer is refused with409and the codealready_member, and Black stores nothing. Find the live subscription withGET /v1/subscriptions?customer={id}. A customer whose subscriptions have all ended may subscribe again, and gets a new subscription with a new first invoice. An unpaid new subscription counts as live until it expires or you cancel it. -
Read the first invoice with
GET /v1/invoices/{id}. Itsstatusisopen, itsamount_remainingis the amount to collect, and itsdue_dateisdays_until_duedays afterfinalized_at. Itsnumber, such asINV-000001, is the invoice's number within the environment; theinvoice_prefixsetting sets its letters. -
Collect the money from the customer yourself. In this payment mode Black takes no payment: it takes one only in
black_charges, through a connected gateway. The subscription gives the customer no access while it isincomplete. -
Report the payment as soon as you take it. Send a
POSTrequest to/v1/invoices/{id}/mark-paidwith theamountand thecurrency. Theamountis a whole number of the currency's smallest unit and must equal the invoice'samount_remaining; thecurrencymust be the invoice's. Add your ownpayment_referencefor the payment, and apayment_noteif you want one. The response holds the invoice: itsstatusispaid,paid_out_of_bandistrue, andpaid_atis set. -
Read the subscription with
GET /v1/subscriptions/{id}. Itsstatusisactive, and its period is the one it had when you created it. Give the customer access. -
Read the events the steps recorded.
customer.subscription.created,invoice.createdandinvoice.finalizedfollow the creation, andinvoice.paidandcustomer.subscription.updatedfollow the report. With the defaultdays_until_dueof 1, the invoice is due one day after it is finalized, soinvoice.overduedoes not follow the creation. With 0 it follows the creation at once, because the invoice is due when it is finalized. See Events.
Read the status of a subscription
Every subscription carries its status, and beside it a status_label that Black works out whenever it returns the subscription and never stores. You never send either field.
| Status | Label | What it means | How a subscription enters it | How it leaves it | Give access? |
|---|---|---|---|---|---|
incomplete | incomplete | The subscription is created and its first invoice is open and unpaid. | You create the subscription. | You report the first invoice paid, and it becomes active. The time for an unpaid new subscription passes, and it becomes incomplete_expired. Or you cancel it now, and it becomes canceled. | No |
active | active | The subscription is running and paid, and it renews each period. | You report the first invoice paid. You report a payment in grace, or a late payment within the revival time. Or you undo a cancel at the end of the period. | A renewal invoice is overdue with grace on, and it becomes past_due. The invoice is overdue with grace off, or you cancel now, and it becomes canceled. | Yes |
active, with cancel_at_period_end true | pending_cancel | The subscription is running and paid, and it ends at the end of its current period. | You cancel it at the end of the period. | You undo the cancel, and it reads active. Its period ends, or you cancel now, and it becomes canceled. | Yes, until the period ends |
past_due | grace_period | A renewal invoice is overdue and grace is running. The label is the same when the subscription is set to cancel at the end of the period. | A renewal invoice is overdue and grace_enabled is true. | You report the payment, and it becomes active with the same period. Grace ends with the invoice still open, and it becomes canceled. | Yes while keeps_entitlements_in_grace is true, which is the default. Otherwise no. |
incomplete_expired | expired | The first invoice was not paid in time. The subscription never bills, and its invoice is void. | The time for an unpaid new subscription passes with no payment reported. | You report the invoice paid, however late, and it becomes active with a new period that starts at the report. In the cases in "Report each payment as soon as you take it" it stays here. | No |
canceled | expired | The subscription has ended, whatever the reason. Its end_reason says how. | Grace ends. An invoice is overdue with grace off. You cancel now. A subscription set to cancel reaches the end of its period. Or its customer is deleted or blocked. | You report its open invoice paid within the revival time, and it becomes active with a new period that starts at the report. In the cases in "Report each payment as soon as you take it" it stays here. | No |
A subscription gives the features of its product while it is active, set to cancel or not. It gives them while it is past_due as long as the environment's keeps_entitlements_in_grace is true. It never gives them while it is incomplete, incomplete_expired or canceled. You do not have to apply this rule yourself: GET /v1/active-entitlements?customer={id} answers with the features a customer has now.
A list of subscriptions leaves out the subscriptions that have ended, incomplete_expired and canceled, unless you filter with status=ended, with one status, or with status=all. A subscription set to cancel is active, so the list holds it without a filter.
Read how a subscription ended and how its grace stands
The subscription's body carries three more fields. They are in every event about the subscription too, as they were when Black recorded the event, and previous_attributes names them when they change.
end_reasonisnullwhile the subscription runs. Once it has ended, it says how:payment_failed(its grace ran out, or an invoice was overdue with grace off),first_invoice_unpaid(it becameincomplete_expired),canceled_now(you cancelled it now),period_end(it reached the end of a period you set it to cancel at),customer_deleted(its customer was deleted),customer_blocked(its customer was blocked) orrenewals_stopped(a renewal came while renewals were stopped). A subscription that a payment brings back readsnullagain.grace_period_endisnullunless the subscription ispast_due. Then it is the time grace ends, in Unix seconds.grace_keeps_entitlementsisnullunless the subscription ispast_due. Then it istrueorfalse: whether the subscription gives its features while its grace runs, as the environment'skeeps_entitlements_in_gracehas it when you read the subscription.
cancellation_reason is a separate field: it holds the reason given for a cancel. Black sets it itself when grace runs out (payment_failed) and in some other endings, and it stays null for a subscription that expired unpaid.
See the lifecycle
The lifecycle from creation to an active subscription, through grace and the cancels, to the end and to revival:
you create the subscription
|
v
+------------------+ unpaid time passes +--------------------+
| incomplete |--------------------->| incomplete_expired |
| (invoice open) | | (label expired) |
+------------------+ +--------------------+
| |
| you report the first | you report the invoice paid,
| invoice paid | however late
v |
+------------------+<-------------------------------+
| | renewal invoice overdue, +------------------+
| active | grace on | past_due |
| (renews each |------------------------------>| (grace_period) |
| period) |<------------------------------| |
+------------------+ you report the payment +------------------+
| ^ in grace (same period) |
| cancel | undo |
| at the | the cancel |
| period | |
| end | |
v | |
+------------------+ |
| active, set to | |
| cancel | |
| (pending_cancel) | |
+------------------+ |
| |
| the period ends | grace ends,
v | invoice open
+------------------------------------+ |
| canceled |<----------------------+
| (label expired) |<---- you cancel now, from incomplete,
+------------------------------------+ active, set to cancel or past_due
|
| you report its open invoice paid within the revival time
v
active again, with a new period that starts at the report
Two more ways end a subscription, and the diagram leaves them out so that it stays readable. A renewal invoice is overdue with grace off, which ends an active subscription at the due date. A customer is deleted or blocked.
Report each payment as soon as you take it
A payment counts from the moment you report it to Black, not from the moment your customer paid. Report each payment as soon as you take it, and never in a later batch, such as a nightly one.
The report decides what the payment does. A report that arrives late can come too late to bring a subscription back:
- A report that arrives after a subscription has ended for an unpaid invoice brings the subscription back only within the revival time,
revival_days, which is 7 days by default, counted from the time it ended. The subscription becomesactivewith a new period that starts at the report. - A report that arrives after that time records the invoice as paid, and a
canceledsubscription stayscanceled. - The first invoice of a subscription that expired unpaid,
incomplete_expired, is the exception: you report it paid, however late, and Black recordsinvoice.paid, thencustomer.subscription.updated. The subscription becomesactivewith a new period that starts at the report and lasts one interval, and its end is cleared. The customer paid what they owed, so the revival time does not apply. - With
revival_daysset to 0, a subscription is never brought back, an expired one included. - A subscription whose customer holds another live subscription is never brought back, an expired one included, because a customer holds one live subscription.
- A subscription whose customer is deleted is never brought back.
- A subscription that a block of its customer reached, or a chargeback, is never brought back. While the block stands, a report for any invoice of the customer's subscriptions is refused with
409and the codeblocked. After the block is removed, the report records the invoice as paid and the subscription stayscanceled.
When Black records a payment and the subscription stays ended, the invoice is paid and the money is yours to refund or to apply outside Black. The invoice of a revived subscription that expired unpaid is paid, and it keeps the time it was voided in voided_at.
Handle a repeat or a mistake
Send a payment_reference with each report. Black remembers the reference, so you can send a report again when you are not sure it arrived.
- A repeat. A report under the same invoice and the same
payment_referenceanswers the result of the first report, whatever its amount, date or note, with the headerIdempotent-Replayed: true. It never pays the invoice twice. The sameIdempotency-Keywith the same body answers the same result. - A wrong amount, currency or date. An
amountother than the invoice'samount_remaining, acurrencyother than the invoice's, or apaid_atlater than now is refused with422and the codeparameter_invalid, which names the field. Nothing is recorded. Correct the field and send the report again under the samepayment_reference. A key that Black has already seen with another body answers409with the codeidempotency_key_reused, so send the corrected report with a newIdempotency-Key, or with none. - An invoice that is already paid. A report for a paid invoice is refused with
409and the codeinvoice_already_paid. Check whether you reported the payment before. - A reference already used. A
payment_referencethat you used for another invoice of the environment is refused with409and the codepayment_reference_in_use. Send the reference of this payment.
A report that has no payment_reference and no Idempotency-Key is a new report each time, and a second one is refused as invoice_already_paid. See Errors for every code and Idempotency.
Handle an unpaid subscription
When you report no payment, two things happen on their own. The invoice becomes overdue at its due date, and Black records an invoice.overdue event. The subscription expires when the time for an unpaid new subscription passes: its status becomes incomplete_expired, its invoice becomes void, and Black records invoice.voided and customer.subscription.updated events. An expired subscription never bills.
You can still bring it back with a late report, as the section "Report each payment as soon as you take it" explains. A renewal that goes unpaid follows other rules: see "Handle an unpaid renewal".
Renew a subscription
An active subscription renews on its own at the end of each period. Black creates a new invoice for the next period, with one line for each item, and the subscription's latest_invoice is that invoice. Report its payment as you report the first one.
The invoice is due days_until_due days after it is finalized, and a subscription keeps the value it took at its creation. With the default of 1 the invoice is due one day after it is finalized. When you report the payment within the day, the subscription stays active, and Black records only an invoice.paid event. When the invoice is still unpaid at its due date, Black records invoice.overdue and, with grace_enabled true, the subscription enters grace: see "Handle an unpaid renewal". With 0 the invoice is due when it is finalized, so it is overdue at once and the subscription enters grace from the renewal. Set days_until_due to the days you need to collect the money before you create subscriptions.
A subscription set to cancel does not renew: it ends at the end of its period.
Handle an unpaid renewal
A renewal invoice that you do not report paid goes through these steps. Black retries nothing, because you collect the money: it waits for your report.
-
The renewal invoice is created. It is
open, and it is duedays_until_duedays after it is finalized. With the default of 1, it is due one day later; with 0, it is due at once. Black recordsinvoice.createdandinvoice.finalized. -
The due date passes with the invoice unpaid. With the default
days_until_dueof 1, this follows one day after the renewal; with 0 the due date is the renewal itself, so it follows at once. The invoice is overdue, and Black recordsinvoice.overdue. Withgrace_enabledtrue, the subscription becomespast_duewith the labelgrace_period, and Black recordscustomer.subscription.updated. Itsgrace_period_endis the due date plusgrace_length_days. Black reads the grace settings at the moment of the overdue. The subscription keeps giving its features whilekeeps_entitlements_in_graceistrue. -
You report the payment in grace. The subscription becomes
activeagain with the period it had, and Black recordsinvoice.paidandcustomer.subscription.updated. A second unpaid invoice of apast_duesubscription records onlyinvoice.overdueand runs its own grace, so the subscription becomesactiveonce no other invoice is in grace. Until then Black records onlyinvoice.paid. -
Grace ends with the invoice still open. The subscription becomes
canceledwith the labelexpired. Itscancellation_reasonand itsend_reasonarepayment_failed, itscanceled_atandended_atare the end of grace, and its period is unchanged. Black recordscustomer.subscription.deleted. The invoice staysopen, and Black bills nothing more. -
You report a payment after the end. Within the revival time, the subscription becomes
activefrom the report, with a new period that starts then. A late report does not bring acanceledsubscription back in four cases: the revival time has passed,revival_daysis 0, the customer holds another live subscription, or the customer is deleted. A subscription that a block of its customer reached is never brought back either. "Report each payment as soon as you take it" explains each.
With grace_enabled false, step 2 ends the subscription at the due date instead. Black records invoice.overdue and then customer.subscription.deleted, and the subscription is canceled with the reason payment_failed.
Collect the money from the customer during grace, and report the payment before grace_period_end. A report after that time is a late report.
Change the grace settings
The sample changes the length of grace and its retries, reads the settings back, and puts them back to their defaults. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes. The first two requests answer the environment's settings with grace_length_days at 30 and grace_retries at 5.
TOKEN=PLACEHOLDER_ACCESS_TOKEN
curl --silent --request PATCH https://api.black.example/v1/settings \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"grace_length_days":30,"grace_retries":5}'
curl --silent https://api.black.example/v1/settings \
--header "Authorization: Bearer $TOKEN"
curl --silent --request PATCH https://api.black.example/v1/settings \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"grace_length_days":15,"grace_retries":3}'
A change sends only the settings that change. A value out of its bounds is refused with 422 and the code parameter_invalid, which names the setting.
See how an invoice affects its subscription
The status of an invoice moves the status of its subscription in these cases:
| The invoice | Its status | What happens to the subscription |
|---|---|---|
| The first invoice, reported paid | paid | An incomplete subscription becomes active, in the period it was created with. |
| The first invoice, not paid in time | void | The subscription becomes incomplete_expired. |
| The first invoice, reported paid after that, however late | paid | The subscription becomes active again, with a new period that starts at the report. It stays incomplete_expired only in the cases in "Report each payment as soon as you take it". |
| A renewal invoice, reported paid before its due date | paid | The subscription stays active. Nothing else changes. |
| A renewal invoice, overdue with grace on | open | The subscription becomes past_due. |
| A renewal invoice, overdue with grace off | open | The subscription becomes canceled, with the reason payment_failed. |
| A renewal invoice, reported paid in grace | paid | The subscription becomes active again, in the period it had. |
| A renewal invoice, still open at the end of grace | open | The subscription becomes canceled, with the reason payment_failed. The invoice stays open. |
An open invoice of a canceled subscription, reported paid within the revival time | paid | The subscription becomes active again, with a new period that starts at the report. |
A runnable sample
The sample creates a customer, a product and a monthly price of 60 SAR, creates a subscription, reports its first invoice paid, and reads the subscription's status. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes, reads each ID from the response before it, and needs sed. A test environment takes five writes a second, so the sample waits a second between its writes.
TOKEN=PLACEHOLDER_ACCESS_TOKEN
CUSTOMER=$(curl --silent --request POST https://api.black.example/v1/customers \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"name":"Noor","email":"noor@example.com"}' \
| sed -n 's/.*"id":"\(cus_[0-9a-z]*\)".*/\1/p')
PRODUCT=$(curl --silent --request POST https://api.black.example/v1/products \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"name":"Prime Monthly"}' \
| sed -n 's/.*"id":"\(prod_[0-9a-z]*\)".*/\1/p')
PRICE=$(curl --silent --request POST https://api.black.example/v1/prices \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":6000,\"recurring\":{\"interval\":\"month\",\"interval_count\":1}}" \
| sed -n 's/.*"id":"\(price_[0-9a-z]*\)".*/\1/p')
SUBSCRIPTION_RESPONSE=$(curl --silent --request POST https://api.black.example/v1/subscriptions \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: noor-prime-monthly" \
--data "{\"customer\":\"$CUSTOMER\",\"items\":[{\"price\":\"$PRICE\"}]}")
SUBSCRIPTION=$(echo "$SUBSCRIPTION_RESPONSE" | sed -n 's/.*"id":"\(sub_[0-9a-z]*\)".*/\1/p')
INVOICE=$(echo "$SUBSCRIPTION_RESPONSE" | sed -n 's/.*"latest_invoice":"\(in_[0-9a-z]*\)".*/\1/p')
curl --silent --request POST https://api.black.example/v1/invoices/$INVOICE/mark-paid \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"amount":6000,"currency":"SAR","payment_reference":"noor-payment-1"}'
curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN"
The subscription request answers 201 with a subscription whose status is incomplete. The report answers 200 with the invoice, now paid. The last request answers 200 with the subscription, now active. To run the sample again in the same environment, change the Idempotency-Key of the subscription and the payment_reference of the report: Black refuses a key that it has seen with another body, and a reference that it has seen on another invoice.
What to do next
- Read how to retry a write safely in Idempotency.
- Read every event a subscription and its invoices record in Events.
- Read every error code in Errors.