Skip to main content

Quickstart: Submit a Sandbox Card Checkout with the TokenEx iFrame

By the end of this page you will have:

  1. Locked a cart so its price and items can't be altered.
  2. 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.
  3. Received a token for the card and checked that it is genuine.
  4. 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​

ItemUsed forFrom
Base URL of the IXOPAY Payment AgentLocking carts and completing payments (/v1/*)Your IXOPAY integration manager
Merchant IDIdentifies your store in cartsYour IXOPAY integration manager
Gateway credentialAuthenticate server-side requests to the independently provisioned gateway origin. The examples use X-API-Key.Your integration manager
TokenEx ID and iFrame Customer Secret KeySign the iFrame configuration and verify the returned token on your server.TokenEx Customer Portal, iFrame Configuration
Token SchemeThe token format the iFrame produces (the TokenEx examples use PCI)Your IXOPAY / TokenEx account
Sandbox test cardsTesting the iFrameYour IXOPAY integration manager
The origin of your checkout pageMust be exact, for example https://shop.example.org. In production it must be HTTPSYou

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​

WhereWhat happens
Checkout serverPrice the cart, call POST /v1/negotiate, and save the returned sessionId and invoiceHash with the order. Sign the iFrame configuration on the server.
Checkout pageLoad 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 serverVerify 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 processingKeep 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
  • timestamp is the current time in UTC, formatted yyyyMMddHHmmss. A key is valid for 20 minutes.
  • origin, tokenExID, timestamp and tokenScheme must be identical to the values in the iFrame configuration object. For example, if the configuration says PCI, sign PCI, 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 load handler fires.
  • After you call tokenize(), your page gets a tokenize event with a token and tokenHMAC, plus firstSix and lastFour only, never a full card number.
  • Your server confirms tokenHMAC, and /v1/checkout/complete returns status: SETTLEMENT_COMPLETE.

If it doesn't work​

You seeLikely causeFix
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 wrongSign exactly the values you pass in the configuration. Run iframe.validateConfig().
"Session expired"The Authentication Key is older than 20 minutesGenerate a new key and a new timestamp when the page loads.
The iFrame is blocked or refuses to loadYour page origin does not match, is not HTTPS in production, or your Content-Security-Policy does not allow the TokenEx iFrame hostUse the exact origin, and allow the TokenEx iFrame host in frame-src and script-src.
validate reports isValid: falseCard number, expiry or CVV missing or invalidAsk the customer to re-enter the card.
tokenHMAC does not match on your serverWrong TokenEx iFrame Customer Secret Key, or the token was altered in the browserDo not use the token. Treat the attempt as failed.
/v1/negotiate returns INVALID_CART_STRUCTUREMissing field, non-integer amount, or amount does not equal the sum of the lines plus tax and shippingMatch the field names, use cents, and recompute amount.
/v1/checkout/complete returns SESSION_EXPIRED_OR_NOT_FOUNDOver 300 s between Step 1 and Step 4Lock the cart again.
/v1/checkout/complete returns 409 INVALID_STATE_TRANSITIONThat session or token was already completedDo not resubmit. Start a new purchase with a new lock.

More in Errors & Troubleshooting.

Where next​