Let a signed-in customer subscribe and manage their subscription
What you will build
You build the pages where a signed-in customer previews a price, subscribes to it, cancels their subscription at the end of its period, undoes that cancel and moves to another plan.
These routes are for an account that collects its own payments, which is the account_collects payment mode. Black takes no payment through them: there is no card, and no charge. Where Black charges the card (black_charges), every subscribe and every change of plan through these routes is refused with 422 and card_payment_not_supported. There, the customer subscribes with a card through Build a hosted checkout page, and the account changes the plan from its server.
Every call here comes from the customer's own page or app, with the customer's session, and never from your server. No path carries a customer ID: Black answers for the customer the session belongs to, and for no other.
Before you start
You need an app with a publishable key, in the environment where the customer signs in: see Register an app and Create a publishable key. Your page or app sends the key in the Black-Publishable-Key header, and a web page is called from one of the app's allowed origins.
You need the environment's payment_mode to be account_collects, as Change account settings explains. That is the value an environment starts with.
You need a product with at least two prices on sale: see Create a product and its prices.
You need a customer session. Sign the customer in with one of the sign-in guides, or make the session from your server, as Start, refresh and end a customer session shows: your server makes a sign-in token for the customer, and the page exchanges it for the session. Keep the session's access_token where your page or app keeps its session.
Steps
Send the publishable key in Black-Publishable-Key and the access token as Authorization: Bearer <access token> in every call below. Send an Idempotency-Key with each write: Black keeps it per customer, so two customers who send the same key never wait on each other, and a retry with the same key answers what the first try did.
Preview a price
-
Ask what the price costs the customer. Send a
POSTrequest to/v1/client/subscription-previewswith theprice. The response is200and holds thesubtotal, thetax, thetotal_excluding_taxand thetotal, in the price's currency, andpayment_method_required, which isfalsewhere the account collects. Nothing is saved. See Preview the subscription of the session's customer.The tax is quoted for the country of the customer's address, never one the page sends. Where the account fixes one tax country in its tax setup, the quote is for that country. A customer with no country, where no tax country is fixed, is refused with
422andcustomer_country_required: add the country to the customer's address, then ask again.
Subscribe
- Subscribe the customer. Send a
POSTrequest to/v1/client/subscriptionswith theprice, andconsent_acceptedset totruewhen the account's settings ask for consent. The response is201and holds the subscription. The customer pays nothing through this call: the account collects. A body that names acustomer,items,collection_method, a currency, a payment method or a card field is refused with422that names the field. See Create a subscription for the session's customer.
Cancel and undo the cancel
A subscription is incomplete until the account reports its first invoice paid from its server, as Create a subscription and report its payments explains. Until then, a cancel or a change of plan is refused with 409 and subscription_incomplete.
-
Cancel at the end of the period. Send a
POSTrequest to/v1/client/subscriptions/{subscriptionId}/cancel. Send acancellation_reasonthe customer picks, and acancellation_commentif you ask for one. The reason is required when the environment asks for one. The response is200and shows the subscription as one that ends at the period end. The customer keeps what it gives until then. Awhenofnowis refused with422, because ending a subscription at once stays the account's. See Cancel the subscription of the session's customer. -
Undo the cancel. Send a
POSTrequest to/v1/client/subscriptions/{subscriptionId}/undo-cancelwith no body, before the period ends. The response is200and shows the subscription as one that renews. See Undo the cancel of the session's customer.
Change plan
- Move the customer to another price. Send a
POSTrequest to/v1/client/subscriptions/{subscriptionId}/change-planwith the newpriceandwhen, eithernoworperiod_end. A changenowanswers200with the change's offer, an invoice with no charge, because the account collects the money. A change atperiod_endis set for the renewal. See Change the plan of the session's customer.
A subscription of another customer answers 404 with resource_not_found, the same answer as an ID that does not exist.
Call the routes from a page
The page sends the session and the key on every call. This function wraps them, and sends a fresh Idempotency-Key for each write:
const BLACK = 'https://api.black.example';
const PUBLISHABLE_KEY = 'pk_test_…';
async function black(path, body, accessToken) {
const response = await fetch(`${BLACK}${path}`, {
method: 'POST',
headers: {
'Black-Publishable-Key': PUBLISHABLE_KEY,
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Idempotency-Key': crypto.randomUUID(),
},
body: JSON.stringify(body ?? {}),
});
return { status: response.status, body: await response.json() };
}
Show the price, then subscribe, and cancel or change plan from the subscription's own id:
const preview = await black('/v1/client/subscription-previews', { price: priceId }, accessToken);
const subscribed = await black('/v1/client/subscriptions', { price: priceId }, accessToken);
const id = subscribed.body.id;
await black(`/v1/client/subscriptions/${id}/cancel`, { cancellation_reason: 'unused' }, accessToken);
await black(`/v1/client/subscriptions/${id}/undo-cancel`, {}, accessToken);
await black(`/v1/client/subscriptions/${id}/change-plan`, { price: otherPriceId, when: 'now' }, accessToken);
Reuse one Idempotency-Key only to retry the same write, for example after a lost answer.
Handle each refusal
Each refusal is an error with a code: see Errors for every code.
422card_payment_not_supported. The environment'spayment_modeisblack_charges, so Black would charge a card, and these routes take none. Nothing was kept. Send the customer to your hosted checkout page to subscribe, and change the plan from your server.409subscription_incomplete. The subscription's first invoice is not paid. Report the payment from your server, then send the request again.404resource_not_found. The subscription is not the customer's, or does not exist. Read the customer's subscriptions again.422parameter_invalid. A field is wrong. The error'sparamnames it: a field the customer may not send, acancellation_reasonthat is not one of the listed values, or awhenofnowon a cancel.422customer_country_required. The customer has no country and the account fixes none. Add the country to the customer's address.409sales_closed. The account has closed sales. Show the customer that subscribing is closed for now.409tax_not_determined. The tax service cannot determine the tax. Where the error namestax_country, the account's own tax setup is the cause, and only the account fixes it: see Build a hosted checkout page.401. The session is missing, expired or ended. Ask the customer to sign in again, or renew the session with its refresh token.
A runnable sample
The sample makes an app and its publishable key, a product with a monthly and a yearly price, and a customer. It makes the customer's sign-in token on the server and exchanges it for a session, as the page does. It then previews the monthly price and subscribes, reports the first invoice paid from the server, as the account does when it takes the money, cancels at the period end, undoes the cancel and changes the plan to the yearly price at once. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes, reads the IDs, the key and the session from the responses, and needs sed. The names are made new on each run, and the sample waits a second between calls, because a test environment takes five writes a second for the account and five for a customer's session.
TOKEN=PLACEHOLDER_ACCESS_TOKEN
RUN=$(date +%s)$RANDOM
API=https://api.black.example
S=(--header "Authorization: Bearer $TOKEN" --header "Content-Type: application/json")
APP=$(curl --silent --request POST $API/v1/apps "${S[@]}" \
--data '{"name":"Own Subscription Demo","kind":"web","allowed_origins":["https://app.example.com"]}' \
| sed -n 's/.*"id":"\(app_[0-9a-z]*\)".*/\1/p')
sleep 1
KEY=$(curl --silent --request POST "$API/v1/apps/$APP/publishable-keys" "${S[@]}" \
| sed -n 's/.*"\(pk_test_[0-9A-Za-z]*\)".*/\1/p')
sleep 1
PRODUCT=$(curl --silent --request POST $API/v1/products "${S[@]}" \
--data "{\"name\":\"Own Subscription $RUN\"}" \
| sed -n 's/.*"id":"\(prod_[0-9a-z]*\)".*/\1/p')
sleep 1
MONTHLY=$(curl --silent --request POST $API/v1/prices "${S[@]}" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":6000,\"recurring\":{\"interval\":\"month\",\"interval_count\":1}}" \
| sed -n 's/.*"id":"\(price_[0-9a-z]*\)".*/\1/p')
sleep 1
YEARLY=$(curl --silent --request POST $API/v1/prices "${S[@]}" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":60000,\"recurring\":{\"interval\":\"year\",\"interval_count\":1}}" \
| sed -n 's/.*"id":"\(price_[0-9a-z]*\)".*/\1/p')
sleep 1
curl --silent --request POST $API/v1/customers "${S[@]}" \
--data "{\"name\":\"Sana\",\"email\":\"own-sub-$RUN@example.com\",\"external_reference\":\"own-sub-$RUN\"}"
sleep 1
SIGN_IN_TOKEN=$(curl --silent --request POST $API/v1/customer-sessions "${S[@]}" \
--data "{\"customer_reference\":\"own-sub-$RUN\"}" \
| sed -n 's/.*"token":"\(cst_[0-9A-Za-z]*\)".*/\1/p')
sleep 1
ACCESS=$(curl --silent --request POST $API/v1/client/auth/token \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com" \
--header "Content-Type: application/json" \
--data "{\"token\":\"$SIGN_IN_TOKEN\"}" \
| sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')
C=(--header "Black-Publishable-Key: $KEY" --header "Origin: https://app.example.com" \
--header "Authorization: Bearer $ACCESS" --header "Content-Type: application/json")
curl --silent --request POST $API/v1/client/subscription-previews "${C[@]}" \
--header "Idempotency-Key: preview-$RUN" \
--data "{\"price\":\"$MONTHLY\"}"
SUBSCRIBED=$(curl --silent --request POST $API/v1/client/subscriptions "${C[@]}" \
--header "Idempotency-Key: subscribe-$RUN" \
--data "{\"price\":\"$MONTHLY\"}")
SUBSCRIPTION=$(echo "$SUBSCRIBED" | sed -n 's/.*"id":"\(sub_[0-9a-z]*\)".*/\1/p')
INVOICE=$(curl --silent "$API/v1/subscriptions/$SUBSCRIPTION" "${S[@]}" \
| sed -n 's/.*"latest_invoice":"\(in_[0-9a-z]*\)".*/\1/p')
curl --silent --request POST "$API/v1/invoices/$INVOICE/mark-paid" "${S[@]}" \
--data "{\"amount\":6000,\"currency\":\"SAR\",\"payment_reference\":\"own-sub-$RUN\"}"
sleep 1
curl --silent --request POST "$API/v1/client/subscriptions/$SUBSCRIPTION/cancel" "${C[@]}" \
--header "Idempotency-Key: cancel-$RUN" \
--data '{"cancellation_reason":"unused"}'
curl --silent --request POST "$API/v1/client/subscriptions/$SUBSCRIPTION/undo-cancel" "${C[@]}" \
--header "Idempotency-Key: undo-$RUN"
sleep 1
curl --silent --request POST "$API/v1/client/subscriptions/$SUBSCRIPTION/change-plan" "${C[@]}" \
--header "Idempotency-Key: change-$RUN" \
--data "{\"price\":\"$YEARLY\",\"when\":\"now\"}"
The app, its key, the product, the two prices, the customer, the sign-in token and the session answer 201. The preview answers 200, the subscribe 201, the report of the payment 200, and the cancel, the undo and the change of plan 200.
What to do next
- Read how a customer sees their own account, cards and invoices in Show a signed-in customer their own account.
- Read how a customer subscribes with a card, where Black charges it, in Build a hosted checkout page.
- Read how the account cancels and changes a plan from its server in Cancel a subscription and Change a customer's plan.
- Read every error code in Errors.