Cancel a subscription
What you will build
You cancel a subscription at the end of its current period, read that it is set to cancel, undo the cancel, and then cancel the subscription at once. You also learn what each request refuses and why, and what happens to a cancelled subscription's unpaid invoice.
Before you start
You need a test environment and an access token. See Authentication. You also need a subscription: create one and report its first invoice paid, as Create a subscription and report its payments explains.
Both cancels and the undo are POST requests on the subscription. Send an Idempotency-Key header with each, so that you can repeat a request safely.
Steps
-
Cancel at the end of the period. Send a
POSTrequest to/v1/subscriptions/{id}/cancelwith{"when":"period_end"}. The response holds the subscription: itsstatusis stillactive, itsstatus_labelispending_cancel,cancel_at_period_endistrue, andcancel_atis the end of the current period, the same time ascurrent_period_end. Black recordscustomer.subscription.updated, withcancel_at_period_endinprevious_attributes. -
Read what the customer keeps. The customer keeps the features of the product until
cancel_at, and Black bills nothing more. Atcancel_atthe subscription ends: its status becomescanceled, its label becomesexpired, and Black recordscustomer.subscription.deleted. The subscription isactiveuntil then, soGET /v1/subscriptionslists it without astatusfilter. In the lookupGET /v1/active-entitlements?customer={id}, the subscription'srenewsisfalsewhile the cancel is set. -
Undo the cancel if the customer stays. Send a
POSTrequest to/v1/subscriptions/{id}/undo-cancelwith no body. The response holds the subscription withcancel_at_period_endfalse, andcancel_at,cancellation_reasonandcancellation_commentarenull. The subscription renews as before, and Black takes no payment for the undo. Black recordscustomer.subscription.updated. -
Cancel at once. Send a
POSTrequest to/v1/subscriptions/{id}/cancelwith{"when":"now"}. The response holds the subscription: itsstatusiscanceled, itsstatus_labelisexpired, itscanceled_atandended_atare the time of the request, and itsend_reasoniscanceled_now. Black refunds nothing, creates no further invoice and drops every step still scheduled for the subscription. It recordscustomer.subscription.deleted.
Choose when to cancel
when is required and has no default, so a subscription never ends at once because you left a field out.
period_endkeeps the customer's access until the end of the period they paid for. Use it when a customer asks to stop.nowends the subscription and its access at once. Use it when the customer must not keep the features, or to end a subscription that is stillincomplete.
A cancel at the end of the period needs a subscription that has been paid: an incomplete subscription is refused. A past_due subscription takes either cancel, and keeps the label grace_period while it is set to cancel.
Give a reason and a comment
A cancel may carry a cancellation_reason and a cancellation_comment. The reason is one of too_expensive, missing_features, switched_service, unused, customer_service, low_quality, too_complex or other. The comment is 1 to 500 characters and is kept beside the reason.
A cancel that gives no reason records the reason not_given. Black alone sets payment_failed, not_given, renewals_stopped, blocked and customer_deleted, so a request that sends one of them is refused. The subscription's cancellation_reason holds the reason, and cancellation_comment the comment, from the cancel at the end of the period until the subscription ends or you undo the cancel, and after it ends. The undo takes no field: a cancellation_reason or a cancellation_comment sent to it is refused.
Require a reason
The setting cancellation_reason_required is false by default. Change it with PATCH /v1/settings. While it is true, a cancel with no cancellation_reason is refused with 422 naming cancellation_reason, and so is a cancel with the reason other and no cancellation_comment, which is refused naming cancellation_comment. The setting applies to both kinds of cancel, and to a cancel now of a subscription that is already set to cancel. An undo needs no reason. Send the reason, and the comment for other, and send the cancel again.
Handle a refusal
Each refusal gives an error with a code. See Errors for every code.
subscription_ended(409). The subscription has ended: it iscanceledorincomplete_expired, or its end has passed and Black has not yet recorded it. A subscription that has ended takes no cancel and no undo. Read it withGET /v1/subscriptions/{id}. If its customer should subscribe again, create a new subscription.subscription_incomplete(409). You asked to cancel anincompletesubscription at the end of the period, and its first invoice is not paid. Cancel it now with{"when":"now"}, or report the first invoice paid and cancel then.cancel_pending(409). The subscription is already set to cancel at the end of the period. Sendundo-cancelfirst if you want another cancel, or leave it as it is.cancel_not_pending(409). You sent an undo for a subscription that is not set to cancel. Read the subscription: itscancel_at_period_endisfalse, so there is nothing to undo.renewal_due(409). You asked to cancel at the end of the period in the second or so between the end of a period and the run of its renewal. Black has recorded nothing. Send the request again a moment later with the sameIdempotency-Key. Once the renewal has run, the cancel is set at the end of the new period.parameter_invalid(422) namingwhen. The field is missing or is neithernownorperiod_end. Send one of the two.parameter_invalid(422) namingcancellation_reason. The cause is one of three. The reason is not one of the eight: send one from the list.cancellation_reason_requiredistrueand you sent none: send a reason. Or you sent a reason toundo-cancel: send the undo with no body.parameter_invalid(422) namingcancellation_comment. The cause is one of three. The comment is empty or longer than 500 characters: send one of 1 to 500 characters, or none. It is missing with the reasonotherwhilecancellation_reason_requiredistrue: send a comment. Or you sent it toundo-cancel: send the undo with no body.
A subscription of a customer that your account has blocked takes no undo: it is refused with 409 and the code blocked. A cancel is never refused because of a block.
Repeat a request safely
Send an Idempotency-Key with each cancel and each undo. A request that you repeat with the same key and the same body answers what the first one answered, marked with the header Idempotent-Replayed: true, and changes nothing a second time. The same key with another body is refused with 409 and the code idempotency_key_reused. See Idempotency.
Without a key, the state of the subscription stops a double: a second cancel at the end of the period is refused cancel_pending, a second cancel now is refused subscription_ended, and a second undo is refused cancel_not_pending.
Bring back a cancelled subscription
A cancelled subscription leaves its unpaid invoice open. Black voids nothing and refunds nothing. When you report that invoice paid with POST /v1/invoices/{id}/mark-paid within the revival time, revival_days, which is 7 days by default, counted from the end, the subscription comes back whatever reason you gave. It is active from the report, with a new period that starts then, and its end, its reason and its comment are cleared. After that time the invoice is recorded as paid and the subscription stays canceled. A subscription whose customer is deleted or blocked is never brought back: see "Report each payment as soon as you take it" in Create a subscription and report its payments.
Read the events a cancel records
A cancel at the end of the period records customer.subscription.updated, and previous_attributes.cancel_at_period_end is false. An undo records the same type, and previous_attributes.cancel_at_period_end is true. A cancel now, and the end of a subscription at the end of its period, record customer.subscription.deleted.
When the features of the customer change, Black also records entitlements.active_entitlement_summary.updated. A cancel now, the end of a subscription at the end of its period and a revival record it. A cancel at the end of the period and an undo record none, because the features stay the same. See Events.
A runnable sample
The sample creates a customer, a product and a monthly price of 60 SAR, creates a subscription, and reports its first invoice paid. It then cancels the subscription at the end of the period with a reason and a comment, reads it, undoes the cancel, and cancels it now. 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 after each write.
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":"Lina","email":"lina@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 Cancel 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: lina-cancel-subscription" \
--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":"lina-cancel-payment-1"}'
curl --silent --request POST https://api.black.example/v1/subscriptions/$SUBSCRIPTION/cancel \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: lina-cancel-period-end" \
--data '{"when":"period_end","cancellation_reason":"too_expensive","cancellation_comment":"Moving to the yearly plan later"}'
curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN"
curl --silent --request POST https://api.black.example/v1/subscriptions/$SUBSCRIPTION/undo-cancel \
--header "Authorization: Bearer $TOKEN" \
--header "Idempotency-Key: lina-cancel-undo"
curl --silent --request POST https://api.black.example/v1/subscriptions/$SUBSCRIPTION/cancel \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: lina-cancel-now" \
--data '{"when":"now","cancellation_reason":"unused"}'
curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN"
Each request answers 200, except the creation of the subscription, which answers 201. The first cancel answers the subscription with status active, status_label pending_cancel and cancel_at_period_end true, and the read after it shows the same. The undo answers it with cancel_at_period_end false. The cancel now answers it with status canceled and status_label expired, and the last read shows the same. To run the sample again in the same environment, change the names that start lina-cancel: 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 a subscription becomes
past_dueand what happens at the end of its grace in Create a subscription and report its payments. - Read how to retry a write safely in Idempotency.
- Read every event a cancel records in Events.
- Read every error code in Errors.