Call Black from a customer's page or app
What you will build
You decide which calls your customer's page or app makes to Black itself, and which stay on your server. At the end you can name the credential each call needs, and you have sent the two calls that Black refuses on purpose.
Black has two surfaces. The Server API, under /v1, is for your servers. The Client API, under /v1/client, is for the page or app that runs in your customer's browser or phone. Every call in this section is a direct HTTP call: a page sends it with fetch, and your server sends it with cURL.
Before you start
You need an app and a publishable key in the environment you work in: see Register an app and Create a publishable key. Manage an app's keys and allowed origins explains both.
You need an API client's access token for the Server API calls. Keep it on your server: see Authentication.
Steps
Pick the credential for each call
The two surfaces take different credentials, and neither takes the other's.
| Surface | Path | Who calls | Credential |
|---|---|---|---|
| Server API | /v1/… | Your servers | An API client's access token, or a person's session token |
| Client API | /v1/client/… | A page or app in the customer's browser or phone | A publishable key, and for anything about a customer, the customer's session |
-
Use the publishable key for what needs no customer. A publishable key is an identifier, not a secret: it can sit in a page's source, a log line or an error report. Send it in the
Black-Publishable-Keyheader. It names one app of one environment, and it opens the Client API for that app alone. -
Add the customer's session for anything about a customer. A session is the pair of tokens Black gives a customer who signed in. Send the access token as
Authorization: Bearer <access token>beside the key. See Start, refresh and end a customer session. -
Read the table to see what each credential opens.
| Call | Needs | What it does |
|---|---|---|
GET /v1/client/config | Key | Reads what a page draws and offers: the look, the sign-in methods that are on, the sign-up fields, the consent addresses and the plans on sale. See Show the environment's configuration. |
GET /v1/client/plans | Key | Reads the plans on sale for a page, by country and currency. See Show your plans on a page. |
POST /v1/client/auth/token, /identity-token | Key | Exchange a token your server or your own sign-in made for a session. |
POST /v1/client/auth/refresh | Key | Exchange a refresh token for a new pair. |
POST /v1/client/auth/sign-up, /sign-in, /link, /link/exchange, /google, /password-reset/request, /password-reset, /email/verify | Key | Black's own sign-in, for each method you turned on. See Sign customers in with email and password. |
POST /v1/client/checkout-sessions | Key | Starts a hosted checkout. |
POST /v1/client/auth/sign-out | Key and session | Ends every session of the customer. |
GET and PATCH /v1/client/customer, and the customer's entitlements, subscriptions, invoices and cards | Key and session | Read and change the customer's own account. See Show a signed-in customer their own account. |
POST /v1/client/auth/password, /email/change, /email/verify/request | Key and session | Change the signed-in customer's password or email. |
A path under /v1/client that is not one of these calls refuses every caller with 403 and permission_denied.
Know the two refusals
The doors never cross, and each crossing has its own answer.
-
Send a publishable key to the Server API. Black answers
401withpublishable_key_not_allowed, from the headers alone, before it reads any data. Call that endpoint from your server with an access token. -
Send a server credential to the Client API. An API client's access token, a person's session token, HTTP Basic credentials and a client secret are all refused with
401andserver_credential_not_allowed. Never put one in a page or an app: send the publishable key instead.
Know what a customer is never shown
-
Read the Client API's answers as the customer's own view. Every answer holds only the fields a customer may see. It never holds your
metadata, the customer'sexternal_reference, notes, flags, blocks or anything else your account keeps for itself. -
Expect no other customer's data. No path carries a customer ID: Black answers for the customer the session belongs to. A subscription or invoice of another customer answers
404andresource_not_found, the same answer as an ID that does not exist.
Know what Black checks
- Know that the key and the origin identify a well-behaved caller and do not prove one. A browser cannot lie about its
Origin, so another website's page cannot use your key. A program outside a browser can send any header. What protects the customer is the session, and what limits abuse is the rate limit: a request over a limit answers429withrate_limit_exceededand aRetry-Afterheader.
Show your plans on a page
-
Send a
GETrequest to/v1/client/planswith the publishable key alone. No customer session is needed. The response is a list of the environment's plans on sale, each with its price, its product and its features, and it holdssales_openandprices_include_taxbeside the list. The list is never paged and Black keeps none of it: each read asks again. -
Add
country, a country code in upper case, as?country=SA. Each plan then holds atax_quotewith theamount, thetax, theamount_excluding_taxand thetotalfor that country. Without a country no tax is shown, andprices_include_taxis still there, unless the account taxes one fixed country: then each plan is quoted for that country, and itstax_quotenames it incountry, as billing will tax it. Acountryyou send does not change that quote. A code that is not a country answers422withparameter_invalid, namingcountry. -
Add
currency, also in upper case, as?currency=USD. Each plan then holds apresentmentwith its price in that currency. A price already in that currency is shown as it is, with its rate fieldsnull. A currency the environment does not offer answers422withcurrency_not_supported: Black never shows the nearest currency. With both, thepresentmentholds its owntax_quote: the price is converted first, then taxed. -
Handle the two answers that mean no price. A tax service that does not answer gives
503withtax_service_unavailable, and a country Black cannot tax gives409withtax_not_determined. Black never shows a tax of 0 in their place, so show the plans without a total, or ask the customer again later. When the error namestax_country, the country refused is the one the account fixed, so the customer cannot fix it by choosing another: show the plans without a total, and tell the account to fix its tax setup with a rate for that country, a default rate or anothertax_country.
A page reads the plans with fetch:
const key = 'PLACEHOLDER_PUBLISHABLE_KEY';
const response = await fetch('https://api.black.example/v1/client/plans?country=SA¤cy=USD', {
headers: { 'Black-Publishable-Key': key },
});
if (!response.ok) {
const { error } = await response.json();
throw new Error(error.code);
}
const { data: plans, prices_include_tax } = await response.json();
A runnable sample
This sample registers an app and its key, reads the configuration with the key alone, then sends the two calls that Black refuses: the key to the Server API and your access token to the Client API. It writes PLACEHOLDER_ACCESS_TOKEN where your access token goes, reads the app's ID and the key from the responses, and needs sed. Each write waits a second because a test environment takes five writes a second.
TOKEN=PLACEHOLDER_ACCESS_TOKEN
APP=$(curl --silent --request POST https://api.black.example/v1/apps \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data '{"name":"Overview 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 "https://api.black.example/v1/apps/$APP/publishable-keys" \
--header "Authorization: Bearer $TOKEN" \
| sed -n 's/.*"\(pk_test_[0-9A-Za-z]*\)".*/\1/p')
curl --silent --request GET https://api.black.example/v1/client/config \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com"
curl --silent --request GET https://api.black.example/v1/customers \
--header "Black-Publishable-Key: $KEY" \
--header "Origin: https://app.example.com"
curl --silent --request GET https://api.black.example/v1/client/config \
--header "Black-Publishable-Key: $KEY" \
--header "Authorization: Bearer $TOKEN" \
--header "Origin: https://app.example.com"
The app and its key answer 201. The configuration read answers 200. The key sent to the Server API answers 401 with publishable_key_not_allowed. The access token sent to the Client API answers 401 with server_credential_not_allowed.
The second sample is a vendor's. It creates a sub-account that sells one plan in SAR with 15% tax added, lists USD and EUR as currencies, sets test exchange rates, makes an app and its key, and reads the plans with the key alone: as they are, for Saudi Arabia, in USD, in USD for Saudi Arabia, and in a currency the environment does not offer. It writes PLACEHOLDER_VENDOR_ACCESS_TOKEN where your access token goes, needs sed, and waits a second after its first three writes, because a test environment takes five writes a second.
TOKEN=PLACEHOLDER_VENDOR_ACCESS_TOKEN
RUN=$(date +%s)$RANDOM
H=(--header "Authorization: Bearer $TOKEN" --header "Content-Type: application/json")
has() { [[ "$1" == *"$2"* ]] || { echo "The answer does not hold: $2"; exit 1; }; }
ACCOUNT=$(curl --silent --request POST https://api.black.example/v1/vendor/accounts "${H[@]}" \
--data "{\"name\":\"Page Plans $RUN\",\"contact_email\":\"owner@page-plans.example\",\"external_reference\":\"page-plans-$RUN\"}" \
| sed -n 's/.*"id":"\(acct_[0-9a-z]*\)".*/\1/p')
H+=(--header "Black-Account: $ACCOUNT")
APP=$(curl --silent --request POST https://api.black.example/v1/apps "${H[@]}" \
--data '{"name":"Page Plans Demo","kind":"web","allowed_origins":["https://app.example.com"]}' \
| sed -n 's/.*"id":"\(app_[0-9a-z]*\)".*/\1/p')
KEY=$(curl --silent --request POST "https://api.black.example/v1/apps/$APP/publishable-keys" "${H[@]}" \
| sed -n 's/.*"\(pk_test_[0-9A-Za-z]*\)".*/\1/p')
sleep 1
curl --silent --request PATCH https://api.black.example/v1/settings "${H[@]}" \
--data '{"tax_mode":"rules","prices_include_tax":false,"vat_rates":{"SA":15},"presentment_currencies":["USD","EUR"]}' >/dev/null
PRODUCT=$(curl --silent --request POST https://api.black.example/v1/products "${H[@]}" \
--data "{\"name\":\"Page Prime $RUN\"}" | sed -n 's/.*"id":"\(prod_[0-9a-z]*\)".*/\1/p')
curl --silent --request POST https://api.black.example/v1/prices "${H[@]}" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":4999,\"recurring\":{\"interval\":\"month\",\"interval_count\":1}}" >/dev/null
curl --silent --request PUT https://api.black.example/v1/test-exchange-rates "${H[@]}" \
--data '{"base":"USD","rates":{"USD":"1","SAR":"3.7504","EUR":"0.861234","KWD":"0.306512"}}' >/dev/null
C=(--header "Black-Publishable-Key: $KEY" --header "Origin: https://app.example.com")
PLANS=$(curl --silent https://api.black.example/v1/client/plans "${C[@]}")
has "$PLANS" '"prices_include_tax":false'
has "$PLANS" '"unit_amount":4999'
BY_COUNTRY=$(curl --silent "https://api.black.example/v1/client/plans?country=SA" "${C[@]}")
has "$BY_COUNTRY" '"tax":750,"amount_excluding_tax":4999,"total":5749'
BY_CURRENCY=$(curl --silent "https://api.black.example/v1/client/plans?currency=USD" "${C[@]}")
has "$BY_CURRENCY" '"currency":"USD"'
curl --silent "https://api.black.example/v1/client/plans?currency=SAR&country=SA" "${C[@]}"
curl --silent "https://api.black.example/v1/client/plans?currency=USD&country=SA" "${C[@]}"
curl --silent "https://api.black.example/v1/client/plans?currency=JPY" "${C[@]}"
The sub-account, the app and the key answer 201, then the settings answer 200, the product and the price 201 and the rates 200. The five reads of the plans that follow answer 200: as they are, for Saudi Arabia, in USD, in SAR for Saudi Arabia (the price's own currency, shown as it is) and in USD for Saudi Arabia. A currency the environment does not offer answers 422 with currency_not_supported.
What to do next
- Create, roll and revoke keys, and set the allowed origins, in Manage an app's keys and allowed origins.
- Start, refresh and end a customer's session in Start, refresh and end a customer session.
- Choose how your customers sign in in Choose how customers sign in.
- Read every error code in Errors.