Skip to main content
Version: 1.0.0

Code Sample

Each part below is the least an integration needs. The checkout example is a complete shop, ready to deploy.

Load the plugin​

index.html
HTML
<link  rel="stylesheet"  href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.9/css/bootstrap.min.css"  integrity="sha384-yEPZ7jP9S0QKiUQ0m3jjsO4ProIW7wvR9gXkI7JOGa2XVsw53Yke2bsdkBbjmmiX"  crossorigin="anonymous"/><link rel="stylesheet" href="https://cdnuat.travelpay.com.au/css/zenpay.payment.css" /><script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/4.1.0/jquery.min.js"  integrity="sha512-LAwtVcZXPhBWVFQr9JK27ozsjKIZWJ6Y811gxInOV82L55pvK12upCcTye8dhlVJ5iIllnd4LO0zq9Ue80vxbQ=="  crossorigin="anonymous"></script><script  src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.9/js/bootstrap.min.js"  integrity="sha384-89aa4glufciPv46aKltztWQEmk+Tu9W2RhzXr6VcnUUEub7F8+06RcL2RYLCOHUq"  crossorigin="anonymous"></script><script src="https://cdnuat.travelpay.com.au/js/zenpay.payment.bs5.js"></script> <!-- Bootstrap 5 and jQuery load before the plugin script. -->

Open the plugin​

Ask your server for a signed payment, then pass it to the plugin.

