Build a hosted checkout page
What you will build
You build the page that a customer opens to pay for a checkout session: it reads the session, shows what the customer buys, takes the card in the gateway's own fields, and sends the payment to Black. You learn the calls in order, what to show for each status, how to follow the bank's step and the return from it, how to let the customer pay again after a decline, and what each refusal means.
Black gives each checkout session an address for its own page. This guide is also the contract of a page that you build yourself, and the reading of Black's page if you want to know what it does.
Before you start
You need a checkout session. Your server creates one with POST /v1/checkout-sessions, with a price, a success_url and a cancel_url. The environment needs a connected gateway and the payment mode black_charges: see Connect a payment gateway. In a test environment the practice gateway needs no gateway account: see The practice gateway.
The page makes four calls: read the session, confirm it, check the payment and pay again. Each endpoint page lists its fields, its errors and its answers: this guide does not repeat them.
The page runs in the customer's browser. It holds the checkout session's secret and nothing else of yours: never a secret key or an access token.
Open the page at its address and keep its secret
The answer that creates the session holds url, the address of the page:
<checkout host>/c/chk_<ID>#chks_<secret>
The checkout host is Black's own host for the page, not the API's host. The API answers a request from that host's origin only. The part after chk_ is the session's ID, in the path. The part after # is the session's secret, in the fragment, so that no server and no log between the customer and the page ever sees it. The answer to the create shows the secret once, and Black keeps only a hash of it. A later read of the session shows url as null.
When the page loads, it does five things with the secret:
- Read the secret from the fragment, keep it in the tab's
sessionStorageunder the session's ID, then remove the fragment from the address bar withhistory.replaceState. The secret is no longer in the tab's history or in a link the customer copies. - When the address has no fragment, read the secret from
sessionStorageunder the ID in the path. This is how the page reads its session again when the bank sends the customer back: the return address carries no secret, on purpose. - When neither holds a secret, which happens in another tab, another browser or after the storage is cleared, say that the page cannot read the session and ask the customer to start again from your site. Never show success or failure.
- Remove the secret from
sessionStorageonce the session readscompleteorexpired. - Send the secret only to the API, in the
Black-Checkout-Secretheader. Never put it in an address, a log, an error report or an analytics call.
Steps
Every call carries the Black-Checkout-Secret header. The two writes also carry Content-Type: application/json. The page sends no publishable key, no Authorization header and no cookie, and the API sets no cookie. A write needs no Idempotency-Key: the session settles each write, so sending the same one again never pays twice. The Black-Version header is optional, and names the API version that you built the page against.
-
Read the session. Send a
GETrequest to/v1/client/checkout-sessions/{id}. The response holds the product, the price, the address to ask for, the preview of the total, the look of your page, and the gateway. Read it again with?country=SA, or the country the customer chose, in two-letter capitals, each time the customer changes the country in your address form. With a country, the preview's tax and total are Black's quote for that country, before the customer pays. Without one, they are quoted for the country of the customer the session names, when it is known. When the account taxes one fixed country, the preview is quoted for that country, named incountry, whatever country you send or the customer has. Otherwisetax,totalandcountryarenull: show the subtotal and say that the tax is worked out from the country. -
Show what the status asks for, as the next section sets out.
-
Take the card in the gateway's own fields, as the section after it sets out. Ask for the token when the customer presses pay, not before.
-
Confirm and pay. Send a
POSTrequest to/v1/client/checkout-sessions/{id}/confirmwith theemailwhile the session readscollect_emailastrue, theaddressto the level thataddress_collectionasks for, thepayment_tokenand, while the session shows aconsent,consent_acceptedset to the JSON booleantrue. Keep the pay button off until the customer ticks the consent box. The response is the session's state alone:complete,processingor an error. -
Act on the answer.
completesends the customer tosuccess_url.processingwith anext_actionsends the customer to the bank.processingwithout one and without alast_payment_errormeans that the gateway has not given a final answer yet: ask Black to check the payment, as the section on the bank's step sets out. Never read it as success.
An email typed on the page always makes a new customer: it never signs anyone in. It is ignored when the session already names a customer. An address for country holds the country alone, and for full holds line1, city, postal_code and country, with line2 and state optional. Leave the address out for none.
Show the right state for each status
Read status from the session, and show:
status | What the page shows |
|---|---|
open | The form: the email when collect_email is true, the address to the level of address_collection, the consent box when consent is set, the card fields, and the pay button. |
processing with a next_action | Sends the customer to next_action.redirect_url, unless the customer has just come back from it. |
processing without a next_action or a last_payment_error | "Waiting for your payment to be confirmed". It asks Black to check the payment and never shows success. |
processing with a last_payment_error | The payment failed: say why, as the section on paying again sets out, and offer to pay again. |
complete | Sends the customer to success_url and forgets the secret. |
expired | "This checkout has expired", with a link to cancel_url, and forgets the secret. |
A session with livemode false is in a test environment: show a test banner. An open session that is past its expires_at is expired, even when status still reads open: show the expired state. A processing session past its end can still complete, because a payment that waits on the bank is settled when the bank answers. Send no new payment for it, keep reading it, and forget the secret only when the API says complete or expired.
Success is decided by Black's record alone, never by the page. Send the customer to success_url only after a read or an answer says complete. Your server gives access on the checkout.session.completed event or on its own read of the session, never on a visit to the success address. See Events.
The cancel link is a plain link to cancel_url: the page calls nothing, and nothing is created.
Take the card in the gateway's own fields
The card goes from the customer's browser straight to the gateway, in fields that the gateway serves. The page never reads, keeps, logs or sends a card number, an expiry date or a security code. What reaches Black is the gateway's single-use token.
Black gives the page the gateway's kind and its public_key, in the gateway field of the session, and nothing else of the connection: no secret key, no signing key and no processing channel. The gateway is null when the environment has no active connection. The page then cannot take a card: say that payment is not available and offer the cancel link.
Choose the card fields by gateway.kind, not by livemode, because a test environment can hold the practice gateway or a sandbox connection of a real gateway.
checkout_com. Load one of the two from Checkout.com. With Frames, load its script, callFrames.initwithpublicKeyset togateway.public_keyand alocalizationofARorEN-GB, and on pay takedata.tokenfromFrames.submitCard(). With Flow, load its script from Checkout.com's address only, as Checkout.com asks you not to host or bundle it, callCheckoutWebComponentswith the public key, theenvironmentand thelocale, with no payment session, create thecardcomponent, mount it, and on pay takedata.tokenfrom itstokenize(). Use only the card component of Flow, because the full component needs a payment session that your secret key makes, and Black makes the payment itself. Without a payment session, Flow needs a public key with the scopespayment-sessions:payandvault-tokenization: set them when you create the key in your Checkout.com Dashboard. See Checkout.com.simulator. The practice gateway has no card fields. Show a picker of test cards and send the token of the chosen one, as the next section sets out.
A Checkout.com token is single-use and lasts 15 minutes, so the page asks for it when the customer presses pay. When a decline carries the reason token_expired, the token was too old: ask the customer to enter the card again.
Use the test tokens of the practice gateway
In a test environment with the practice gateway, send one of these tokens as the payment_token. The gateway declines any other token with incorrect_number.
| Token | The outcome with the customer present |
|---|---|
tok_simulator_succeeds | Paid. |
tok_simulator_declined | Declined with card_declined. |
tok_simulator_insufficient_funds | Declined with insufficient_funds. |
tok_simulator_expired | Declined with expired_card. |
tok_simulator_requires_action | The practice bank asks the customer to authenticate: the answer holds a next_action, and its address opens a page where the customer approves or fails the step. See Answer the practice bank's step. |
tok_simulator_saves_then_fails | Paid now. Later renewals fail. |
Your server lists the same tokens with GET /v1/test-helpers/simulator-tokens.
Follow the bank's step and the return
When an answer or a read holds a next_action, the bank asks the customer to authenticate. Send the customer to next_action.redirect_url in the same tab, with location.assign, never in a frame or a pop-up. The secret stays in that tab's sessionStorage. The bank then sends the customer back to <checkout host>/c/chk_<ID>, sometimes with the gateway's own query parameters, which the page ignores.
Back on the page, do four things:
- Note in
sessionStoragethat the customer has come back from the bank, so that the page does not send them to the bank again for the sameredirect_url. - Ask Black to check the payment. Send a
POSTrequest to/v1/client/checkout-sessions/{id}/checkwith no body. While the payment waits for the bank, Black asks the gateway for its state at once and settles the payment as the gateway's own notification would, so a payment is never applied twice. The response is the session's state, as the confirm answers it:complete,processingwith alast_payment_error, orprocessingwithout one. An unclear answer from the gateway, or none, leaves the sessionprocessing: Black never reports a payment paid or declined on a guess. Black asks the gateway at most once every 5 seconds for a session. A check sent sooner answers with the session as it stands, without asking. The check charges nothing. - Keep checking while the answer is
processingwith neither anext_actionnor alast_payment_error: send the check every 5 seconds, or read the session every 3 seconds, for up to 2 minutes. Stop as soon asstatusiscompleteand go tosuccess_url,expiredand show the expired state,openand show the form again, or alast_payment_errorappears and the page shows why the payment failed. While you wait, show "Waiting for your bank to confirm". Thenext_actioncan stay for a while after the customer is back, because Black learns the bank's answer from the gateway's notification, not from the customer's return. While it stays, keep checking and do not send the customer to the bank again. - After 2 minutes, stop reading and say that the payment is still being confirmed and that the customer can close the page: your server is told when it is. Offer "Check again", which sends the check once more, and "Pay with another card", which pays again, as the next section sets out. Never show success or failure on a guess.
The read and the check tell a payment that failed after the bank's step, for example when the customer did not pass the authentication, from one that still waits. The failed one reads processing with no next_action and a last_payment_error. One that still waits has a last_payment_error of null, and paying again is refused with payment_in_progress until that payment has failed.
Pay again after a decline
A decline answers 402 with the code payment_declined and a decline_reason. The session stays processing, and its subscription stays unpaid. Say that the card was declined, in your own words for the reason, and ask for another card. Take a new token, then send a POST request to /v1/client/checkout-sessions/{id}/pay with the payment_token and, while the session shows a consent, consent_accepted set to true. Sending the confirm again with a new token does the same. Paying again is possible until the session's end.
A session whose payment failed after the bank's step shows the same failure in last_payment_error, with a code and a decline_reason. The code is payment_declined, or gateway_unavailable when the gateway could not take the payment, and then the decline_reason is null. For payment_declined say that the card was declined, with your words for the reason, and ask for another card. For gateway_unavailable say that payments are not available right now, without blaming the card. Either way, offer to pay again with the steps above.
The decline_reason is one of insufficient_funds, expired_card, incorrect_number, lost_or_stolen, suspected_fraud, do_not_honor, authentication_failed, authentication_required, transaction_not_allowed, risk_declined, card_declined or token_expired. Show your own words for each, and a general message for any other.
Handle a refusal
Every refusal has one shape: an error with a type, a code, a message, a param and a request_id, plus a decline_reason on a 402. Show your own words for each code that you know and a general message for any other. Never show the message to the customer as it stands. See Errors for every code.
checkout_secret_invalid(401). The secret is wrong or gone. Show the state of a page that cannot read its session.payment_declined(402). The customer's bank refuses the charge. Ask for another card and pay again.payment_in_progress(409). Another tab or an earlier press is paying. Check the payment again until it settles.checkout_session_complete(409). The session is paid. Read it and send the customer tosuccess_url.checkout_session_expired(409). Show the expired state.already_memberandsales_closed(409). The purchase cannot go ahead, and the session is open again. Show the reason and the cancel link.tax_not_determined(409). The account's tax cannot be worked out for the country that you sent. Ask the customer to choose another country. When the error namestax_country, the account's fixed tax country is the one refused, and a customer cannot fix that: say that checkout cannot go on for now, and tell the account to fix its tax setup with a rate for that country, a default rate or anothertax_country.checkout_session_not_confirmed(409). You paid again a session that was never confirmed. Confirm it first.parameter_invalid(422). Mark the field thatparamnames:email,address.<field>,payment_tokenorconsent_accepted. Acountrythat Black does not know on the read is refused the same way, namingcountry.customer_country_required(422). The account's tax needs the customer's country. Whenaddress_collectioniscountryorfull, the page already asks for it. Withnone, the page cannot send one: say that the purchase cannot be completed here and offer the cancel link.rate_limit_exceeded(429). Wait the seconds thatRetry-Aftergives. After 5 declines on one session, or 10 from one address within an hour, paying is refused until the count frees.gateway_unavailable(503). Say that payments are not available right now, without blaming the card. The session stays payable.billing_engine_unavailableandtax_service_unavailable(503). Say that something went wrong on your side and to try again in a moment. Nothing was charged. A read withcountrycan answer these too.
The page's requests are counted for each checkout session: 100 reads and 30 writes a second, the same in a test environment as in a live one. A request over a limit answers 429 with a message that names the limit it met. Checking every 5 seconds, or reading every 3, is well within them. A check that Black answers without asking the gateway counts as a request like any other.
Keep to what the page must never do
- Decide that a payment succeeded on its own: on the gateway's events, on the return from the bank or on a timer.
- Read, keep, log or send a card number, an expiry date or a security code, or load the gateway's script from anywhere but the gateway.
- Send the secret anywhere but the
Black-Checkout-Secretheader, or keep it pastcompleteorexpired. - Send the customer to any address but
success_url,cancel_urlandnext_action.redirect_url. - Load a script that is neither your page's own nor the gateway's: no analytics and no tag manager on a payment page.
Show amounts in the currency's smallest unit, formatted for the page's language with the browser's Intl.NumberFormat and the currency that the session gives. Show the product's name and description as the account wrote them. Use look.brand_color for the pay button and look.logo_url at the top, and your own neutral look when either is null. In Arabic, set <html lang="ar" dir="rtl"> and give the card fields the same language.
A runnable sample
The sample is a vendor's. It creates a sub-account, a product and a monthly price of 30 SAR, connects the practice gateway and sets the payment mode to black_charges. It creates a checkout session, takes the session's ID and secret from the url in the answer, and reads the session as the page does, with the secret in Black-Checkout-Secret and with the country SA. It confirms with a declined token and is refused with 402, pays again with the token that succeeds, and reads the session, which is complete. A call with a wrong secret is refused with 401. It writes PLACEHOLDER_VENDOR_ACCESS_TOKEN where your access token goes and the placeholders sk_test_… and pk_test_… where gateway keys go, and needs sed. A test environment takes five writes a second, and the page's own writes are limited to three a second for each session, so the sample waits a second after each write. Its names end in a number made from the time, so that it runs again.
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\":\"Hosted Page $RUN\",\"contact_email\":\"owner@hosted-page.example\",\"external_reference\":\"hosted-page-$RUN\"}" \
| sed -n 's/.*"id":"\(acct_[0-9a-z]*\)".*/\1/p')
H+=(--header "Black-Account: $ACCOUNT")
PRODUCT=$(curl --silent --request POST https://api.black.example/v1/products "${H[@]}" \
--data "{\"name\":\"Prime Page $RUN\"}" \
| sed -n 's/.*"id":"\(prod_[0-9a-z]*\)".*/\1/p')
PRICE=$(curl --silent --request POST https://api.black.example/v1/prices "${H[@]}" \
--data "{\"product\":\"$PRODUCT\",\"currency\":\"SAR\",\"unit_amount\":3000,\"recurring\":{\"interval\":\"month\",\"interval_count\":1}}" \
| sed -n 's/.*"id":"\(price_[0-9a-z]*\)".*/\1/p')
curl --silent --request POST https://api.black.example/v1/gateway-connections "${H[@]}" \
--data '{"gateway":"simulator","secret_key":"sk_test_PLACEHOLDER","prefix":"practice","processing_channel":"pc_practice","public_key":"pk_test_PLACEHOLDER"}'
curl --silent --request PATCH https://api.black.example/v1/settings "${H[@]}" \
--data '{"payment_mode":"black_charges"}'
CREATED=$(curl --silent --request POST https://api.black.example/v1/checkout-sessions "${H[@]}" \
--data "{\"price\":\"$PRICE\",\"success_url\":\"http://shop.example/done?session={CHECKOUT_SESSION_ID}\",\"cancel_url\":\"http://shop.example/cancel\",\"address_collection\":\"country\"}")
SESSION=$(echo "$CREATED" | sed -n 's/.*"id":"\(chk_[0-9a-z]*\)".*/\1/p')
SECRET=$(echo "$CREATED" | sed -n 's/.*#\(chks_[0-9A-Za-z]*\)".*/\1/p')
P=(--header "Black-Checkout-Secret: $SECRET" --header "Content-Type: application/json")
READ=$(curl --silent "https://api.black.example/v1/client/checkout-sessions/$SESSION?country=SA" "${P[@]}")
has "$READ" '"status":"open"'
has "$READ" '"kind":"simulator"'
curl --silent --request POST https://api.black.example/v1/client/checkout-sessions/$SESSION/confirm "${P[@]}" \
--data '{"email":"buyer@hosted-page.example","address":{"country":"SA"},"payment_token":"tok_simulator_declined"}'
curl --silent --request POST https://api.black.example/v1/client/checkout-sessions/$SESSION/pay "${P[@]}" \
--data '{"payment_token":"tok_simulator_succeeds"}'
DONE=$(curl --silent https://api.black.example/v1/client/checkout-sessions/$SESSION "${P[@]}")
has "$DONE" '"status":"complete"'
curl --silent https://api.black.example/v1/client/checkout-sessions/$SESSION --header "Black-Checkout-Secret: chks_wrong"
The sub-account, the product, the price, the gateway connection and the checkout session answer 201, with the settings change and the first read answering 200. The confirm with the declined token answers 402, the payment with the token that succeeds answers 200, the last read answers 200, and the read with a wrong secret answers 401.
What to do next
- Read Connect a payment gateway to connect the gateway that the page's card fields belong to.
- Read The practice gateway to try every outcome of a payment before you hold a gateway account.
- Read Checkout.com for what the page's public key must carry.
- Read Events for
checkout.session.completedand the other events that your server follows.