npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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 call initiate. 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 / onFailure already wait for the status API, but your server remains the source of truth. When result.verified is false the result came from the browser alone (only possible with allowUnverified).


How the iframe learns the result

The SDK listens for the result in three ways. Each callback fires only once.

  1. postMessage. The hosted checkout page posts a message to window.parent. See the contract below. It is a hint only (see Payment verification).
  2. 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 sets successUrl, failureUrl and backButtonUrl to a page on your origin, with ?edfapay_status=success|failure|cancel added. When the iframe lands there, the SDK can read the URL because it's the same origin. This is also a hint only. Set returnUrl to a blank page (see examples/edfapay-return.html) so your site never flashes inside the frame. If you set successUrl or failureUrl yourself, they are used as-is.
  3. Status polling (optional). Use pollIntervalMs: 3000 to poll /payment/status. This needs apiKey or getStatus. 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.referrer

The 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