Give a customer a plan for free and upgrade it
What you will build
You give a customer one term of a plan for free, read what the customer holds, and upgrade the customer to a paid plan. You learn that the free term never turns into a charge on its own, what the upgrade costs, which events Black records, and what each request refuses.
Before you start
You need a vendor's access token and a sub-account, with the sub-account's ID in the Black-Account header on every request. See Create and act for sub-accounts. You also need a product with a recurring price. The upgrade needs a second recurring price of the same product and currency, and of another interval than the first, as a yearly price for a monthly grant. See Authentication.
Only the vendor gives a free plan. The account's own client is refused with 403 and the code grant_by_vendor, whatever it sends.
You collect the money for the upgrade from your own customer, as in Change a customer's plan: the card, and the retry of a charge that fails, are on your side. Bookings, spending and savings are on your side too. Black does not hold them, and no call gives them.
Steps
-
Give the plan. Send a
POSTrequest to/v1/subscription-grantswith thepriceand one of two fields. Sendcustomer, the ID of an existing customer, orcustomer_reference, your own reference for the person, 1 to 255 characters once trimmed. A reference that no customer holds makes the customer. Send anIdempotency-Keyheader, so that you can repeat the request safely. The response answers201with the subscription. -
Read what the customer holds. The subscription is
activeat once. Itssourceisgrant, itslatest_invoiceisnull, and itscancel_at_period_endistrue, so it ends atcancel_at, the end of the term, which is one interval of the price from now. Itscancellation_reasonisgrant_ended, and itsstatus_labelisactive. Black makes no invoice, and the lookupGET /v1/active-entitlements?customer={id}gives the features of the plan withrenewsfalse. See Check what a customer holds. -
Read the events. Black records
customer.subscription.created, thencustomer.subscription.granted, thenentitlements.active_entitlement_summary.updated, in that order. The granted event is about the subscription, itsdata.ends_atis the end of the term in Unix seconds, and its actor is the vendor's client. A customer that the grant made hascustomer.createdbefore them. Read them withGET /v1/events?customer={id}. The activity log holds an entrysubscription.grantedwith the actor, the price andends_at: read it withGET /v1/activity-entries?customer={id}. -
Upgrade the customer to a paid plan. Send a
POSTrequest to/v1/subscriptions/{id}/change-planwith the newprice,whenset tonow, andauto_renew, which istrueorfalseand says whether the paid term renews. Black never fillsauto_renewfor you, so the customer's choice is always yours to send. The response holds the subscription, still on the free price, withprice_change_offerand alatest_invoice: anopeninvoice for the full price of the new plan. -
Collect the invoice from the customer, then report it paid. Send a
POSTrequest to/v1/invoices/{id}/mark-paidwith theamount, thecurrencyand apayment_reference. Read the subscription a few seconds later. It is on the new price,active, withsourcestillgrant.
Know what the customer is charged
A free plan never renews. Black sends no renewal reminder for it, makes no renewal invoice, and moves no price under it. At the end of the term the subscription reads canceled, its status_label is expired, and its end_reason is grant_ended. Black records customer.subscription.deleted, with the system as its actor, and empties the lookup. The customer may then be given a plan again, or may buy one.
The upgrade gives no credit for the free days. The offer holds one line, of type subscription_item, for the full price of the new plan, from the end of the free term for one interval of the new price. It holds no proration_credit line and no proration_charge line. The offer expires 23 hours after the request, or at the end of the free term if that is sooner, and Black then voids it.
When you report the offer paid, the free days that are left are kept. The paid term runs from the end of the free term for one interval of the new price, and the subscription's billing_cycle_anchor is the end of the free term. With auto_renew true the subscription renews at the end of the paid term. With auto_renew false Black sets the subscription to end there: a few seconds after the report its status_label is pending_cancel and its cancel_at is the end of the paid term.
Read the events an upgrade records
The offer records invoice.created and invoice.finalized, as any upgrade now does. The report records invoice.paid and customer.subscription.updated, for the move to the new price. With auto_renew false, Black then records a second customer.subscription.updated, for the end that it sets. See Events.
Handle a refusal
Each refusal gives an error with a code. See Errors for every code.
grant_by_vendor(403). The account's own client sent the request. Send it as the vendor, withBlack-Account.already_member(409). The customer holds a subscription that isincomplete,activeorpast_due.paramnamescustomerorcustomer_reference, whichever you sent. Wait for the subscription to end, or cancel it.blocked(409). The customer is blocked. See Block a customer.sales_closed(409). The account's service is off or its renewals are stopped. See Switch a service off and on.parameter_invalid(422). A field is wrong, you sent bothcustomerandcustomer_referenceor neither, or you sent a field the request does not take.paramnames it. On the upgrade it also means thatauto_renewis missing from a change now of a free plan, or that you sentauto_renewon any other subscription or withwhenperiod_end.resource_not_found(404). The customer or the price is unknown, deleted, or of another environment or account.subscription_granted(409). You sent an undo of a cancel for a free plan. It has nothing to undo.cancel_pending(409). You sent a cancel at the period's end, or a change at the period's end, for a free plan. It already ends at the end of the term.invoice_void(409). You reported an offer paid after Black voided it. The free term had already ended. Make the change again for a customer who holds a plan.
A runnable sample
The sample is a vendor's. It creates a sub-account, a product, a monthly price of 30 SAR and a yearly price of 300 SAR. It gives the monthly plan for free to a customer that it names by reference, reads the events and the activity entries, and reads the lookup. It then upgrades the customer to the yearly price with auto_renew set to false, reports the offer paid, and reads the subscription until it is pending_cancel. It writes PLACEHOLDER_VENDOR_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. Its names and references end in a number made from the time, so that it runs again.
TOKEN=PLACEHOLDER_VENDOR_ACCESS_TOKEN
RUN=$(date +%s)$RANDOM
ACCOUNT=$(curl --silent --request POST https://api.black.example/v1/vendor/accounts \
--header "Authorization: Bearer $TOKEN" \
--data name="Free Plan Demo $RUN" \
--data contact_email=owner@free-plan-demo.example \
--data external_reference=free-plan-demo-$RUN \
| sed -n 's/.*"id":"\(acct_[0-9a-z]*\)".*/\1/p')
PRODUCT=$(curl --silent --request POST https://api.black.example/v1/products \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT" \
--header "Content-Type: application/json" \
--data "{\"name\":\"Prime Free $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 "Black-Account: $ACCOUNT" \
--header "Content-Type: application/json" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":3000,\"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 "Black-Account: $ACCOUNT" \
--header "Content-Type: application/json" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":30000,\"recurring\":{\"interval\":\"year\",\"interval_count\":1}}" \
| sed -n 's/.*"id":"\(price_[0-9a-z]*\)".*/\1/p')
GRANT=$(curl --silent --request POST https://api.black.example/v1/subscription-grants \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: free-plan-grant-$RUN" \
--data "{\"customer_reference\":\"free-plan-guest-$RUN\",\"price\":\"$MONTHLY\"}")
SUBSCRIPTION=$(echo "$GRANT" | sed -n 's/.*"id":"\(sub_[0-9a-z]*\)".*/\1/p')
CUSTOMER=$(echo "$GRANT" | sed -n 's/.*"customer":"\(cus_[0-9a-z]*\)".*/\1/p')
curl --silent "https://api.black.example/v1/events?customer=$CUSTOMER" \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT"
curl --silent "https://api.black.example/v1/activity-entries?customer=$CUSTOMER" \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT"
curl --silent "https://api.black.example/v1/active-entitlements?customer=$CUSTOMER" \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT"
OFFER_RESPONSE=$(curl --silent --request POST https://api.black.example/v1/subscriptions/$SUBSCRIPTION/change-plan \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: free-plan-upgrade-$RUN" \
--data "{\"price\":\"$YEARLY\",\"when\":\"now\",\"auto_renew\":false}")
OFFER=$(echo "$OFFER_RESPONSE" | sed -n 's/.*"latest_invoice":"\(in_[0-9a-z]*\)".*/\1/p')
curl --silent --request POST https://api.black.example/v1/invoices/$OFFER/mark-paid \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT" \
--header "Content-Type: application/json" \
--data "{\"amount\":30000,\"currency\":\"SAR\",\"payment_reference\":\"free-plan-payment-$RUN\"}"
for attempt in 1 2 3 4 5 6 7 8 9 10; do
STATE=$(curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN" \
--header "Black-Account: $ACCOUNT")
if [[ "$STATE" == *'"status_label":"pending_cancel"'* ]]; then
break
fi
sleep 1
done
if [[ "$STATE" != *'"status_label":"pending_cancel"'* ]]; then
echo "The subscription is not set to end at the end of the paid term."
exit 1
fi
The first request answers 201 with the sub-account, and so do the creations of the product, the two prices and the grant. The other requests answer 200. The grant answers the subscription with source grant, status active and latest_invoice null. The events hold customer.created, customer.subscription.created, customer.subscription.granted and entitlements.active_entitlement_summary.updated, newest first, and the activity entries hold subscription.granted. The lookup holds the features of the product with renews false. The change answers the subscription with a price_change_offer of 30000 SAR and auto_renew false, the report answers the invoice, now paid, and the last read shows the yearly price, status active, source grant and status_label pending_cancel.
What to do next
- Read how an upgrade is offered and paid in Change a customer's plan.
- Read what the lookup answers for a free plan in Check what a customer holds.
- Read every event a free plan records in Events, and every error code in Errors.