Embedded payments with Stripe Elements
Take a card or wallet payment on your own checkout page. The buyer types the card into Stripe Elements, Stripe.js turns it into a single-use credential, and your backend sends that credential to Flint. Flint charges it against the order, runs 3D Secure when the issuer asks for it, and marks the order paid. Card numbers never reach your servers or Flint's.
Use this when checkout lives on your domain. If a Flint-hosted payment page is enough, follow Accept your first payment instead. Cart building, delivery, receipts, and checkout sessions for a full merchant-owned checkout are in Build your own checkout; this guide covers the payment step inside it.
Before you start#
Get a test API key. Create one on the dashboard's API keys page. A test key starts with flint_test_ and is bound to a sandbox, so payments run in Stripe test mode and no real money moves. Test and live keys use the same base URL, https://api.withflintpay.com; the key decides the mode.
Give the key the permissions this guide uses. A write permission also grants its read.
| Permission | Covers |
|---|---|
commerce.orders.write | Creating, reading, and paying orders, and creating payment legs on them |
merchants.profile.read | The readiness check below |
payments.payment_intents.write | Capturing or canceling a payment leg |
checkouts.checkout_sessions.write | Creating an embedded checkout session, if you use one |
Registering a wallet domain needs payments.payment_method_domains.write. Put it on a separate administrative key rather than the one your checkout uses.
Keep the key on your backend. The browser talks to Stripe.js and to your backend, never to the Flint API. Flint has no publishable key and does not accept API requests from merchant browser origins. The one Flint page a browser can show is the gift card challenge, in a frame.
Check that your sandbox can take card payments:
curl https://api.withflintpay.com/v1/merchant \
-H "Authorization: Bearer YOUR_API_KEY"
data.readiness.payments.status is ready when the account can charge cards.
A 200 response confirms the request worked, not that the sandbox can charge cards. While readiness.payments.status is pending or blocked, its status_reason and readiness.requirements name what is still due. Complete it in the dashboard, then run the check again.
Register your checkout hostname for wallets. Apple Pay and Google Pay buttons appear only on HTTPS hostnames registered with POST /v1/payment-method-domains. Apple Pay and Google Pay covers registering, checking, and testing each hostname. Cards work without it.
The flow#
- Your backend sends 1. POST /v1/orders to Flint
- Your backend sends 2. GET /v1/orders/{order_id} to Flint
- Flint returns balance and payment_collection to Your backend
- Your backend returns payment_collection to Browser
- Browser sends 3 and 4. create the credential to Browser
- Browser sends the credential to Your backend
- Your backend sends 5. POST /v1/orders/{order_id}/pay to Flint
- Flint returns payment attempt to Your backend
- Your backend returns 6. client action, if 3D Secure is needed to Browser
- Browser sends challenge finished to Your backend
- Your backend sends action: resume to Flint
- Flint returns 7. order.paid webhook to Your backend
Who confirms the payment#
Flint does. Every PaymentIntent that belongs to an order is created and confirmed through the order, so one payment attempt records what happened. The browser only creates a credential.
- Never call
stripe.confirmPaymentorstripe.confirmCardPaymentfor an order.payment_collectionholds no PaymentIntent client secret, so there is nothing for the browser to confirm. The only client secret Flint returns is in a pending action, for 3D Secure or another buyer step, in step 6. It is a Stripe PaymentIntent client secret, so it can also confirm the payment at Stripe with a different card. Pass it only tohandleNextAction, never toconfirmPaymentorconfirmCardPayment, and read the outcome from your backend. POST /v1/payment-intents/{payment_intent_id}/confirmrefuses an order's PaymentIntent with409 ACTION_NOT_ALLOWEDand reasonorder_owned. Pay it throughPOST /v1/orders/{order_id}/pay.- Capture and cancel work the same as for a standalone PaymentIntent, through
/v1/payment-intents/{payment_intent_id}/captureand/cancel. Flint finds the order payment attempt that owns the leg and updates the order.
A payment leg is one PaymentIntent on the order. The steps below never create one by hand: action: "pay" creates a full-balance, automatic-capture leg and confirms it in one request. Create legs yourself only for split tender or partial payment and for manual capture.
Step 1: create an order#
The order is Flint's record of the sale, and the payment settles against it. Amounts are integers in the currency's minor unit, so 9900 is $99.00.
curl -X POST https://api.withflintpay.com/v1/orders \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: order-pro-annual-001" \
-d '{
"line_items": [{
"type": "custom",
"name": "Pro Plan Annual",
"quantity": 1,
"unit_price_money": {"amount": 9900, "currency": "USD"},
"fulfillment": {"requirement": "none"}
}]
}'
{
"data": {
"order_id": "ord_1kmn0aExample",
"status": "open",
"payment_status": "unpaid",
"version": 1790760000,
"settlement_amounts": {
"paid_money": {"amount": 0, "currency": "USD"},
"outstanding_money": {"amount": 9900, "currency": "USD"}
}
},
"request_id": "req_..."
}
status says whether the order still accepts changes and payments, and payment_status tracks collection. An unpaid order is open and unpaid. Once the full balance is collected it becomes closed and paid. Apply delivery, tax, promotions, and tips before the buyer pays, because each can change the total.
Step 2: read the collection guidance#
Read the order right before you mount Elements. data.payment_collection says what to collect and under which Stripe account, and Flint recalculates it on every read.
curl https://api.withflintpay.com/v1/orders/ord_1kmn0aExample \
-H "Authorization: Bearer YOUR_API_KEY"
{
"data": {
"order_id": "ord_1kmn0aExample",
"status": "open",
"payment_status": "unpaid",
"version": 1790760000,
"settlement_amounts": {
"outstanding_money": {"amount": 9900, "currency": "USD"}
},
"payment_collection": {
"stripe": {
"account_id": "acct_1AbcPlaceholder",
"publishable_key": "pk_test_51AbcPlaceholder",
"elements": {
"next_step": "collect_payment_source",
"submit_to": "pay_order",
"mode": "payment",
"amount_money": {"amount": 9900, "currency": "USD"},
"payment_method_types": ["card"],
"digital_wallets": ["apple_pay", "google_pay"],
"payment_method_creation": "manual"
}
}
}
},
"request_id": "req_..."
}
Store settlement_amounts.outstanding_money and version from this response on your backend. They are what the buyer approves, and you send them back with the payment in step 5.
Send payment_collection to the browser as returned. It holds no secrets: the publishable key and account ID exist for Stripe.js. Reading the order creates no payment leg and holds no funds.
next_step names the Stripe.js call the browser makes, and with it the credential your backend sends to Flint:
next_step | Stripe.js call | Credential |
|---|---|---|
collect_payment_source | stripe.createPaymentMethod | A pm_..., sent as credential_type: "token" |
create_confirmation_token | stripe.createConfirmationToken | A ctoken_..., sent as credential_type: "stripe_confirmation_token" |
A read with your API key returns collect_payment_source. A read with a checkout session credential returns create_confirmation_token. Branch on the returned value, not on how you authenticated, so one browser implementation serves both. A zero-balance order returns mode: "setup" with next_step: "collect_setup_payment_source", which saves a card instead of charging one; Build your own checkout covers it.
Step 3: mount Stripe Elements#
Initialize Stripe.js with the publishable key and connected account from the guidance. Then create Elements in deferred mode from the amount, currency, and payment method types.
<script src="https://js.stripe.com/v3/"></script>
<form id="payment-form">
<div id="payment-element"></div>
<button id="submit" type="submit">Pay $99.00</button>
<div id="payment-message" role="alert"></div>
</form>
const {stripe: collection} = paymentCollection;
const guidance = collection.elements;
const stripe = Stripe(collection.publishable_key, {
stripeAccount: collection.account_id,
});
const elements = stripe.elements({
mode: guidance.mode,
amount: guidance.amount_money.amount,
currency: guidance.amount_money.currency.toLowerCase(),
paymentMethodCreation: guidance.payment_method_creation,
paymentMethodTypes: guidance.payment_method_types,
});
elements.create("payment").mount("#payment-element");
paymentMethodCreation: "manual" is what lets Stripe.js create a credential without confirming a payment. Flint confirms it in step 5.
If the total changes after Elements is mounted, for example because the buyer picks a delivery option, read the order again and call elements.update() with the new amount_money.amount. Show the buyer the new total before they pay.
Step 4: create the credential#
When the buyer submits, call elements.submit() to validate the form, then the Stripe.js call that next_step names. Post the credential's ID to your backend.
document.querySelector("#payment-form").addEventListener("submit", async (event) => {
event.preventDefault();
const {error: submitError} = await elements.submit();
if (submitError) return showMessage(submitError.message);
let credential;
if (guidance.next_step === "create_confirmation_token") {
const {error, confirmationToken} = await stripe.createConfirmationToken({elements});
if (error) return showMessage(error.message);
credential = {kind: "confirmation_token", id: confirmationToken.id};
} else if (guidance.next_step === "collect_payment_source") {
const {error, paymentMethod} = await stripe.createPaymentMethod({elements});
if (error) return showMessage(error.message);
credential = {kind: "payment_method", id: paymentMethod.id};
} else {
throw new Error(`Unsupported collection step: ${guidance.next_step}`);
}
const response = await fetch("/checkout/pay", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({credential}),
});
await handlePaymentResult(await response.json());
});
The credential is single-use and pays one payment leg. Send it to your backend over HTTPS and nowhere else: not to logs, analytics, or browser storage. A Stripe.js error here means Stripe rejected the form, and nothing was sent to Flint.
Step 5: pay#
Your backend sends the credential in payment_source with action: "pay". Flint creates a leg for the full outstanding balance and starts the payment attempt in the same request.
curl -X POST https://api.withflintpay.com/v1/orders/ord_1kmn0aExample/pay \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: pay-ord_1kmn0aExample-pm_1kmn0aExample" \
-d '{
"action": "pay",
"payment_source": {"credential_type": "token", "token": "pm_1kmn0aExample"},
"expected_outstanding_money": {"amount": 9900, "currency": "USD"},
"expected_version": 1790760000,
"buyer_contact": {"email": "ada@example.com"}
}'
{
"data": {
"order": {
"order_id": "ord_1kmn0aExample",
"status": "closed",
"payment_status": "paid",
"version": 1790760002,
"settlement_amounts": {
"paid_money": {"amount": 9900, "currency": "USD"},
"outstanding_money": {"amount": 0, "currency": "USD"}
}
},
"order_payment_attempt": {
"order_payment_attempt_id": "opat_1kmn0aExample",
"status": "succeeded",
"is_resumable": false,
"mode": "payment",
"expected_outstanding_money": {"amount": 9900, "currency": "USD"},
"payment_intents": [{
"payment_intent_id": "pi_1kmn0aExample",
"status": "succeeded",
"amount_money": {"amount": 9900, "currency": "USD"},
"tip_money": {"amount": 0, "currency": "USD"}
}],
"pending_actions": [],
"gift_card_redemptions": []
}
},
"request_id": "req_..."
}
The same request from a Node backend, building payment_source from what the browser posted:
app.post("/checkout/pay", async (req, res) => {
const {credential} = req.body;
// The order ID, balance, and version from the read the buyer approved.
const quote = await loadQuote(req.session);
const paymentSource =
credential.kind === "confirmation_token"
? {credential_type: "stripe_confirmation_token", stripe: {confirmation_token: credential.id}}
: {credential_type: "token", token: credential.id};
const response = await fetch(`https://api.withflintpay.com/v1/orders/${quote.orderId}/pay`, {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.FLINT_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `pay-${quote.orderId}-${credential.id}`,
},
body: JSON.stringify({
action: "pay",
payment_source: paymentSource,
expected_outstanding_money: quote.outstandingMoney,
expected_version: quote.version,
buyer_contact: {email: quote.buyerEmail},
}),
});
const body = await response.json();
if (!response.ok) return res.status(response.status).json({error: body.error});
const {order, order_payment_attempt: attempt} = body.data;
await saveAttempt(req.session, attempt.order_payment_attempt_id, order.version);
res.json({
status: attempt.status,
clientAction: attempt.pending_actions[0]?.client_action ?? null,
});
});
Deriving the Idempotency-Key from the order and the single-use credential makes a network retry of the same request safe: Flint returns the stored response or recovers the same attempt instead of charging twice. A new credential gets a new key. Idempotency covers the rules.
What to send#
expected_outstanding_moneyis the balance the buyer approved. If the order's outstanding balance no longer matches, Flint returns409 VERSION_CONFLICTbefore charging. It also returnsVERSION_CONFLICTwithparamapplied_discountswhen a promotion on the order stopped being available; Flint has already removed that discount, so a fresh read shows the new total. Either way, read the order again, show the buyer the new total, and ask them to approve it. Never resubmit silently. It is optional with your API key on an order with no open checkout session, and required otherwise: leaving it out then returns400 INVALID_REQUESTwith detail codeREQUIRED. Send it every time.expected_versionis the order'sversionfrom the same read. It catches an edit that leaves the balance unchanged, such as an item swapped for another at the same price. A mismatch returns409 VERSION_CONFLICTwithparamexpected_versionand the current version indetails[0].current_version. Starting a payment advances the version, so before the buyer tries again after a decline, take it from the order in the pay response.buyer_contact.emailrecords the guest buyer's email on the order, for the receipt. For a signed-in buyer, setcustomer_idon the order before payment instead, so their saved payment methods resolve.
pay accepts payment_source, expected_outstanding_money, expected_version, buyer_contact, accepted_gift_card_allocation, save_payment_method, and save_payment_method_phone. Each action accepts only its own fields, and any other field returns 400 INVALID_REQUEST with detail code UNKNOWN_FIELD. Saving the card during checkout and gift cards are in Build your own checkout.
Read the attempt, not the HTTP status#
A 200 carries every outcome: success, a decline, and a pause for 3D Secure. Flint never answers a decline with 402. Act on order_payment_attempt.status:
status | What to do |
|---|---|
succeeded | Show a confirmation. Fulfill from the webhook in step 7. |
requires_action | Run the client action in the browser, then resume. See step 6. |
failed | Nothing was charged. Show the leg's last_payment_error.message and collect a new card. |
canceled, expired | Nothing was charged. Start a new payment with a new credential. |
processing, requires_retry, finalizing | The outcome is still being settled. Don't start another payment. Resume while is_resumable is true; otherwise wait and read the attempt again. |
To retry after failed, collect a new credential, then send action: "confirm_payment_intents" with the declined leg's payment_intent_id and the new credential. The declined leg stays on the order, so a second action: "pay" returns 400 INVALID_REQUEST with detail code REQUIRED and the leg in details[0].selectable_resources. Declines and payment attempts has the retry request, every attempt status, and how to recover a lost response through the order's active_payment_attempt.
Step 6: handle 3D Secure#
When the issuer asks for authentication, the attempt pauses with status: "requires_action", is_resumable: true, and a pending action:
{
"order_payment_attempt": {
"order_payment_attempt_id": "opat_1kmn0aExample",
"status": "requires_action",
"is_resumable": true,
"pending_actions": [{
"pending_action_id": "pendact_1kmn0aExample",
"subject": {
"payment_intent": {"payment_intent_id": "pi_1kmn0aExample"}
},
"action_type": "payment_authentication",
"client_action": {
"stripe": {
"account_id": "acct_1AbcPlaceholder",
"publishable_key": "pk_test_51AbcPlaceholder",
"payment_intent": {
"stripe_js_call": "handle_next_action",
"client_secret": "pi_3AbcPlaceholder_secret_XyzPlaceholder"
}
}
}
}]
}
}
In the browser, run the call that stripe_js_call names with the action's client secret, using a Stripe instance for the action's publishable_key and account_id. Then ask your backend to resume.
async function handlePaymentResult(result) {
if (result.status === "succeeded") return showConfirmation();
if (result.status !== "requires_action") return showMessage(paymentMessage(result));
const action = result.clientAction.stripe;
const actionStripe = Stripe(action.publishable_key, {stripeAccount: action.account_id});
const {error} = await actionStripe.handleNextAction({
clientSecret: action.payment_intent.client_secret,
});
if (error) showMessage(error.message);
// Resume even after an error: Flint reads the real outcome from Stripe.
const response = await fetch("/checkout/resume", {method: "POST"});
await handlePaymentResult(await response.json());
}
Your backend resumes the attempt with action: "resume" and its order_payment_attempt_id:
curl -X POST https://api.withflintpay.com/v1/orders/ord_1kmn0aExample/pay \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: resume-opat_1kmn0aExample-1" \
-d '{
"action": "resume",
"order_payment_attempt_id": "opat_1kmn0aExample",
"expected_outstanding_money": {"amount": 9900, "currency": "USD"}
}'
- Use a new
Idempotency-Key. Reusing the start request's key with a resume body returnsIDEMPOTENCY_KEY_REUSED. - Send no credential. The resume continues the same attempt with the credential it already has. A resume accepts
order_payment_attempt_id,expected_outstanding_money, andbuyer_contact, andpayment_sourcereturns400 INVALID_REQUESTwith detail codeUNKNOWN_FIELD. - The amount guard checks the attempt. On a resume,
expected_outstanding_moneyis compared with the amount frozen on the attempt when it started, not the live balance. A mismatch returnsVERSION_CONFLICTwith the attempt's amount indetails[0].expected_attempt_outstanding_money.
A resume returns the same shape as step 5. If the buyer abandons or fails the challenge, the attempt ends canceled or failed, and the buyer pays again with a new credential. An attempt still waiting for authentication 30 minutes after it started is canceled. Finish 3D Secure covers each outcome.
Step 7: verify and fulfill#
Fulfill from the order.paid webhook, or from a fresh read of the order on your backend. A buyer can close the tab before your page hears the result, and a success message in the browser proves nothing to your server.
curl https://api.withflintpay.com/v1/orders/ord_1kmn0aExample \
-H "Authorization: Bearer YOUR_API_KEY"
Fulfill when payment_status is paid. Check payment_status, not status: an order can also close without payment, and closed_reason says why. A later refund doesn't reopen the order or change its payment_status.
Other credentials#
payment_source takes one of three credentials, chosen by credential_type. All of them use action: "pay" and the same attempt, 3D Secure, and retry flow.
credential_type | Field | Where it comes from |
|---|---|---|
token | token | A pm_... from stripe.createPaymentMethod |
stripe_confirmation_token | stripe.confirmation_token | A ctoken_... from stripe.createConfirmationToken |
payment_method | payment_method_id | A saved Flint payment method belonging to the order's customer |
Your API key accepts any of them, whatever next_step the read returned. A saved payment method must belong to the customer paying, so set customer_id on the order before you pay with one. Listing and choosing saved cards is in Build your own checkout.
Collect under a checkout session#
An embedded checkout session gives the buyer's side of checkout its own credential. Create one when that side needs Flint delivery selection, a checkout expiry, the checkout customer's saved payment methods, card saving, or a receipt resend. Create it on your backend with surface: "embedded":
curl -X POST https://api.withflintpay.com/v1/checkout-sessions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: checkout-pro-annual-001" \
-d '{
"type": "order",
"order_id": "ord_1kmn0aExample",
"surface": "embedded",
"page_origin": "https://shop.example.com"
}'
The response is the checkout session with checkout_auth_token among its fields. It has no url, because there is no Flint page to send the buyer to. page_origin is the origin of your checkout page, and only that page can show the gift card challenge. Offering Affirm also needs payment_return_url; see Affirm and ACH debit.
Requests with the checkout credential send it as the bearer token, with no API key. The token names its session, so no session ID goes beside it:
Authorization: Bearer ckat_1kmn0aExample
A request carries either the checkout credential or your API key, never both. In the SDKs, the checkout auth mode sends it for you.
Under the checkout credential, the flow above changes in three places:
- The order read returns
next_step: "create_confirmation_token", so the browser callsstripe.createConfirmationTokenand your backend sendscredential_type: "stripe_confirmation_token". expected_outstanding_moneyis required on every pay and resume.- The credential reaches only this checkout: its session and order, the buyer's delivery, promotion, tip, and tax choices, the checkout customer's saved payment methods, payment, canceling its own order's legs, and the receipt resend. Manual-capture legs, refunds, and other merchant operations use your API key.
Keep the credential on your backend, tied to your own signed browser session, and relay checkout calls through your backend with your own CSRF and origin checks. Never put it in local storage, URLs, logs, or analytics. Decide whether you need a checkout session has the full list of what it can do, and Securing a headless checkout covers the boundary and what changes for PCI scope once your JavaScript runs on the payment page.
Pay in more than one leg#
Split tender, partial payment, and a staged amount need legs you create first, with POST /v1/orders/{order_id}/payment-intents. Collect a credential for each leg in your own UI, then confirm them together with action: "confirm_payment_intents", one entry per leg in payment_intents. While legs exist, payment_collection.stripe.elements.selectable_payment_intents lists the ones the buyer can still pay, each with its own payment_collection. Split one payment across two cards walks through a two-card order request by request.
Hosted checkout pays an order with one payment method, so it can collect at most one unpaid leg, meaning a leg still waiting for a payment method or for its first confirmation:
- Creating a hosted checkout session for an order with two or more unpaid legs returns
409 RESOURCE_IN_USE, with the legs aspayment_intentreferences indetails[0].blocking_resources. - While a hosted session is open, creating a leg on an order that already has an unpaid one returns
409 RESOURCE_IN_USE.details[0].blocking_resourceslists the unpaid leg, anddetails[0].current_resourcenames the session.
In either case, cancel a leg with POST /v1/payment-intents/{payment_intent_id}/cancel, or collect the split payment in your own UI. An embedded checkout session has no such limit, because your UI collects each leg.
Manual capture#
To authorize now and capture later, create one leg with "capture_method": "manual" through POST /v1/orders/{order_id}/payment-intents, then confirm it with action: "confirm_payment_intents". The attempt ends requires_capture, and the order stays open and unpaid until you capture.
Capture with POST /v1/payment-intents/{payment_intent_id}/capture, or release the hold with /cancel. Neither takes an attempt ID. Both accept expected_version, which is the PaymentIntent's own version, not the order's. A stale value returns 409 VERSION_CONFLICT before Flint contacts Stripe, so nothing is captured or released. Stripe events also advance the leg's version, so read the leg just before you capture, and on a conflict read it again and check status and capturable_money before you decide.
A manual-capture attempt confirms exactly one leg, so split payment with delayed capture is refused. Amounts, partial capture, and authorization expiry are in Manual capture on orders.
Errors#
A declined card is not an error: it comes back as a 200 with a failed attempt. These are the errors this flow returns for misuse or changed state.
Test it#
In a sandbox, enter these cards in the Payment Element with any future expiry date and any CVC:
| Card | What happens |
|---|---|
4242 4242 4242 4242 | The payment succeeds and the order becomes paid. |
4000 0025 0000 3155 | The attempt returns requires_action. Complete the challenge and the resume succeeds; fail it and the attempt ends failed. |
4000 0000 0000 0002 | The attempt ends failed with card_declined, so you can exercise the retry. |
Testing lists every test card. To run these scenarios from a terminal without a browser, pay with a Stripe test token such as pm_card_visa, as in Pay from the API with a test token.
