Guide

Embedded payment formBeta

Mount the CX Pay payment form on your website with the hosted JavaScript API. Version 0.0.1 Beta.

Keep your checkout page and place the CX Pay payment form inside it. Your server creates a Checkout Session; the browser mounts it with one call. CX Pay owns the fields, payment button, bank verification and payment-status checks. Interrupted bank verification has a known beta limitation.

0.0.1 Beta covers the complete form. It works on any HTTPS domain registered for your MerchantOrg, in test and live alike; there is no separate switch for live. On an unregistered domain the form shows an error and the browser API emits error with EMBED_ORIGIN_NOT_ALLOWED. Hosted checkout uses the session's returned url. Separate fields, arbitrary layouts inside the form, full-page embeds, npm/React wrappers and NMI are not part of this beta support contract. Confirm the script URL and pay origin with CX Pay before integration testing.

Before you start

  • Create test API credentials for the MerchantOrg receiving the payment. Keep the key and signing secret on your server.
  • Register your HTTPS website and return URL origins in that MerchantOrg's return domains for the test or live mode you use. If another website frames your checkout, register each ancestor origin as well.
  • Enable the payment methods you need. The form shows eligible configured card and wallet methods and supported local, QR and redirect methods. Currency, amount, customer, device and provider capability can affect eligibility. A merchant cannot force an unavailable method through browser options.
  • Complete wallet provider/domain verification separately. Allowlisting a domain with CX Pay alone does not enable Apple Pay or guarantee a wallet button on every device.
  • Configure signed webhooks for fulfillment. The browser can disappear before a payment finishes.

For the initial handoff, use test credentials on the production URLs. Test and live payments use separate data partitions on the same API host; a production URL does not make a test key charge real money. Verify the returned livemode is false in your test-order flow. Use the assigned script URL only after CX Pay confirms its DNS and deployment are ready.

URLs and runnable sample

ResourceURL
API basehttps://api.cxpay.net
Hosted browser scripthttps://js.cxpay.net/v1/cxpay.js
Payment iframe originhttps://pay.cxpay.net
Public sample and setup instructionsCX Pay API samples

For hosted checkout, redirect to the session's returned url; do not build a payment URL yourself. For the embedded form, pass the session's id to the hosted script.

The sample uses Node.js and plain HTML/CSS/JavaScript. Its README covers server-only environment variables, an HTTPS development tunnel, domain registration, stable order retries and optional signed webhooks. It is test-only and defaults to manual capture: an authorized payment remains requires_capture until captured separately. It does not fulfill orders or provide a capture endpoint.

Send CX Pay your integration URLs

Send these through your private support channel before testing:

  • Checkout origin: the exact HTTPS origin where your page runs, for example https://checkout.example.com, without a path or trailing slash. Include every staging and production origin separately, and any ancestor origins if your site is itself embedded.
  • Return and cancel URLs: the full URLs your server will put into checkout creation, for example https://checkout.example.com/return. Include any additional domains they use.
  • Webhook endpoint: the full HTTPS URL that accepts POST requests, for example https://api.example.com/webhooks/cxpay. Identify whether it is for test or live events.

You can manage return and embed origins in the dashboard or through the Return domains API. API changes require return_domains:write granted explicitly; test and live have separate lists. Domain registration does not configure webhooks. CX Pay registers the webhook endpoint, then supplies that endpoint's separate webhook signing secret. Your API signing secret is not the webhook secret. Use raw-body signature verification and event-ID deduplication before processing deliveries.

Use a registered public HTTPS tunnel for local development. Localhost, loopback and IP addresses are refused in both test and live, for return URLs and embedding. The edge may return 403 before the API returns 400 validation. In the sample, set CXPAY_PUBLIC_ORIGIN in .env, restart the server and open that same HTTPS origin.

1. Create a session on your server

Use HMAC request signing. Persist the order, checkout creation idempotency key, request body, session ID and PaymentIntent ID together in your order system. Reuse the key and identical body when retrying a lost response. Do not take the price or an arbitrary return URL from the browser.

