@edfapay/checkout-js
v0.1.0
Published
EdfaPay hosted checkout SDK — get a checkout URL or embed the checkout in an iframe with callbacks.
Readme
@edfapay/checkout-js
Accept EdfaPay payments on any website in two ways:
| Mode | You call | You get |
|---|---|---|
| 1. Checkout URL | edfapay.createCheckout(order) | { checkoutUrl, sessionId }: redirect, open a popup, or send a link |
| 2. Embedded iframe | edfapay.mount('#el', { payment, onSuccess, onFailure, onCancel }) | Checkout rendered inside your page, with callbacks when it finishes |
Works with plain JS, any bundler, React (@edfapay/checkout-js/react), Node 18+, and a <script> tag.
npm i @edfapay/checkout-js⚠️ Keep your API key on the server
X-API-KEY is a merchant secret. The same key can also call /payment/refund and /payment/recurring.
If you put it in browser JavaScript, anyone can read it and use it.
So the SDK supports two setups:
- Server (Node):
new EdfaPay({ apiKey })calls the EdfaPay API directly. - Browser:
new EdfaPay({ createSession })asks your backend to callinitiate. Your backend uses the server setup above.
The SDK logs a console warning if it sees apiKey in a browser. You can silence it with dangerouslyAllowBrowserApiKey: true, but only do that if the key is safe to make public.
Setup
Backend (Node)
import { EdfaPay } from '@edfapay/checkout-js';
const edfapay = new EdfaPay({
apiKey: process.env.EDFAPAY_API_KEY,
environment: 'development', // or 'production', or baseUrl: 'https://…'
});
app.post('/api/checkout', async (req, res) => {
const order = await db.orders.find(req.body.orderId); // don't trust amounts from the browser
const session = await edfapay.createCheckout({
orderId: order.id,
amount: order.total,
currency: 'SAR',
customerDetails: { name: order.name, email: order.email },
successUrl: req.body.successUrl, // forwarded from the browser SDK (needed for iframe mode)
failureUrl: req.body.failureUrl,
backButtonUrl: req.body.backButtonUrl,
});
res.json(session); // { checkoutUrl, sessionId, ... }
});Frontend
import { EdfaPay } from '@edfapay/checkout-js';
const edfapay = new EdfaPay({
createSession: (payment) =>
fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payment),
}).then((r) => r.json()),
// needed in the browser so results can be confirmed (and for `pollIntervalMs`)
getStatus: ({ sessionId, orderId }) =>
fetch(`/api/checkout/status?${new URLSearchParams({ sessionId: sessionId ?? '', orderId: orderId ?? '' })}`)
.then((r) => r.json()),
});createSession can return any of these: the raw API envelope, its data, a { checkoutUrl, sessionId } object, or just the URL string.
Mode 1: Get the checkout URL
const { checkoutUrl, sessionId } = await edfapay.createCheckout({
orderId: 'ORD-1001',
amount: 120.5,
currency: 'SAR',
customerDetails: { name: 'Alice', email: '[email protected]' },
successUrl: 'https://shop.com/thanks',
failureUrl: 'https://shop.com/payment-failed',
});
window.location.href = checkoutUrl;
// or the one-liner:
await edfapay.redirectToCheckout(order);Mode 2: Embedded iframe
const checkout = edfapay.mount('#edfapay-checkout', {
payment: { orderId: 'ORD-1001', amount: 120.5, currency: 'SAR' },
height: 640,
onReady: (session) => {},
onSuccess: (result) => { /* result.status === 'success' */ },
onFailure: (result) => {},
onCancel: (result) => {},
onError: (error) => {}, // initiate failed, network error…
onEvent: (event) => {}, // every event: loading | ready | resize | success | failure | cancel | error | message
});
checkout.destroy(); // remove it yourself if needed (it's removed automatically after a final result)After a final result the iframe is removed (autoDestroy). To let the customer try again, call mount() again with a new orderId (or, in React, change the orderId / a key). Reusing the same orderId may be rejected by the API, so check this with your EdfaPay contact.
You can also embed a URL you already created on your server: mount(el, { checkoutUrl, sessionId, ... }).
React
import { EdfaPayCheckout } from '@edfapay/checkout-js/react';
<EdfaPayCheckout
client={edfapay}
payment={{ orderId, amount, currency: 'SAR' }}
onSuccess={(r) => navigate(`/orders/${r.orderId}/thanks`)}
onFailure={(r) => toast.error(r.payment?.reason ?? 'Payment failed')}
onCancel={() => navigate('/cart')}
/>A new session is created only when payment.orderId (or checkoutUrl) changes, so re-renders and React StrictMode won't create duplicate payments.
Showing your own result page (resultDisplay)
Pass your own successUrl / failureUrl (they can differ per payment) and choose where they appear
once the result is known:
<EdfaPayCheckout
client={edfapay}
checkoutUrl={checkoutUrl}
sessionId={sessionId}
payment={{ orderId, successUrl: 'https://shop.example/paid', failureUrl: 'https://shop.example/failed' }}
pollIntervalMs={3000}
resultDisplay="inside" // 'inside' = same iframe, 'outside' = whole page, 'none' = callbacks only (default)
/>With 'inside' the iframe stays mounted (don't unmount it in your callback). With 'outside' the browser
navigates away after your callbacks run. edfapay_status and edfapay_order are appended to the URL.
Only http(s) or relative URLs are used. If an outcome has no URL, nothing is shown for it.
Script tag (no bundler)
<script src="https://unpkg.com/@edfapay/[email protected]/dist/edfapay.global.js"></script>
<script>
const edfapay = new EdfaPay({ createSession: /* … */ });
edfapay.mount('#checkout', { payment: { /* … */ }, onSuccess: console.log });
</script>Result object
{
status: 'success' | 'failure' | 'cancel',
orderId, sessionId, transactionId,
source: 'postMessage' | 'redirect' | 'status-poll',
verified: boolean, // true when the status API confirmed it; false only for a cancel or with allowUnverified
payment?: PaymentStatus, // the status API response that confirmed the result
data?: {...} // extra fields sent by the checkout page
}Always confirm on your server before fulfilling an order. Call
GET /api/v1/payment/status(edfapay.getPaymentStatus({ sessionId })) or use your webhook.onSuccess/onFailurealready wait for the status API, but your server remains the source of truth. Whenresult.verifiedisfalsethe result came from the browser alone (only possible withallowUnverified).
How the iframe learns the result
The SDK listens for the result in three ways. Each callback fires only once.
- postMessage. The hosted checkout page posts a message to
window.parent. See the contract below. It is a hint only (see Payment verification). - Redirect detection (only works if the checkout redirects the iframe to your
successUrl/failureUrl; EdfaPay's own result pages do not do this). In embedded mode the SDK setssuccessUrl,failureUrlandbackButtonUrlto a page on your origin, with?edfapay_status=success|failure|canceladded. When the iframe lands there, the SDK can read the URL because it's the same origin. This is also a hint only. SetreturnUrlto a blank page (seeexamples/edfapay-return.html) so your site never flashes inside the frame. If you setsuccessUrlorfailureUrlyourself, they are used as-is. - Status polling (optional). Use
pollIntervalMs: 3000to poll/payment/status. This needsapiKeyorgetStatus. A final status from the API is delivered directly.
Payment verification
A "success" seen in the browser (postMessage or return redirect) is never trusted on its own. The SDK asks the status API (getStatus or apiKey) and delivers onSuccess / onFailure only when it returns a final status:
| Status API says | Result |
|---|---|
| status: PAID or paymentStatus: APPROVED | success |
| FAILED, DECLINED, EXPIRED, CANCELED (in status or paymentStatus) | failure |
| ACTIVE, REDIRECT, PENDING (e.g. 3DS in progress), unknown values, or a conflict such as PAID + DECLINED | not final: the SDK keeps checking |
| API error, empty or invalid response | not final: the SDK keeps checking |
transactionStatus: SUCCESS and status: SUCCESS alone never count as paid (a 3DS session reports transactionStatus: SUCCESS while still pending). Values are compared trimmed and case-insensitive.
The SDK re-checks every verifyIntervalMs (default 2000) for up to verifyTimeoutMs (default 60000). If the API never confirms, no result is delivered and onError is called. A customer cancel is delivered directly with verified: false.
Without getStatus or apiKey the SDK cannot verify: browser results are ignored, onError is called once, and a warning is logged on mount. To accept unverified results anyway (for example while prototyping), set allowUnverified: true; results then have verified: false and your server must confirm. verify is deprecated and ignored (verification is always on).
Mode 1 (redirect) has no callbacks: on your return page call getPaymentStatus on your server before fulfilling the order.
postMessage contract for the hosted checkout page
window.parent.postMessage({
source: 'edfapay-checkout',
type: 'payment.success', // payment.failure | payment.cancel | ready | resize
data: { orderId, sessionId, transactionId, reason },
height: 712 // only for type 'resize' (auto-sizes the iframe)
}, '*'); // or the merchant origin from document.referrerThe SDK accepts a message only if all of these hold: event.source is its own iframe window; event.origin is exactly the checkout page's origin (not your own origin); the payload is a plain object (or a JSON string up to 10,000 characters) with source: 'edfapay-checkout'; type is a known string of at most 64 characters; data.transactionId, if present, is a string; and a resize height is a finite number between 1 and 10000. Anything else is ignored.
For the checkout page to work inside an iframe, the hosted checkout domain must allow framing: a Content-Security-Policy: frame-ancestors that lists the merchant sites (or *), and no X-Frame-Options: DENY/SAMEORIGIN.
API reference
| Method | Description |
|---|---|
| new EdfaPay(config) | apiKey | createSession, getStatus, environment, baseUrl, timeoutMs, fetch, resolveSession, allowedCheckoutOrigins |
| createCheckout(req) | POST /api/v1/payment/initiate → CheckoutSession |
| redirectToCheckout(req) | Creates the checkout and navigates the page to it |
| mount(el, options) | Embeds the checkout → { iframe, session, destroy() } |
| getPaymentStatus({ sessionId \| orderId \| transactionId }) | GET /api/v1/payment/status |
Errors are thrown as EdfaPayError with httpStatus, code, errorCode and body. The body is sanitised (API keys, tokens, card and personal fields are replaced by [redacted], URL query strings are removed, size is capped), the message is one short line, and an empty or non-JSON response is an EdfaPayError. A custom createSession / getStatus that does not answer within timeoutMs (default 30000) fails with a timeout error.
Checkout URL policy. A checkout URL (from initiate, createSession or checkoutUrl) must be an absolute https URL without credentials on *.edfapay.com. Outside environment: 'production', http://localhost is also accepted. Add your own hosts with allowedCheckoutOrigins: ['https://pay.example.com', 'https://*.example.com'] (they are added to the default). Anything else is rejected with an EdfaPayError and the iframe is never loaded. edfapay.assertCheckoutUrl(url) runs the same check.
resolveSession. The initiate response data currently looks like { redirectUrl, id }. The SDK looks for the URL in checkoutUrl, url, redirectUrl, paymentUrl, sessionUrl and link (including one level deep), and for the session id in sessionId and id. If your response uses other names, override it:
new EdfaPay({ apiKey, resolveSession: (data) => ({ checkoutUrl: data.hppUrl, sessionId: data.token }) });Development
npm install
npm test # vitest + jsdom
npm run build # ESM + CJS + .d.ts + IIFE (dist/edfapay.global.js)
npm publish --access public