Guides
Checkout widget
Drop Qoene delivery options into any checkout: the five products with your contract prices and promised dates, an address field, and a ranked Qoene Point and locker picker with a map. It runs in a frame on js.qoenedelivery.com, inline or as a popup, and hands your page a signed token your server books with.
How it works
Create a publishable key
In the Business workspace, open Settings → API & webhooks, pick the API client and add a checkout widget key with the websites that may show the widget, for example
https://shop.example.com(orhttps://*.example.comfor subdomains;http://localhost:3000for a TEST key while you build). The key looks likeqd_pk_live_…. It is not a secret: it can only read delivery options, promised dates and Qoene Points, only from those websites, and each key has its own per-minute limit.Start a checkout session on your server
When the buyer reaches delivery, your server calls
POST /checkout/sessionswith your secret key (scopecheckout.write). The session fixes the parcel, where it starts and which products you offer, so the browser cannot change what is priced. Pass the session'sclientSecretand your publishable key to the page.Show the widget
Load
qoene-checkout.jsand callQoeneCheckout.mount()(inline) orQoeneCheckout.open()(popup). The buyer enters their address, compares the products and, for Relay, picks a Qoene Point or locker from the ranked list or the map.Receive the signed choice
When the buyer confirms,
onSelectreceives{ token, selectionId, expiresAt, selection }.tokenis a compact JWS signed by Qoene (Ed25519). Send it to your server with the order; showselectionto the buyer.Verify and book on your server
Check the token (offline with the SDK, or with
POST /checkout/selections/verify), then book withcheckoutSelection: tokenonPOST /shipments. Qoene verifies it again, books the exact quote the buyer saw and uses the selection once.
Plain HTML
The whole client side for a server-rendered checkout. It works on any page, including WordPress.
<!-- 1. Where the widget goes -->
<div id="qoene-delivery"></div>
<!-- 2. The script. Pin a version with SRI for production (see "Versions and SRI"). -->
<script src="https://js.qoenedelivery.com/v1/qoene-checkout.js" defer></script>
<script>
// 3. When the buyer reaches delivery, ask YOUR server for a checkout session.
async function showDelivery() {
const { publishableKey, clientSecret } = await fetch('/api/checkout/delivery-session', { method: 'POST' })
.then(response => response.json());
// 4. Show Qoene delivery options inside the page.
QoeneCheckout.mount('#qoene-delivery', {
publishableKey, // qd_pk_live_… (safe in the browser)
session: clientSecret, // qd_cks_… (this checkout only)
theme: 'auto', // 'light' | 'dark' | 'auto'
accent: '#1F3F99', // optional: your brand colour for small accents
onSelect(selection) {
// 5. Send the signed token to your server with the order. Never trust the price from the browser.
document.querySelector('#delivery-token').value = selection.token;
document.querySelector('#delivery-summary').textContent =
selection.selection.name + ' · ' + (selection.selection.totalMinor / 100).toFixed(2) + ' GHS';
},
onClear() { document.querySelector('#delivery-token').value = ''; },
onError(error) { console.warn('Qoene checkout:', error.code, error.message); },
});
}
window.addEventListener('DOMContentLoaded', showDelivery);
</script>
<form method="post" action="/checkout/place-order">
<input type="hidden" id="delivery-token" name="deliveryToken">
<p id="delivery-summary"></p>
<button type="submit">Place order</button>
</form>Popup
Same options. Call open() directly in the click handler (browsers block windows opened later), so fetch the session when the page loads. The window closes itself once the buyer confirms.
<button type="button" id="choose-delivery">Choose delivery</button>
<script>
document.querySelector('#choose-delivery').addEventListener('click', async () => {
// Open the window first, in the click, or the browser blocks it: fetch the session beforehand.
const handle = QoeneCheckout.open({ publishableKey, session: clientSecret, onSelect: saveToken });
const selection = await handle.result; // null when the buyer closes the window
if (!selection) console.log('Buyer closed the delivery window');
});
</script>Create the session (server)
const { session } = await qoene.checkout.createSession({
parcel: { actualWeightGrams: 1200, lengthMm: 300, widthMm: 200, heightMm: 120 },
origin: { pointCode: SHOP_DROPOFF_POINT }, // and/or address: { text, latitude, longitude } for Express
serviceCodes: ['EXPRESS_STANDARD', 'RELAY_POINT', 'RELAY_HOME'], // optional; default all five
orderReference: 'SHOP-1001',
payOnPickup: false,
}, { idempotencyKey: idempotencyKey('cart', cart.id, cart.version, 'delivery-session') });
// → session.clientSecret (qd_cks_…) for the page; session.expiresAt (30 minutes by default)curl -X POST https://api.qoenedelivery.com/v1/checkout/sessions \
-H "Authorization: Bearer $QOENE_API_KEY" \
-H "Idempotency-Key: cart-8812:checkout-v3" \
-H "Content-Type: application/json" \
--data '{"parcel":{"actualWeightGrams":1200,"lengthMm":300,"widthMm":200,"heightMm":120},"origin":{"pointCode":"QD-DO-…"},"orderReference":"SHOP-1001"}'$response = $client->post('checkout/sessions', [
'headers' => ['Idempotency-Key' => "cart-{$cart['id']}:checkout-v{$cart['version']}"],
'json' => [
'parcel' => ['actualWeightGrams' => 1200, 'lengthMm' => 300, 'widthMm' => 200, 'heightMm' => 120],
'origin' => ['pointCode' => $shopDropoffPoint],
'orderReference' => $orderNumber,
],
]);
$session = json_decode((string) $response->getBody(), true)['data']['session'];
// Give $session['clientSecret'] to the page.response = requests.post(
"https://api.qoenedelivery.com/v1/checkout/sessions",
headers={**headers, "Idempotency-Key": f"cart-{cart['id']}:checkout-v{cart['version']}"},
json={"parcel": {"actualWeightGrams": 1200, "lengthMm": 300, "widthMm": 200, "heightMm": 120},
"origin": {"pointCode": shop_dropoff_point}, "orderReference": order_number},
timeout=30,
)
session = response.json()["data"]["session"] # give session["clientSecret"] to the page| Field | Meaning |
|---|---|
parcel | Weight (grams) and sides (millimetres) as packed. Required. |
origin.pointCode | Your drop-off Qoene Point, for the Relay products. |
origin.address | Your pickup address (text, and latitude/longitude if you have them), for Express. |
serviceCodes | Products to offer; default all five. Products you cannot use still show with the reason. |
payOnPickup | Price Relay for payment when the receiver collects. Book with the matching paymentMode. |
orderReference | Used for the booking unless the booking sends its own. |
expiresInMinutes | 5–120, default 30. A price inside it is valid for 30 minutes after it is shown. |
prefill.addressText | Shown in the address field. |
React and Next.js
A small component that loads the script once and mounts the widget, and the route that creates the session. The publishable key may be a public environment variable; the secret key stays in server code.
'use client';
// app/checkout/QoeneDelivery.tsx (Next.js App Router, or any React 18+ app)
import { useEffect, useRef } from 'react';
declare global { interface Window { QoeneCheckout?: any } }
const SCRIPT = 'https://js.qoenedelivery.com/v1/qoene-checkout.js';
function loadQoeneCheckout(): Promise<any> {
if (window.QoeneCheckout) return Promise.resolve(window.QoeneCheckout);
return new Promise((resolve, reject) => {
const tag = Object.assign(document.createElement('script'), { src: SCRIPT, async: true });
tag.onload = () => resolve(window.QoeneCheckout);
tag.onerror = reject;
document.head.appendChild(tag);
});
}
export function QoeneDelivery({ publishableKey, clientSecret, onToken }: {
publishableKey: string; clientSecret: string; onToken: (token: string | null) => void;
}) {
const box = useRef<HTMLDivElement>(null);
useEffect(() => {
let handle: { destroy(): void } | undefined;
let cancelled = false;
loadQoeneCheckout().then(QoeneCheckout => {
if (cancelled || !box.current) return;
handle = QoeneCheckout.mount(box.current, {
publishableKey, session: clientSecret, theme: 'auto',
onSelect: (selection: { token: string }) => onToken(selection.token),
onClear: () => onToken(null),
});
});
return () => { cancelled = true; handle?.destroy(); };
}, [publishableKey, clientSecret, onToken]);
return <div ref={box} />;
}// app/api/checkout/delivery-session/route.ts (runs on your server)
import { QoeneDelivery, idempotencyKey } from '@qoene/delivery';
import { getCart } from '@/lib/cart';
const qoene = new QoeneDelivery({ apiKey: process.env.QOENE_API_KEY! });
export async function POST() {
const cart = await getCart();
const { session } = await qoene.checkout.createSession({
parcel: cart.parcel, // grams and millimetres, from your products
origin: { pointCode: process.env.QOENE_DROPOFF_POINT!, // Relay: where you hand parcels in
address: { text: 'Adwoa Styles, Oxford Street, Osu, Accra', latitude: 5.5566, longitude: -0.1826 } }, // Express pickup
orderReference: cart.orderNumber,
payOnPickup: false,
}, { idempotencyKey: idempotencyKey('cart', cart.id, cart.version, 'delivery-session') });
return Response.json({ publishableKey: process.env.NEXT_PUBLIC_QOENE_PUBLISHABLE_KEY, clientSecret: session.clientSecret });
}Verify the token and book (server)
The token's body is readable by anyone, so never act on it unverified. The SDK checks the Ed25519 signature against Qoene's public keys (GET /checkout/keys, cached for five minutes), the expiry and the environment. In other languages, call POST /checkout/selections/verify, or check the JWS with any EdDSA library (PHP: sodium_crypto_sign_verify_detached).
import { QoeneCheckoutSelectionError } from '@qoene/delivery';
// When the order is placed (and paid, if you take payment first):
export async function bookDelivery(order: { id: string; deliveryToken: string; buyer: { name: string; phone: string } }) {
let claims;
try {
claims = await qoene.checkout.verifySelectionOffline(order.deliveryToken); // signature, expiry, environment
} catch (error) {
if (error instanceof QoeneCheckoutSelectionError) throw new Error('Please choose delivery again');
throw error;
}
// claims.selection: serviceCode, totalMinor (what Qoene charges you), promise, point, deliveryAddress.
// Charge the buyer what YOU decide; this number is signed by Qoene, so the browser cannot change it.
const { shipment } = await qoene.shipments.create({
checkoutSelection: order.deliveryToken, // checked again and used once
description: 'Two cotton shirts, boxed',
sender: { name: 'Adwoa Styles', phone: '0241234567' },
receiver: order.buyer,
paymentMode: 'PAY_ON_PICKUP', // must match the session's payOnPickup
prohibitedItemsDeclaration: { accepted: true, version: DECLARATION_VERSION },
}, { idempotencyKey: `order-${order.id}:book` });
return shipment;
}Online check
const check = await qoene.checkout.verifySelection({ token });
// check.selection, check.used, check.shipmentId, check.expiresAtcurl -X POST https://api.qoenedelivery.com/v1/checkout/selections/verify \
-H "Authorization: Bearer $QOENE_API_KEY" \
-H "Content-Type: application/json" \
--data "{\"token\":\"$DELIVERY_TOKEN\"}"$response = $client->post('checkout/selections/verify', ['json' => ['token' => $_POST['deliveryToken']]]);
$check = json_decode((string) $response->getBody(), true)['data'];
// $check['selection']['totalMinor'], $check['used']response = requests.post(f"{base}/checkout/selections/verify", headers=headers,
json={"token": form["deliveryToken"]}, timeout=30)
check = response.json()["data"] # check["selection"], check["used"]| Refusal | Status | What to do |
|---|---|---|
CHECKOUT_SELECTION_INVALID | 422 | Changed or not issued by Qoene. Ask the buyer to choose delivery again. |
CHECKOUT_SELECTION_EXPIRED | 422 | The price expired (30 minutes). Ask the buyer to choose again. |
CHECKOUT_SELECTION_ENVIRONMENT | 422 | A TEST selection sent with a LIVE key, or the reverse. |
CHECKOUT_SELECTION_USED | 409 | Already booked under another Idempotency-Key. Retrying with the same key returns the original booking. |
CHECKOUT_SELECTION_NOT_FOUND | 404 | Issued for another Business. |
Widget options
| Option | Meaning |
|---|---|
publishableKey | Required. qd_pk_test_… or qd_pk_live_…. Passing a secret key throws, so it never leaves your server by accident. |
session | Required. The session clientSecret. |
onSelect(selection) | The buyer confirmed. selection.token goes to your server. |
onClear() | The buyer pressed Change; forget the previous token. |
onCancel() | Popup closed or Cancel pressed without a choice. |
onError({ code, message }) | For your logs; the widget also explains the problem to the buyer. |
onReady() | The frame has loaded. |
theme | auto (follows the device), light or dark. |
accent | Your brand colour, #RRGGBB, for small parts such as the selected marker. Ignored when it is too light to read on white. |
locale | en today; the text is ready for more languages. |
prefill | { addressText }, overriding the session prefill. |
host | Only for staging (https://js-staging.qoenedelivery.com) or local development. |
mount() returns { frame, update({ theme, accent }), destroy() }; the frame resizes itself to its content. open() returns { window, result, close() }, where result resolves to the selection or null.
Security model
- Secret keys never reach the browser. The browser holds a publishable key and one session secret. Neither can book, cancel, read shipments or change prices.
- Origins are locked. The frame is served with
Content-Security-Policy: frame-ancestorsset to the key's allowed websites, so other sites cannot embed it; the popup refuses any opener origin outside the list; the browser API rejects other origins. - Strict messages. The page and the frame exchange versioned
qoene-checkoutmessages on a random channel, each side checking the other's origin and window. The session secret goes by message, never in a URL. - Prices are signed. The quote, price, promise and point come from Qoene and are signed; the booking re-checks the signature, uses the exact stored quote and accepts each selection once.
- Limits. Each publishable key has a per-minute limit (default 300, set per key); each session can be priced at most 40 times. A 429 carries
Retry-After. - Audit. Creating, changing and revoking publishable keys, prices shown in checkout and every issued selection are recorded with the key and the website.
Message protocol (v1)
You do not need this when you use qoene-checkout.js; it documents what crosses the frame boundary. Every message is { protocol: "qoene-checkout", version: 1, channel, type, payload }.
| Direction | Type | Payload |
|---|---|---|
| frame → page | ready | { widgetVersion }; the page answers with init |
| page → frame | init | { session, theme, accent, locale, prefill } |
| page → frame | update | { theme?, accent? } |
| page → frame | close | {} (popup) |
| frame → page | resize | { height } (inline) |
| frame → page | selection | { token, selectionId, expiresAt, selection } |
| frame → page | cleared, cancel | {} |
| frame → page | error | { code, message } |
Versions and SRI
https://js.qoenedelivery.com/v1/qoene-checkout.js always serves the newest 1.x release (cached for five minutes). Every release also has an immutable path, for example https://js.qoenedelivery.com/v1.0.0/qoene-checkout.js, cached for a year. https://js.qoenedelivery.com/manifest.json lists every version with its Subresource Integrity hash. For production, pin a version with its hash:
<script src="https://js.qoenedelivery.com/v1.0.0/qoene-checkout.js"
integrity="sha384-…from manifest.json…" crossorigin="anonymous" defer></script>If your checkout sends its own Content-Security-Policy, allow script-src https://js.qoenedelivery.com and frame-src https://js.qoenedelivery.com. A page that sets Cross-Origin-Opener-Policy: same-origin cannot receive popup messages; use same-origin-allow-popups or the inline mode.
Testing
Use a publishable key and a secret key from the same TEST API client: the widget shows a "Test mode" label, prices come from the same tariffs and bookings are simulated (QD-TST-…). A TEST selection cannot be booked with a LIVE key. http://localhost origins are allowed for TEST keys only. The reference integration includes a runnable checkout page.