JavaScript
1import crypto from "node:crypto";
2
3async function createCheckout(order) {
4 const path = "/v1/checkout-sessions";
5 const body = JSON.stringify({
6 mode: "payment",
7 amount: order.amountMinor,
8 currency: order.currency,
9 return_url: "https://shop.example/checkout/return",
10 metadata: { order_id: order.id },
11 });
12 const timestamp = new Date().toISOString();
13 const nonce = crypto.randomUUID();
14 const bodyHash = crypto.createHash("sha256").update(body).digest("hex");
15 const canonical = ["POST", path, "", timestamp, nonce, bodyHash].join("\n");
16 const signature = crypto.createHmac(
17 "sha256", Buffer.from(process.env.CXPAY_SECRET, "base64")
18 ).update(canonical).digest("base64");
19
20 const response = await fetch(`https://api.cxpay.net${path}`, {
21 method: "POST",
22 headers: {
23 "Content-Type": "application/json",
24 "X-Key-Id": process.env.CXPAY_KEY_ID,
25 "X-Timestamp": timestamp,
26 "X-Nonce": nonce,
27 "X-Body-Hash": bodyHash,
28 "X-Signature": signature,
29 "Idempotency-Key": order.checkoutIdempotencyKey,
30 },
31 body,
32 signal: AbortSignal.timeout(30_000),
33 });
34 if (!response.ok) throw new Error("Checkout creation failed");
35 return response.json();
36}
37
38// In your authenticated order route:
39// save session.id and session.payment_intent against this order;
40// return only { sessionId: session.id } to its browser.

See Checkout Sessions for server options, including capture policy, customer and saved-card settings. Capture policy is set on the server. The embed does not change it. Treat session URLs/IDs as private checkout access links; do not put them in public analytics.

Session IDs and URLs grant access to a checkout: anyone who has one can open its hosted payment page while the session permits it. They are not proof of the customer's identity. Authenticate the order owner before your server returns an existing session, and do not expose other customers' sessions in logs, public pages or analytics.

The domain allowlist restricts embedding, not access to a shared hosted checkout link. The CX Pay iframe reports its framing origins; payment initialization checks them against the MerchantOrg's registered domains and rejects missing or unregistered origins. This check does not make a leaked session ID harmless or authenticate arbitrary API callers. Always verify payment and order ownership on your server before fulfillment.

2. Load the hosted script and mount

Use CX Pay's hosted script directly so compatible fixes can reach your checkout. Your CSS controls the surrounding page; CX Pay renders the secure form in an iframe.

HTML
1<div id="payment-form"></div>
2<p id="checkout-message" role="status"></p>
3<script type="module">
4 const message = document.querySelector("#checkout-message");
5 const script = document.createElement("script");
6 script.src = "https://js.cxpay.net/v1/cxpay.js";
7 const loaded = new Promise((resolve, reject) => {
8 const timer = setTimeout(() => reject(new Error("Script timeout")), 30_000);
9 script.onload = () => { clearTimeout(timer); resolve(); };
10 script.onerror = () => { clearTimeout(timer); reject(new Error("Script unavailable")); };
11 });
12 document.head.appendChild(script);
13
14 try {
15 await loaded;
16 // This merchant route returns the existing session for the signed-in order,
17 // or creates it once on the server. It never returns API credentials.
18 const response = await fetch("/api/checkout", { method: "POST" });
19 if (!response.ok) throw new Error("Session unavailable");
20 const { sessionId } = await response.json();
21 const form = CxPay.embed({
22 session: sessionId,
23 container: "#payment-form",
24 view: "form",
25 });
26
27 form.on("ready", () => { message.textContent = "Payment form ready"; });
28 form.on("error", () => {
29 message.textContent = "Checkout needs attention. Follow the form instructions; keep this page open during bank verification.";
30 });
31 form.on("complete", ({ status }) => {
32 message.textContent = status === "requires_capture"
33 ? "Payment authorized; capture is pending."
34 : "Checking your order confirmation…";
35 // Your confirmation page reads the order from your server.
36 window.location.assign("/order/confirmation");
37 });
38
39 window.addEventListener("pagehide", () => form.unmount(), { once: true });
40 // In a SPA, call form.unmount() when this checkout component leaves the page.
41 // Mount it again with the same session when the customer returns.
42 } catch {
43 message.textContent = "Secure checkout could not load. Refresh to try again.";
44 }
45 </script>

