Quickstart: Submit a Sandbox Card Checkout with the TokenEx iFrame
By the end of this page you will have:
- Locked a cart so its price and items can't be altered.
- Shown the TokenEx iFrame on your page. The customer enters the card inside the iFrame, so the card number never reaches your page or your servers.
- Received a token for the card and checked that it is genuine.
- Recorded a gateway handover for the locked cart. Your processor confirms the payment separately.
This takes about 30 minutes and works in the sandbox. No card-network credentials are needed.
What you need
| Item | Used for | From |
|---|---|---|
| Base URL of the IXOPAY Payment Agent | Locking carts and completing payments (/v1/*) | Your IXOPAY integration manager |
| Merchant ID | Identifies your store in carts | Your IXOPAY integration manager |
| Gateway credential | Authenticate server-side requests to the independently provisioned gateway origin. The examples use X-API-Key. | Your integration manager |
| TokenEx ID and iFrame Customer Secret Key | Sign the iFrame configuration and verify the returned token on your server. | TokenEx Customer Portal, iFrame Configuration |
| Token Scheme | The token format the iFrame produces (the TokenEx examples use PCI) | Your IXOPAY / TokenEx account |
| Sandbox test cards | Testing the iFrame | Your IXOPAY integration manager |
| The origin of your checkout page | Must be exact, for example https://shop.example.org. In production it must be HTTPS | You |
Replace <ixopay-payment-agent-host> with your provisioned gateway host. Set TOKENEX_ID to the tenant ID for this environment and IXOPAY_GATEWAY_KEY to its gateway credential on your server.
A complete, runnable version of this page is available to download: checkout-server.js and iframe-checkout.html.
How it fits together
| Where | What happens |
|---|---|
| Checkout server | Price the cart, call POST /v1/negotiate, and save the returned sessionId and invoiceHash with the order. Sign the iFrame configuration on the server. |
| Checkout page | Load the signed configuration. The customer enters their card inside the TokenEx iFrame. When the page calls iframe.tokenize(), send the returned token and tokenHMAC to your server. |
| Checkout server | Verify tokenHMAC. Send the token as uttToken to POST /v1/checkout/complete with the stored session ID and invoice hash. Keep the iFrame Customer Secret Key and gateway credential on the server. |
| Order processing | Keep the order pending after SETTLEMENT_COMPLETE. Fulfill it once your processor confirms the payment for the same order, amount, and currency. |
Step 1. Lock the cart (server)
Amounts are integers in minor units (cents). Item fields are exactly id, name, price, qty, and amount must equal sum(price × qty) + taxCents + shippingCents.
curl -X POST https://<ixopay-payment-agent-host>/v1/negotiate \
-H "Content-Type: application/json" \
-H "X-API-Key: $IXOPAY_GATEWAY_KEY" -H "tx-tokenex-id: $TOKENEX_ID" \
-d '{
"agentId": "web-checkout",
"cartParams": {
"merchantId": "<your-merchant-id>",
"currency": "USD",
"amount": 4200,
"items": [
{ "id": "SKU-A", "name": "Lip Treat", "price": 1600, "qty": 1 },
{ "id": "SKU-B", "name": "Glazing Fluid", "price": 2600, "qty": 1 }
]
}
}'
{
"sessionId": "sess_0f2f9565-ba19-479f-af8a-43cb9f53e44c",
"invoiceHash": "e53d7b6af2c008d2fbec41e8ef8ddfac1fcaf3daa41a1c687369d5de7991a627",
"status": "PARAMETER_NEGOTIATION",
"expiresIn": 300
}
The lock lasts 300 seconds. The invoiceHash is a SHA-256 fingerprint of the cart. Any later change to the total, currency, merchant or line items breaks it and the payment is refused. Store the cart, sessionId and invoiceHash on your server.
The sample hash e53d7b6af2c008d2fbec41e8ef8ddfac1fcaf3daa41a1c687369d5de7991a627 is produced only when merchantId is merch_demo_01 (with the cart above). A different merchantId gives a different hash.
Step 2. Generate the iFrame Authentication Key (server)
Required for merchants embedding the TokenEx iFrame. If you use only the signed-agent payment flow, skip this step and follow the Agent Developer Guide.
The Authentication Key is a Base64 HMAC-SHA256, keyed with your TokenEx iFrame Customer Secret Key, over this pipe-delimited string:
tokenExID|origin|timestamp|tokenScheme
timestampis the current time in UTC, formattedyyyyMMddHHmmss. A key is valid for 20 minutes.origin,tokenExID,timestampandtokenSchememust be identical to the values in the iFrame configuration object. For example, if the configuration saysPCI, signPCI, not a scheme number.
const crypto = require("crypto");
// Call with apiKey: process.env.TOKENEX_IFRAME_SECRET
function tokenExAuthenticationKey({ tokenExID, origin, tokenScheme, apiKey }) {
const timestamp = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14); // yyyyMMddHHmmss, UTC
const data = `${tokenExID}|${origin}|${timestamp}|${tokenScheme}`;
const authenticationKey = crypto.createHmac("sha256", apiKey).update(data, "utf8").digest("base64");
return { authenticationKey, timestamp };
}
Your server returns this configuration to your page, together with sessionId and invoiceHash. Never return the TokenEx iFrame Customer Secret Key.
Step 3. Show the TokenEx iFrame (browser)
Load the TokenEx iFrame script from TokenEx's servers (do not self-host it). In the sandbox the script is https://test-htp.tokenex.com/iframe/iframe-v3.min.js; your production script address comes from TokenEx. Then create the iFrame in a container on your page:
<div id="tokenExIframeDiv"></div>
<button id="pay" disabled>Pay now</button>
<p id="status"></p>
<script src="https://test-htp.tokenex.com/iframe/iframe-v3.min.js"></script>
<script>
async function start() {
const statusEl = document.getElementById("status");
// Your server returns { sessionId, invoiceHash, iframeConfig } (Steps 1 and 2).
const init = await (await fetch("/checkout/start", { method: "POST" })).json();
// iframeConfig: { tokenExID, origin, timestamp, authenticationKey, tokenScheme, pci: true }
const iframe = new TokenEx.Iframe("tokenExIframeDiv", init.iframeConfig);
iframe.on("load", () => {
document.getElementById("pay").disabled = false;
});
iframe.on("validate", (d) => {
if (!d.isValid) statusEl.textContent = "Check the card details";
});
iframe.on("error", (e) => {
statusEl.textContent = "Card step failed: " + e.error;
});
iframe.on("tokenize", async (data) => {
// data: { token, tokenHMAC, referenceNumber, firstSix, lastFour, cardType, ... }
const r = await fetch("/checkout/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId: init.sessionId, token: data.token, tokenHMAC: data.tokenHMAC }),
});
statusEl.textContent = r.ok ? "Submitted. Awaiting payment confirmation." : "Could not confirm checkout.";
});
iframe.load();
document.getElementById("pay").onclick = () => iframe.tokenize();
}
start();
</script>
The iFrame configuration needs origin, tokenExID (numeric), tokenScheme, authenticationKey, timestamp and, for card data, pci: true. Call iframe.validateConfig() if the iFrame does not appear; it reports which property is missing or invalid. The full list of events, functions and styling options is in the TokenEx iFrame documentation.
All communication between your page and the iFrame uses postMessage inside the TokenEx library. You do not write postMessage code yourself.
Step 4. Verify the token and complete the payment (server)
The token travels through the browser, so check it before you trust it. tokenHMAC is the Base64 HMAC-SHA256 of the token, keyed with your TokenEx iFrame Customer Secret Key (the apiKey parameter below):
function tokenIsGenuine(token, tokenHMAC, apiKey) {
const expected = crypto.createHmac("sha256", apiKey).update(token, "utf8").digest("base64");
const a = Buffer.from(expected),
b = Buffer.from(tokenHMAC || "");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
If it is genuine, complete the payment. Use the sessionId and invoiceHash you stored in Step 1, not values from the browser:
curl -X POST https://<ixopay-payment-agent-host>/v1/checkout/complete \
-H "Content-Type: application/json" \
-H "X-API-Key: $IXOPAY_GATEWAY_KEY" -H "tx-tokenex-id: $TOKENEX_ID" \
-d '{ "sessionId": "sess_0f2f9565-…", "invoiceHash": "e53d7b6a…a627", "uttToken": "<token>", "protocol": "TOKENEX_DIRECT" }'
{
"status": "SETTLEMENT_COMPLETE",
"statusCode": 200,
"sessionId": "sess_0f2f9565-…",
"transactionId": "tx_hpp_…",
"settlementRail": "TokenEx UTT Direct",
"tokenExUttReference": "<token>",
"authCode": "UTT_48213",
"pciScope": "SAQ_A_LEVEL_1_ISOLATED",
"invoiceHashMatch": true,
"zeroPanScrubbed": true
}
Always send the invoiceHash from your stored lock. SETTLEMENT_COMPLETE acknowledges the gateway record. Keep the order pending until your processor confirms the authorization or capture required for fulfillment. Match the processor record to the order, amount and currency before shipping. Release notes
What success looks like
- The iFrame appears and your
loadhandler fires. - After you call
tokenize(), your page gets atokenizeevent with a token andtokenHMAC, plusfirstSixandlastFouronly, never a full card number. - Your server confirms
tokenHMAC, and/v1/checkout/completereturnsstatus: SETTLEMENT_COMPLETE.
If it doesn't work
| You see | Likely cause | Fix |
|---|---|---|
The iFrame does not appear, or an error event says "Invalid Authentication Key" | origin, tokenExID, timestamp or tokenScheme in the signed string differs from the configuration, or the TokenEx iFrame Customer Secret Key is wrong | Sign exactly the values you pass in the configuration. Run iframe.validateConfig(). |
| "Session expired" | The Authentication Key is older than 20 minutes | Generate a new key and a new timestamp when the page loads. |
| The iFrame is blocked or refuses to load | Your page origin does not match, is not HTTPS in production, or your Content-Security-Policy does not allow the TokenEx iFrame host | Use the exact origin, and allow the TokenEx iFrame host in frame-src and script-src. |
validate reports isValid: false | Card number, expiry or CVV missing or invalid | Ask the customer to re-enter the card. |
tokenHMAC does not match on your server | Wrong TokenEx iFrame Customer Secret Key, or the token was altered in the browser | Do not use the token. Treat the attempt as failed. |
/v1/negotiate returns INVALID_CART_STRUCTURE | Missing field, non-integer amount, or amount does not equal the sum of the lines plus tax and shipping | Match the field names, use cents, and recompute amount. |
/v1/checkout/complete returns SESSION_EXPIRED_OR_NOT_FOUND | Over 300 s between Step 1 and Step 4 | Lock the cart again. |
/v1/checkout/complete returns 409 INVALID_STATE_TRANSITION | That session or token was already completed | Do not resubmit. Start a new purchase with a new lock. |
More in Errors & Troubleshooting.
Where next
- Full merchant checklist and optional manifest and webhook setup: Integration Guide.
- Agents that sign Mastercard or Visa mandates: Agent Developer Guide.
- Every field: API Reference.