checkout.js
JavaScript
async function pay(orderId) { // Ask your server for a signed payment: the browser never sets the price.  const response = await fetch('/api/checkout', {    method: 'POST',    headers: { 'Content-Type': 'application/json' },    body: JSON.stringify({ orderId }),  });  if (!response.ok) throw new Error('Could not start the payment.'); // fetch does not fail on an error status, so check it before reading the payment.  const payment = await response.json();
  const result = $.zpPayment({    url: payment.url,    apiKey: payment.apiKey,    merchantCode: payment.merchantCode,    fingerprint: payment.fingerprint,    timestamp: payment.timestamp,    merchantUniquePaymentId: payment.merchantUniquePaymentId,    mode: payment.mode,    paymentAmount: payment.paymentAmount,    customerName: payment.customerName,    customerEmail: payment.customerEmail,    customerReference: payment.customerReference,    callbackUrl: payment.callbackUrl,    redirectUrl: payment.redirectUrl,    allowCardOneOffPayment: true, // The payment methods to show. Each one also has to be enabled for your merchant.    allowCardTokenisePayment: true,    allowBankAcOneOffPayment: false,    allowPayIdOneOffPayment: false,    allowPayToOneOffPayment: false,    allowAliPayPlusOneOffPayment: true,    allowApplePayOneOffPayment: true,    allowGooglePayOneOffPayment: true,    allowUnionPayOneOffPayment: true,    allowWeChatOneOffPayment: true,  }).init();
  if (!result.isSuccess) console.error(result.message); // isSuccess is false, with a message, when the plugin could not open.}

Sign the payment​

Your server prices the order, creates the fingerprint and puts a signed token with the payment's details in the callbackUrl, so the callback needs no database. The username and password stay on the server.

server/checkout.ts
TypeScript
import { createHash, createHmac, randomUUID } from 'node:crypto';
const {  ZENPAY_API_KEY,  ZENPAY_MERCHANT_CODE,  ZENPAY_USERNAME,  ZENPAY_PASSWORD,  CALLBACK_SECRET,} = process.env; // Read from the environment. The username and password never leave the server; the API key and merchant code go to the browser.if (  !ZENPAY_API_KEY ||  !ZENPAY_MERCHANT_CODE ||  !ZENPAY_USERNAME ||  !ZENPAY_PASSWORD ||  !CALLBACK_SECRET)  throw new Error('A ZenPay setting is missing.');
const sha3_512 = (fields: Array<string | number | undefined>) =>  createHash('sha3-512').update(fields.join('|')).digest('hex');const sign = (text: string) =>  createHmac('sha3-512', CALLBACK_SECRET).update(text).digest('hex'); // CALLBACK_SECRET is 32 random bytes or more, used for nothing else.
const createCallbackToken = (launch: { // The payment ID, mode and amount, signed so the callback can trust them without a database. The token expires after 7 days.  merchantUniquePaymentId: string;  mode: number;  paymentAmount: number;}) => {  const body = Buffer.from(    JSON.stringify({      ...launch,      expires: Date.now() + 7 * 24 * 60 * 60 * 1000,    }),  ).toString('base64url');  return `${body}.${sign(body)}`;};
export async function createPayment(order: {  amount: number;  customerName: string;  customerEmail: string;  reference: string;}) {  const mode = 0; // Mode 0 is a one-off payment.  const merchantUniquePaymentId = randomUUID(); // Use a new payment ID for every attempt.  const timestamp = new Date().toISOString().slice(0, 19); // UTC, as YYYY-MM-DDTHH:mm:ss, with no milliseconds or timezone.  const amountInCents = Math.round(order.amount * 100); // Rounded, because 19.99 * 100 is 1998.9999999999998 in floating point.  const fingerprint = sha3_512([ // The fingerprint proves this server signed the payment: SHA3-512 of apiKey|username|password|mode|amount in cents|payment ID|timestamp. It lasts 15 minutes, so create it when the customer clicks Pay.    ZENPAY_API_KEY,    ZENPAY_USERNAME,    ZENPAY_PASSWORD,    mode,    amountInCents,    merchantUniquePaymentId,    timestamp,  ]);
  const callbackUrl = new URL('https://shop.example.com/api/zenpay/callback'); // ZenPay posts the result here.  callbackUrl.searchParams.set( // The token tells your callback which payment it is.    't',    createCallbackToken({      merchantUniquePaymentId,      mode,      paymentAmount: order.amount,    }),  );
  return { // What the browser passes to the plugin. The username and password are not in it.    url: 'https://pay.sandbox.travelpay.com.au/Online/v5',    apiKey: ZENPAY_API_KEY,    merchantCode: ZENPAY_MERCHANT_CODE,    fingerprint,    timestamp,    merchantUniquePaymentId,    mode,    paymentAmount: order.amount,    customerName: order.customerName,    customerEmail: order.customerEmail,    customerReference: order.reference,    callbackUrl: callbackUrl.href,    redirectUrl: 'https://shop.example.com/payment/result',  };}

Check the callback​

Check the token's signature and expiry, then recompute the validationCode from the token's payment details and ZenPay's paymentReference. Only paymentStatus 3 is paid. The route reads the token from the address and the body, and answers 200 to every callback.

server/callback.ts
TypeScript
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
const { ZENPAY_API_KEY, ZENPAY_USERNAME, ZENPAY_PASSWORD, CALLBACK_SECRET } =  process.env; // The same credentials that signed the fingerprint.if (!ZENPAY_API_KEY || !ZENPAY_USERNAME || !ZENPAY_PASSWORD || !CALLBACK_SECRET)  throw new Error('A ZenPay setting is missing.');
const sha3_512 = (fields: Array<string | number | undefined>) =>  createHash('sha3-512').update(fields.join('|')).digest('hex');const sign = (text: string) =>  createHmac('sha3-512', CALLBACK_SECRET).update(text).digest('hex');const same = (a: string, b: string) => { // Compares in constant time, so a wrong value does not reveal how much of it matched. It compares bytes, because timingSafeEqual throws when the lengths differ.  const left = Buffer.from(a);  const right = Buffer.from(b);  return left.length === right.length && timingSafeEqual(left, right);};
function verifyCallbackToken(token: string) { // The payment ID, mode and amount the token was signed with, or nothing when its signature is wrong or it has expired.  const [body, signature] = token.split('.');  if (!body || !signature || !same(signature, sign(body))) return;  const launch: {    merchantUniquePaymentId: string;    mode: number;    paymentAmount: number;    expires: number;  } = JSON.parse(Buffer.from(body, 'base64url').toString()); // Read only after the signature matched, so the text is what createCallbackToken wrote.  if (launch.expires > Date.now()) return launch;}
export function handleCallback( // A callback counts only when its token, payment reference and validationCode all check out.  token: string,  body: {    response?: { paymentReference?: string; paymentStatus?: number };    validationCode?: string;  } | null,) {  const launch = verifyCallbackToken(token);  const reference = body?.response?.paymentReference;  if (!launch || !reference || typeof body?.validationCode !== 'string') return;  const amountInCents = Math.round(launch.paymentAmount * 100);
  const expected = sha3_512([ // The same hash as the fingerprint, but ending with ZenPay's payment reference instead of the timestamp.    ZENPAY_API_KEY,    ZENPAY_USERNAME,    ZENPAY_PASSWORD,    launch.mode,    amountInCents,    launch.merchantUniquePaymentId,    reference,  ]);  if (!same(expected, body.validationCode)) return;
  const status = body.response?.paymentStatus;  if (status === 3) return 'paid'; // 3 (Successful) is paid.  if (status === 1 || status === 4 || status === 5) return 'failed'; // 1 (Error), 4 (Failed) and 5 (Cancelled) are treated as failed.}
export async function onCallback(request: Request) { // The route behind your callbackUrl: ZenPay posts JSON, and the token is in the address.  const token = new URL(request.url).searchParams.get('t') ?? '';  const body = await request.json().catch(() => null);  const outcome = handleCallback(token, body);  console.log('callback outcome', outcome); // Update your order here, and only on 'paid'. The same callback can arrive more than once.  return new Response('OK'); // Answer 200 to every callback, whether or not it verified.}