Skip to main content

Build a TokenEx iFrame checkout

Goal: a small server that prices a cart, locks it, generates the iFrame Authentication Key, serves a page with the TokenEx iFrame, verifies the token, completes the payment, and receives the webhook.

You need Node 18+, Express, the provisioned HTTPS Payment Agent origin and gateway key, a merchant ID, a webhook signing secret and a registered receiver. For the iFrame, obtain your TokenEx ID, token scheme and iFrame Customer Secret Key. Keep each secret on the server and use it only for its intended service.

The complete files are available to download: checkout-server.js and iframe-checkout.html. They are shown below.

// server.js
const express = require("express");
const crypto = require("crypto");

const BASE = process.env.IXOPAY_URL; // https://<ixopay-payment-agent-host>
const MERCHANT_ID = process.env.IXOPAY_MERCHANT_ID;
const WEBHOOK_SECRET = process.env.IXOPAY_WEBHOOK_SECRET;
const TOKENEX_ID = process.env.TOKENEX_ID;
const IFRAME_SECRET = process.env.TOKENEX_IFRAME_SECRET;
const GATEWAY_KEY = process.env.IXOPAY_GATEWAY_KEY;
const TOKEN_SCHEME = process.env.TOKENEX_TOKEN_SCHEME || "PCI";
const PAGE_ORIGIN = process.env.PAGE_ORIGIN; // exact origin of your checkout page, e.g. https://shop.example.org

const PRICES = { "SKU-A": { name: "Lip Treat", price: 1600 }, "SKU-B": { name: "Glazing Fluid", price: 2600 } };
if (!GATEWAY_KEY || !IFRAME_SECRET || !TOKENEX_ID || !WEBHOOK_SECRET || !MERCHANT_ID || !PAGE_ORIGIN) {
throw new Error("Missing checkout configuration");
}
if (new URL(BASE).protocol !== "https:") throw new Error("Configure an HTTPS gateway origin");

const orders = new Map(); // sessionId -> { cart, invoiceHash, status }

// Build the TokenEx iFrame configuration with a fresh Authentication Key.
function iframeConfig() {
const timestamp = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14); // yyyyMMddHHmmss, UTC
const signed = `${TOKENEX_ID}|${PAGE_ORIGIN}|${timestamp}|${TOKEN_SCHEME}`;
const authenticationKey = crypto.createHmac("sha256", IFRAME_SECRET).update(signed, "utf8").digest("base64");
return {
tokenExID: TOKENEX_ID,
origin: PAGE_ORIGIN,
timestamp,
authenticationKey,
tokenScheme: TOKEN_SCHEME,
pci: true,
};
}

// The token passes through the browser, so check its HMAC before trusting it.
function tokenIsGenuine(token, tokenHMAC, apiKey) {
const expected = crypto.createHmac("sha256", apiKey).update(String(token), "utf8").digest("base64");
const a = Buffer.from(expected),
b = Buffer.from(String(tokenHMAC || ""));
return a.length === b.length && crypto.timingSafeEqual(a, b);
}

const app = express();

// 1. Price and lock the cart. Prices come from YOUR data, never from the request.
app.post("/checkout/start", express.json(), async (req, res) => {
const items = [];
for (const line of req.body.lines || []) {
const p = PRICES[line.id];
const qty = Number.isInteger(line.qty) && line.qty > 0 ? line.qty : null;
if (!p || !qty) return res.status(400).json({ error: "BAD_LINE" });
items.push({ id: line.id, name: p.name, price: p.price, qty });
}
if (!items.length) return res.status(400).json({ error: "EMPTY_CART" });
const amount = items.reduce((s, i) => s + i.price * i.qty, 0); // must equal sum(lines) + tax + shipping, or /v1/negotiate returns 400

const cart = { merchantId: MERCHANT_ID, currency: "USD", amount, items };
const r = await fetch(`${BASE}/v1/negotiate`, {
method: "POST",
redirect: "error",
headers: { "Content-Type": "application/json", "X-API-Key": GATEWAY_KEY, "tx-tokenex-id": TOKENEX_ID },
body: JSON.stringify({ agentId: "web-checkout", cartParams: cart }),
signal: AbortSignal.timeout(5000),
});
const lock = await r.json();
if (!r.ok) return res.status(502).json({ error: "CART_LOCK_FAILED" });

orders.set(lock.sessionId, { cart, invoiceHash: lock.invoiceHash, status: "LOCKED" });
// The browser gets the iFrame configuration and the session reference, never your secrets.
res.json({ sessionId: lock.sessionId, iframeConfig: iframeConfig() });
});

// 2. The browser sends back the token the iFrame produced. Verify it, then finish the payment.
app.post("/checkout/finish", express.json(), async (req, res) => {
const order = orders.get(req.body.sessionId);
if (!order || order.status !== "LOCKED") return res.status(409).json({ error: "NOT_PAYABLE" });
if (!tokenIsGenuine(req.body.token, req.body.tokenHMAC, IFRAME_SECRET))
return res.status(400).json({ error: "TOKEN_NOT_GENUINE" });
order.status = "PAYING"; // guard against double submit

let out;
try {
const r = await fetch(`${BASE}/v1/checkout/complete`, {
method: "POST",
redirect: "error",
headers: { "Content-Type": "application/json", "X-API-Key": GATEWAY_KEY, "tx-tokenex-id": TOKENEX_ID },
body: JSON.stringify({
sessionId: req.body.sessionId,
uttToken: req.body.token,
invoiceHash: order.invoiceHash, // from YOUR stored lock, not from the browser
protocol: "TOKENEX_DIRECT",
}),
signal: AbortSignal.timeout(5000),
});
out = await r.json();
if (!r.ok || out.status !== "SETTLEMENT_COMPLETE" || !out.transactionId) throw new Error("Unconfirmed handover");
} catch {
order.status = "RECONCILIATION_REQUIRED";
return res.status(502).json({ error: order.status });
}
order.status = "AWAITING_PROCESSOR";
order.transactionId = out.transactionId; // reconcile this handover with the processor
res.json({ status: order.status, transactionId: out.transactionId });
});