Mount once per checkout container. unmount() is safe to call repeatedly. It removes listeners and the iframe; it does not cancel a payment already sent to the server. If you use browser back/forward caching, remount on pageshow after disposing on pagehide.

Browser API

TypeScript
1const form = CxPay.embed({ session, container, view: "form" });
2const unsubscribe = form.on("change", state => { /* update surrounding UI */ });
3unsubscribe();
4form.unmount();
OptionMeaning
sessionCheckout Session ID returned by your server
containerDOM element or selector
view: "form"Required for the supported beta form experience
methodLayout"spaced" (form default), "grouped", or "tabs". Requires the current hosted SDK and pay runtime; see customization
payUrlOptional pay origin supplied by CX Pay for a development environment; omit in production
autoNavigateOmit for normal behavior: follow required payment redirects and let your page own final navigation
EventPayload and meaning
readyA usable form or visible outcome/recovery screen is ready. Iframe loading alone is insufficient; this is not a payment result
changeIncludes canConfirm, action, method, amount, currency, and optional paymentStatus. In the full form, its own button controls submission; do not call confirm()
complete{ sessionId, status }, where status is succeeded or requires_capture. A browser notification, not fulfillment authorization
error{ code, message }. Use safe text rendering and your normal error reporting; no payment details are included
resize{ height }; the loader adjusts its iframe height automatically
navigate{ url, reason? }. Reasons are payment_redirect or post_completion when provided

For advanced routing, autoNavigate: false delegates all navigation events to your page. You must then perform required payment_redirect navigation promptly. Do not use this option merely to suppress thank-you navigation: the form already leaves final navigation to you by default. autoNavigate: true also follows post-completion navigation.

Bank verification, redirects and delayed outcomes

CX Pay runs the 3DS fingerprint/challenge/complete-action flow. You do not implement a bank popup, listen to provider messages or call complete-action from the merchant page.

Redirect payment methods can navigate the top-level page to the bank. On your registered return page, load the same order's session from your server and mount it again. A success query parameter, a bank return, a closed popup and a complete browser event are not substitutes for the canonical payment result.

Payment statusWhat your integration should do
succeededServer-confirmed captured payment; fulfill once
requires_captureAuthorized only; wait for capture before treating it as paid
processing, uncertain, requires_reviewKeep the order pending; recover its existing attempt and await server/webhook evidence
requires_actionComplete verification in the existing frame. Refreshing during OTP can prevent resuming it; see the known limitation below
Confirmed declineLet the form offer a legitimate retry; do not manufacture a new attempt after a network timeout
Closed/expired sessionThe form displays an authoritative terminal summary when available; otherwise it stays explicit that the result is unknown

Polling is bounded. Check again resumes a status check instead of creating another payment. If the browser closes or session access expires, backend completion and webhooks still drive the order. A checkout session can be complete for an authorized payment, so checkout_session.completed alone does not mean paid.

Known limitation: interrupted bank verification

Do not refresh, navigate away or remount the form while the bank's OTP challenge is open. Refreshing destroys the active challenge: the restored Continue verification screen can fail with Empty TermURL for the CRes POST.

The embed cannot safely recover an interrupted bank challenge. There is no supported reset() or restart-payment API on the embed. If this happens, check the existing payment on your server and contact CX Pay with its session/payment IDs. Do not automatically create a replacement payment or assume that an interrupted browser means a failed payment. Recovering a persisted payment status does not guarantee that a bank challenge can be reopened.

Reporting beta issues

Send the following through your private CX Pay support channel:

  • Expected result, actual result and steps to reproduce.
  • Checkout Session ID and PaymentIntent ID, plus the SDK error code if available.
  • Timestamp with timezone, browser/device and whether the payment is test or live.
  • A screenshot with private details removed, if it helps explain the issue.

Do not send card numbers, CVV, OTPs, API credentials, client secrets, bank challenge URLs or raw network payloads. The current SDK exposes lifecycle/error events; it does not include an automatic diagnostic-payload export tool.

Fulfill once, on your server

Verify the webhook signature against raw bytes. For payment_intent.succeeded, retrieve the PaymentIntent with your server credentials and verify its ID, succeeded status, amount, currency and livemode against the order's stored binding. Scope the order to the owning MerchantOrg. Never accept those values from the browser.

