Change a customer's plan
What you will build
You move a customer's subscription to another price in two ways. You upgrade it now: Black offers an invoice, you collect it and report it paid, and the subscription is on the new price from the report. You also set a change for the end of the period, and undo it before the period ends. You learn what the customer is charged and when, which events Black records, and what each request refuses.
Before you start
You need a test environment, an access token and a subscription that is active: create one and report its first invoice paid, as Create a subscription and report its payments explains. You also need a second recurring price of the same currency. See Authentication.
You collect the money from your own customer, so a change that costs money gives you an invoice to collect: the card, and the retry of a charge that fails, are on your side. Black gives the invoice and the events to act on.
Every request below is a POST request on the subscription. Send an Idempotency-Key header with each, so that you can repeat a request safely.
Steps
-
Choose when the change takes effect. Send a
POSTrequest to/v1/subscriptions/{id}/change-planwith thepriceto move to andwhen.whenis required and has no default, so a plan never changes at once because you left a field out.nowis an upgrade that the customer pays for.period_endis a change that the renewal makes. -
Upgrade now. Send
{"price":"price_…","when":"now"}. The price must be of another interval than the price the subscription is on, as a yearly price for a monthly subscription. The response holds the subscription, still on its old price with its period unchanged. Itslatest_invoiceis the offer, anopeninvoice with thebilling_reasonsubscription_update, and itsprice_change_offerholds the offer'sinvoice,price,amount_due,currencyandexpires_at. Black recordsinvoice.createdandinvoice.finalized. -
Collect the offer from the customer, then report it paid. Send a
POSTrequest to/v1/invoices/{id}/mark-paidwith the offer'samount_dueas theamount, itscurrencyand apayment_reference. The response holds the invoice, nowpaid. Read the subscription: it isactiveon the new price, with a new period that starts at the report, and itsprice_change_offerisnull. -
Set a change for the end of the period instead. Send
{"price":"price_…","when":"period_end"}. The response holds the subscription withpending_price_change: thepriceand theeffective_at, which iscurrent_period_end. Nothing is invoiced and nothing else changes. The customer keeps the old price and its features until the renewal, which bills the new price, moves the subscription to it and clears the change. Any recurring, active price of the same currency is taken, including one of the same interval. -
Undo a change set for the end of the period. Send a
POSTrequest to/v1/subscriptions/{id}/undo-plan-changewith no body. The response holds the subscription withpending_price_changenull, and it renews on its own price. The undo takes no field: apriceor awhensent to it is refused with422naming the field. -
Read the events in Events. The next sections say which each step records.
Read what the customer is charged
An upgrade now never charges the customer for the days already paid. The offer holds two lines: one for the new price, with the type subscription_item, and one below zero at the old price, with the type proration_credit, for the whole days left of the period the customer paid for. The day of the change is not counted. A monthly price of 3000 SAR paid the day before the change, with 29 whole days left in a month of 30 days, gives a credit line of -2900. A yearly price of 30000 SAR then gives an amount_due of 27100. Black works out the amounts: read amount_due from the offer, and never work it out yourself.
The customer pays the offer when you report it paid. From the report, the subscription is on the new price with a new period that starts then, and the next renewal bills the new price for the next period. A change for the end of the period charges nothing at the request. The renewal bills the new price in full, with one line on it and no credit.
An offer expires if you do not report it paid within unpaid_subscription_expiry_hours, 23 by default, or by the end of the period if that is sooner. expires_at says when. Black voids the offer, records invoice.voided, and changes nothing else. A report of the void offer within the revival time, in the same period, still makes the change from the report.
Upgrade a subscription whose month is unpaid
A subscription whose current period is unpaid, in grace (past_due) or open and not yet due, may be upgraded now too. It has no credit, because the customer has not paid for the days left. The offer holds the new price and a line above zero, with the type proration_charge, at the old price for the days of the period already used. The offer names the unpaid invoice it settles in price_change_offer.charged_invoice.
Either payment cancels the other, so the same days are never charged twice:
- You report the offer paid. The unpaid invoice is voided at the report, with
invoice.voided, and the subscription isactiveon the new price. - You report the unpaid invoice paid instead. Black voids the offer in the same step, and the customer stays on the old price. A report of the void offer is refused with
409and the codeinvoice_void, and Black records nothing. A new change gets the usual credit. If you collected both payments, refund one of them yourself.
Undo a change
A change for the end of the period has an undo. A cancel at the end of the period, a cancel now and every end of the subscription clear it too, and undoing the cancel does not bring it back.
An offer of an upgrade now has no undo. An undo while an offer is open is refused with 409 and the code price_change_not_pending. Leave the offer unpaid and it expires, or report it paid to make the change. A second change while the offer is open is refused with price_change_pending, so Black never makes two offers.
Read the events a change records
- An upgrade now records
invoice.createdandinvoice.finalizedat the request. The report recordsinvoice.paid, theninvoice.voidedwhen an unpaid invoice is voided, thencustomer.subscription.updated, with the earlieritems, the earlier period and the earlierprice_change_offerinprevious_attributes. When the features of the customer change, it also recordsentitlements.active_entitlement_summary.updated. The customer holds the old price's features until the report. - A change for the end of the period records
customer.subscription.updatedwithpending_price_changeset andprevious_attributes.pending_price_changenull. The undo records the same type, withpending_price_changenulland the earlier change inprevious_attributes. - The renewal that makes the change records
invoice.created,invoice.finalizedandcustomer.subscription.updated, with the earlieritemsandpending_price_changeinprevious_attributes. The renewal reminder,customer.subscription.renewal_upcoming, names the new price withprice_changestrue.
The activity log records subscription.price_change_offered, subscription.price_change_scheduled and subscription.price_change_undone. See Flag a customer and read the activity log.
Handle a refusal
Each refusal gives an error with a code. See Errors for every code.
parameter_invalid(422) namingwhenorprice.whenis missing or is neithernownorperiod_end, orpriceis missing. Send both.parameter_invalid(422) namingprice, for a change now to a price of the same interval as the subscription's. The message is "A change now to a price of the same interval is not available yet. Change the plan at the end of the period instead." Sendperiod_end, or choose a price of another interval fornow. The same code namespricefor a price that is charged once, one of another currency than the subscription's, and one longer than three years.resource_not_found(404) namingprice. The environment holds no such price.price_archivedandproduct_archived(409). The price, or its product, is archived. Make it active again, or choose another price.price_unchanged(409). The subscription is already on this price. Choose another.price_change_pending(409). An offer is open or a change for the end of the period is pending. Wait for the offer to expire, or undo the change.price_change_not_pending(409). You sent an undo, and no change for the end of the period is pending. An open offer cannot be undone.invoice_open(409). A change for the end of the period needs every invoice paid, and a change now needs every earlier invoice paid. Report the open invoice paid, then send the change again.credit_exceeds_charge(409). The credit for the days left is larger than the new price, so the plan cannot change now. Change it at the end of the period.cancel_pending(409). The subscription is set to cancel at the end of the period, so it takes no change for that time. Undo the cancel first.subscription_incomplete(409). Its first invoice is not paid. Report it paid first.subscription_ended(409). The subscription has ended, so it takes no change and no undo.subscription_has_several_items(409). Only a subscription of one item changes plan.renewal_dueandrenewal_deferred(409). The period's renewal has not run yet, or waits until the service is on again. Send the request again with the sameIdempotency-Keyonce the renewal has run.blocked(409). The customer is blocked. See Block a customer.
A refusal that depends on time, such as renewal_due, price_change_pending and credit_exceeds_charge, is not kept for its Idempotency-Key, so the same request runs again when the cause has gone.
PATCH /v1/subscriptions/{id} refuses items and price with 422 and points to change-plan.
A runnable sample
The sample creates a customer, a product, a monthly price of 60 SAR and a yearly price of 600 SAR, creates a subscription and reports its first invoice paid. It then upgrades the subscription to the yearly price now, reads the amount to collect from the offer and reports the offer paid. It sets a change back to the monthly price for the end of the period, reads it and undoes it. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes, reads each ID and the amount 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. Its keys and references end in a number made from the time, so that it runs again in the same environment.
TOKEN=PLACEHOLDER_ACCESS_TOKEN
RUN=$(date +%s)$RANDOM
CUSTOMER=$(curl --silent --request POST https://api.black.example/v1/customers \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"name":"Sara","email":"sara@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 Plan Change $RUN\"}" \
| sed -n 's/.*"id":"\(prod_[0-9a-z]*\)".*/\1/p')
MONTHLY=$(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')
YEARLY=$(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\":60000,\"recurring\":{\"interval\":\"year\",\"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: sara-plan-subscription-$RUN" \
--data "{\"customer\":\"$CUSTOMER\",\"items\":[{\"price\":\"$MONTHLY\"}]}")
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\":\"sara-plan-first-$RUN\"}"
OFFER_RESPONSE=$(curl --silent --request POST https://api.black.example/v1/subscriptions/$SUBSCRIPTION/change-plan \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: sara-plan-now-$RUN" \
--data "{\"price\":\"$YEARLY\",\"when\":\"now\"}")
OFFER=$(echo "$OFFER_RESPONSE" | sed -n 's/.*"latest_invoice":"\(in_[0-9a-z]*\)".*/\1/p')
AMOUNT=$(echo "$OFFER_RESPONSE" | sed -n 's/.*"price_change_offer":{[^}]*"amount_due":\([0-9]*\).*/\1/p')
curl --silent --request POST https://api.black.example/v1/invoices/$OFFER/mark-paid \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"amount\":$AMOUNT,\"currency\":\"SAR\",\"payment_reference\":\"sara-plan-upgrade-$RUN\"}"
curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN"
curl --silent --request POST https://api.black.example/v1/subscriptions/$SUBSCRIPTION/change-plan \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: sara-plan-period-end-$RUN" \
--data "{\"price\":\"$MONTHLY\",\"when\":\"period_end\"}"
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-plan-change \
--header "Authorization: Bearer $TOKEN" \
--header "Idempotency-Key: sara-plan-undo-$RUN"
curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN"
Each request answers 200, except the creations, which answer 201. The upgrade answers the subscription with a price_change_offer, and the report of the offer answers the invoice, now paid. The read after it shows the subscription on the yearly price with price_change_offer null. The change for the end of the period answers pending_price_change with the monthly price, and the read after it shows the same. The undo answers pending_price_change null, and the last read shows the same.
What to do next
- Read how a subscription is cancelled at the end of its period, and how a cancel is undone, in Cancel a subscription.
- Move time forward to see a change take effect at a renewal in Test your integration with test clocks.
- Read how to retry a write safely in Idempotency.
- Read every event a change records in Events, and every error code in Errors.