// 3. Webhook: raw body, verify, idempotent.
const seen = new Set(); // Sandbox only. Persist events atomically in production.
app.post("/ixopay-webhook", express.raw({ type: "application/json" }), (req, res) => {
const parts = Object.fromEntries(
String(req.get("X-Ixopay-Signature") || "")
.split(",")
.map((p) => p.split("=")),
);
const t = parseInt(parts.t, 10);
const expected = crypto
.createHmac("sha256", WEBHOOK_SECRET)
.update(`${t}.${req.body.toString("utf8")}`)
.digest("hex");
const ok =
t &&
parts.v1 &&
Math.abs(Date.now() / 1000 - t) <= 300 &&
/^[0-9a-f]{64}$/.test(parts.v1) &&
crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
if (!ok) return res.sendStatus(401);
const evt = JSON.parse(req.body.toString("utf8"));
if (!seen.has(evt.eventId)) {
seen.add(evt.eventId); /* reconcile evt.transactionId here */
}
res.sendStatus(200);
});

app.use(express.static("public"));
app.listen(4000);
<!-- public/index.html: browser side (iframe-checkout.html) -->
<div id="tokenExIframeDiv"></div>
<button id="pay" disabled>Pay now</button>
<p id="status" role="status"></p>

<!--
Load the script from TokenEx's servers. Do not self-host it.
This is the sandbox address; your production address comes from TokenEx.
Your Content-Security-Policy must allow the TokenEx host in script-src and frame-src.
-->
<script src="https://test-htp.tokenex.com/iframe/iframe-v3.min.js"></script>
<script>
// Works with checkout-server.js in this folder: run it, then open http://localhost:4000.
// Your server prices and locks the cart (POST /v1/negotiate), signs the iFrame Authentication Key
// with your TokenEx iFrame Customer Secret Key, and returns { sessionId, iframeConfig }. iframeConfig is
// { tokenExID, origin, timestamp, authenticationKey, tokenScheme, pci: true }
// Never put the TokenEx iFrame Customer Secret Key or your /v1/* credentials in this page.
const statusEl = document.getElementById("status");
const payBtn = document.getElementById("pay");

async function start() {
// Send only SKUs and quantities. The server looks up the prices.
const init = await (
await fetch("/checkout/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
lines: [
{ id: "SKU-A", qty: 1 },
{ id: "SKU-B", qty: 1 },
],
}),
})
).json();
if (!init.iframeConfig) throw new Error(init.error || "could not start checkout");

const iframe = new TokenEx.Iframe("tokenExIframeDiv", init.iframeConfig);

iframe.on("load", () => {
payBtn.disabled = false;
});
iframe.on("validate", (d) => {
statusEl.textContent = d.isValid ? "" : "Check the card details";
});
iframe.on("error", (e) => {
statusEl.textContent = "Card step failed: " + e.error;
payBtn.disabled = false;
});
iframe.on("tokenize", async (data) => {
// data: { token, tokenHMAC, referenceNumber, firstSix, lastFour, cardType }
// Send the token and its HMAC to your server, which verifies the HMAC and completes the payment.
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(); // run iframe.validateConfig() if the iFrame does not appear
payBtn.onclick = () => {
payBtn.disabled = true;
iframe.tokenize();
};
}

start().catch((e) => {
statusEl.textContent = "Error: " + e.message;
});
</script>

Run it:

IXOPAY_URL=https://<ixopay-payment-agent-host> \
IXOPAY_MERCHANT_ID=<your-merchant-id> \
IXOPAY_WEBHOOK_SECRET=<webhook-signing-secret> \
TOKENEX_ID=<your-tokenex-id> \
IXOPAY_GATEWAY_KEY=<gateway-key> TOKENEX_IFRAME_SECRET=<iframe-customer-secret> \
TOKENEX_TOKEN_SCHEME=PCI \
PAGE_ORIGIN=http://localhost:4000 \
node server.js

Then open http://localhost:4000 and pay with a sandbox test card. PAGE_ORIGIN must be exactly the origin you open in the browser, because it is signed into the iFrame Authentication Key. In production the origin must be HTTPS.

If you use the downloaded checkout-server.js instead, run node checkout-server.js with the same environment variables, with iframe-checkout.html in the same folder. It serves the page at /.

What to notice

  • The browser never sends a price. The server rebuilds the cart from PRICES.
  • The TokenEx iFrame Customer Secret Key stays on the server. The page only receives the iFrame configuration (which contains a signed, 20-minute Authentication Key) and the sessionId. The card is typed into the TokenEx iFrame, so your page and server never see it.
  • status: PAYING stops a double-click from completing twice. The Payment Agent also refuses a repeat with 409 INVALID_STATE_TRANSITION.
  • Keep the order pending after handover. Fulfill from the stored cart after the downstream processor confirms the payment for this order, amount and currency.