Persist event deduplication, the paid-order transition and a fulfillment-outbox entry in one database transaction. For example, with your own PostgreSQL order/inbox/outbox tables and a unique outbox key per order:

SQL
1BEGIN;
2WITH received AS (
3 INSERT INTO webhook_inbox (merchant_org_id, livemode, event_id)
4 VALUES ($1, $2, $3)
5 ON CONFLICT DO NOTHING
6 RETURNING event_id
7), paid AS (
8 UPDATE orders SET status = 'paid'
9 WHERE merchant_org_id = $1 AND livemode = $2
10 AND payment_intent_id = $4 AND amount_minor = $5 AND currency = $6
11 AND status <> 'paid' AND EXISTS (SELECT 1 FROM received)
12 RETURNING id
13)
14INSERT INTO fulfillment_outbox (order_id)
15SELECT id FROM paid
16ON CONFLICT (order_id) DO NOTHING;
17COMMIT;

The parameters come from the verified event and the independently retrieved payment. Check the order binding before recording the event as processed. Return 200 only after committing; return an error if processing fails so delivery can retry. Your fulfillment worker must also be idempotent. Different events or browser refreshes for the same payment must not ship an order twice.

Setup troubleshooting

SymptomCheck
Hosted script does not loadCheck browser access to the script URL, DNS and your page's Content Security Policy. Changing API credentials does not fix script delivery.
INVALID_RETURN_URLRegister the checkout and return origins for the MerchantOrg that owns the API key. Use the registered HTTPS origin in your server configuration.
EMBED_ORIGIN_NOT_ALLOWEDThe page framing the form is not on the MerchantOrg's registered domains. Register its HTTPS origin, and every ancestor's if another site frames yours. The same list covers test and live.
CAPTURE_METHOD_LOCKEDMatch the request's capture method to the MerchantOrg's payment configuration. A manual-capture account cannot request automatic capture.
Sample /api/checkout returns HTTP 502Read its sanitized error message for the upstream API status. The sample wraps creation failures in a local 502; that alone does not identify a tunnel failure.
Editing configuration does not fix an existing sample orderSaved orders retain their original request body, capture method and return URL. Reconcile that order before replacing it; never discard an unresolved payment just to retry.

See the sample troubleshooting instructions for distinguishing a confirmed validation rejection from an unknown payment outcome.

Styling

Style the merchant page and the container normally: width, spacing, surrounding text and responsive layout. Keep the container visible, with enough width for the form; avoid fixed heights and clipping. The loader handles changing height during validation and verification.

CSS
1#payment-form { width: 100%; max-width: 560px; min-width: 0; }

Merchant CSS does not cross the iframe. Beta has no arbitrary CSS injection, appearance option or field-level styling API on embed(). The form reuses the hosted checkout components and their supported merchant settings. It does not require a merchant banner, logo or order summary.

See Customize checkout for method layouts, matching loading skeletons, mount-time settings and the boundary between your CSS and the secure form. Options demonstrated on the development branch are not evidence that a production CDN release has been enabled.

Browsers and security policy

Verify your required browsers and actual wallet devices in test mode before launch, including bank verification, redirects and returning to an unfinished payment. This guide does not certify minimum browser versions. Embedded in-app browsers/WebViews are outside this beta support contract.

Use a direct iframe integration on Firefox. Nested Firefox embedding is not supported because the browser cannot supply the full ancestor chain. Chrome and Safari nesting requires every ancestor to be an allowed HTTPS origin. Do not add a restrictive sandbox to the generated iframe; it needs scripts, forms, provider frames, wallet permissions and required navigation.

If your page has a Content Security Policy, allow https://js.cxpay.net in script-src and https://pay.cxpay.net in frame-src (or the CX-provided environment origins). Preserve your existing policy and nonce/hash requirements for your own scripts. Your page should send at least its origin as the iframe referrer; strict-origin-when-cross-origin works for the direct Firefox case. no-referrer can prevent origin validation where the ancestor API is unavailable.

Versioning

Load the hosted script from the URL confirmed for your environment. CX Pay updates the script and iframe runtime centrally. Active documents keep their loaded code through a release; they are not hot-swapped during 3DS. Do not self-host the script or pin its contents with Subresource Integrity if you expect managed updates.

Powered by CX Pay