Test your integration with test clocks
What you will build
You make a test clock, put a customer on it, and move its time forward past a renewal, so that you test in seconds what takes a month. You learn what moves with the clock and what keeps the real time, and you follow one example from a first payment to a renewal.
Before you start
You need a test environment and an access token of a test client. See Authentication. Every test clock request with a live token is refused with 403 and the code test_mode_required.
A clock holds at most 3 customers, and a customer on a clock at most 3 subscriptions. A test environment holds at most 100 clocks, and Black deletes a clock 30 days after you make it, with its customers.
Attach the features to your products before you make a clock. Start the clock at the real time or later: a feature that you attach today is seen by a clock set in the past only once it passes today.
Steps
-
Make a clock. Send a
POSTrequest to/v1/test-clockswith anameof 1 to 255 characters and afrozen_time, a time in Unix seconds. The response holds the clock: itsidstarts withclock_, itsstatusisready, and itsdeletes_atis 30 days after its creation. Black recordstest_clock.created. -
Put a customer on the clock. Send a
POSTrequest to/v1/customerswithtest_clockset to the clock's ID. You do this only when you create the customer: an update that sendstest_clockis refused with422. The customer'screatedis the clock'sfrozen_time. A fourth customer for a clock is refused with409and the codetest_clock_limit_reached. -
Create the customer's subscription and report its first invoice paid, as Create a subscription and report its payments explains. The subscription's period starts at the clock's time, and a payment that you report without
paid_atis paid at the clock's time. -
Advance the clock. Send a
POSTrequest to/v1/test-clocks/{id}/advancewith afrozen_timethat is not before the clock's own, as a time one second after the end of the period. The response holds the clock with thestatusadvancing, itsfrozen_timeunchanged andadvancing_tothe time it moves to. Black recordstest_clock.advancing. -
Read the clock until it is ready. Send a
GETrequest to/v1/test-clocks/{id}once a second until itsstatusisready. It takes a few seconds. Itsfrozen_timeis then the new time, and Black recordstest_clock.ready. A clock that stops with thestatusinternal_failurekeeps its old time, and its customers can no longer be changed: delete it and start again. -
Read what moved. Read the subscription, its invoices and its events: everything that fell due up to the new time has run, in order.
-
Delete the clock when you are done. Send a
DELETErequest to/v1/test-clocks/{id}. The response hasdeletedtrue, and the clock and its customers then answer404. Their events and activity entries stay. A clock that is advancing is not deleted.
Rename a clock with a PATCH request to /v1/test-clocks/{id} that sends only name. List your clocks with GET /v1/test-clocks.
Know what moves with the clock
Everything that Black dates for a customer on the clock is dated by the clock: the subscription's created, its period and its anchor, an invoice's created, finalized_at, due_date and paid_at, and the canceled_at and ended_at of an end. When you advance the clock, Black runs what falls due in order:
- A renewal creates the next invoice and the next period.
- The reminder before a renewal,
customer.subscription.renewal_upcoming, is recorded when the clock passes the lead time, and not before. - An invoice that is unpaid at its due date becomes overdue,
invoice.overdue, and with grace on the subscription becomespast_due. - Grace ends: the subscription becomes
canceledwith theend_reasonpayment_failed. - A subscription set to cancel at the end of the period ends at it.
- An unpaid first invoice expires, and so does an unpaid offer of an upgrade.
Know what does not move
The application's own records keep the real time, whatever the clock says: an event's created, so the 30 days of the event list and its date filters read the real time, the activity entries, the idempotency keys, the access tokens and the delivery of events to your endpoints. A customer on no clock lives in the real time as before. The clock moves forward only. Time on a clock passes only when you advance it, and nothing runs between two advances.
An advance may move the clock by at most two periods of the shortest subscription on it that has not ended, or by two years when it has none. A target before the clock's own time, or further than that, is refused with 422 naming frozen_time. Move in smaller steps.
Handle a request while the clock moves
While a clock is advancing, another advance, its deletion, and every write about its customers (a subscription, a report of payment, a cancel, a change of plan, a deletion) are refused with 409 and the code test_clock_advancing, and Black saves nothing. Reads and the rename answer as usual. Read the clock until it is ready, then send the request again. Black does not keep the refusal for the Idempotency-Key, so the same request with the same key runs again once the clock is ready.
Follow a worked example
The example follows one customer from a first payment to a renewal, with the default days_until_due of 1.
-
You make a clock whose
frozen_timeis now, and a customer on it. You create a subscription to a monthly price of 60 SAR and report its first invoice paid. The subscription isactive, and itscurrent_period_endis one month after the clock's time. -
You advance the clock to one second after
current_period_end, and read the clock until it isready. On the way the clock passed the reminder date, 7 days before the renewal by default, so Black recordedcustomer.subscription.renewal_upcoming. Then the renewal ran: the subscription isactivein a new period of a month, and itslatest_invoiceis a newopeninvoice of 6000, with thebilling_reasonsubscription_cycle, due one day after the renewal. Black recordedinvoice.created,invoice.finalizedandcustomer.subscription.updated. -
You report the renewal invoice paid. It is
paidat the clock's time, and the subscription staysactive.
When you leave the renewal invoice unpaid, advancing the clock past the due date records invoice.overdue and makes the subscription past_due with the label grace_period. Advancing past grace_period_end ends it as canceled, with the invoice still open. A subscription takes days_until_due when you create it. Change the setting with PATCH /v1/settings before you create the subscription, and put it back afterwards, because it applies to the whole environment.
A runnable sample
The sample creates a product and a monthly price of 60 SAR, makes a test clock set to the real time, and creates a customer on it with a subscription whose first invoice it reports paid. It reads the subscription's current_period_end, advances the clock to one second after it, reads the clock until it is ready, reads the renewed subscription and the reminder, reports the renewal invoice paid and deletes the clock. 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. 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
PRODUCT=$(curl --silent --request POST https://api.black.example/v1/products \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"name\":\"Prime Clock $RUN\"}" \
| 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')
NOW=$(date +%s)
CLOCK=$(curl --silent --request POST https://api.black.example/v1/test-clocks \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: clock-create-$RUN" \
--data "{\"name\":\"Renewal test $RUN\",\"frozen_time\":$NOW}" \
| sed -n 's/.*"id":"\(clock_[0-9a-z]*\)".*/\1/p')
CUSTOMER=$(curl --silent --request POST https://api.black.example/v1/customers \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"name\":\"Rana\",\"email\":\"rana@example.com\",\"test_clock\":\"$CLOCK\"}" \
| sed -n 's/.*"id":"\(cus_[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: rana-clock-subscription-$RUN" \
--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\":\"rana-clock-first-$RUN\"}"
PERIOD_END=$(curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN" \
| sed -n 's/.*"current_period_end":\([0-9]*\).*/\1/p')
RENEWAL_TIME=$((PERIOD_END + 1))
curl --silent --request POST https://api.black.example/v1/test-clocks/$CLOCK/advance \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--header "Idempotency-Key: clock-advance-$RUN" \
--data "{\"frozen_time\":$RENEWAL_TIME}"
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
sleep 1
STATE=$(curl --silent https://api.black.example/v1/test-clocks/$CLOCK \
--header "Authorization: Bearer $TOKEN")
if [[ "$STATE" == *'"status":"ready"'* ]]; then
break
fi
done
if [[ "$STATE" != *'"status":"ready"'* ]]; then
echo "The clock is not ready."
exit 1
fi
RENEWED=$(curl --silent https://api.black.example/v1/subscriptions/$SUBSCRIPTION \
--header "Authorization: Bearer $TOKEN")
RENEWAL_INVOICE=$(echo "$RENEWED" | sed -n 's/.*"latest_invoice":"\(in_[0-9a-z]*\)".*/\1/p')
curl --silent "https://api.black.example/v1/events?type=customer.subscription.renewal_upcoming&customer=$CUSTOMER" \
--header "Authorization: Bearer $TOKEN"
curl --silent --request POST https://api.black.example/v1/invoices/$RENEWAL_INVOICE/mark-paid \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"amount\":6000,\"currency\":\"SAR\",\"payment_reference\":\"rana-clock-renewal-$RUN\"}"
curl --silent --request DELETE https://api.black.example/v1/test-clocks/$CLOCK \
--header "Authorization: Bearer $TOKEN"
Each request answers 200, except the creations, which answer 201. The advance answers the clock with the status advancing, and the clock is read until it is ready. The renewed subscription is active with current_period_start at the clock's new time, and its latest_invoice is the open renewal invoice. The reminder is listed, the report answers the invoice, now paid, and the deletion answers deleted true.
What to do next
- Read how a change of plan takes effect at a renewal in Change a customer's plan.
- Read how an unpaid renewal goes through grace in Create a subscription and report its payments.
- Read every test clock event in Events, and every error code in Errors.