Embedded checkout: Pesepay Elements on your own page: the quickstart, guides, framework packages and migration from the Direct API, without the generated reference # Embedded checkout > Take payments on your own page with Pesepay Elements, for every payment method including cards with 3-D Secure. Embedded checkout puts Pesepay’s payment fields on your own page. The customer picks a method, types their details and pays without leaving your site. Every method works, including Visa and Mastercard with 3-D Secure, and card details never reach your page or your servers. The fields are **Pesepay Elements**: components you mount into your page from a script tag or from npm, with packages for React, Vue and Angular. The checkout element is a payment form, Pay button included, that you place inside your own checkout page rather than sending the customer to ours. [Quickstart ](/embedded-checkout/quickstart/)Take your first payment on your own page, in plain HTML, JavaScript, React, Vue or Angular. ## How it fits together [Section titled “How it fits together”](#how-it-fits-together) 1. 1 Your server creates the payment 2. 2 Your page mounts the checkout element 3. 3 The customer pays in the element 4. 4 Your server confirms the payment 1) **Your server** creates the transaction with your integration and encryption keys, the same call Hosted checkout uses, and gets back a reference number. Neither key goes near the browser. 2) **Your page** passes that reference number to Elements, which lists the methods the transaction can be paid with and shows each one’s fields. 3) **The customer pays** with the element’s own Pay button. The element runs every step, from 3-D Secure to waiting for an EcoCash approval, then shows the result and tells your page how the payment ended. To use your own Pay button instead, see [Custom payment flow](/embedded-checkout/custom-payment-flow/). 4) **Your server** checks the transaction before it fulfils the order. What the browser reports is for your page; only your server’s check is proof of payment. Creating the transaction and checking it on your server are the same as in every Pesepay integration. See [How payments work](/payments/how-payments-work/) and [The result callback](/webhooks/result-callback/). Already on the Direct API? See [Migrate from the Direct API](/embedded-checkout/migrate-from-seamless/). ## Where card details go [Section titled “Where card details go”](#where-card-details-go) Elements loads its code from `js.pesepay.com`, so fixes reach your checkout without a redeploy. Card fields run in a frame served from a Pesepay origin: your page can place and style it, but cannot read what is typed into it. For Mastercard and Zimswitch, the customer types the card number into the card provider’s own form, which keeps it off your page in the same way. ## Payment methods [Section titled “Payment methods”](#payment-methods) The checkout element shows every method the transaction can be paid with, with the total and fee for the one the customer picks. | Method | What the customer does | | --------------------- | ---------------------------------------------------------- | | Visa | Types the card into Pesepay’s card fields, then 3-D Secure | | Mastercard, Zimswitch | Pays in the card provider’s form inside the element | | EcoCash | Approves a prompt on their phone | | O’mari | Types the code sent to them by SMS | | InnBucks, PayGo | Scans a code with the provider’s app | Each kind has a guide: [Cards and 3-D Secure](/embedded-checkout/guides/cards/), [Mobile money approval](/embedded-checkout/guides/mobile-money/) and [Scan to pay](/embedded-checkout/guides/scan-to-pay/). The [payment methods](/payment-methods/overview/) pages cover limits and currencies for each one. Before you go live, read [Accept a payment](/embedded-checkout/guides/accept-a-payment/). ## Packages [Section titled “Packages”](#packages) ![](/_astro/javascript.BxUIoaTT_Z1z4nbv.svg) [@pesepay/js ](/embedded-checkout/javascript/)[npm](https://www.npmjs.com/package/@pesepay/js) The loader and TypeScript types, for any page or framework. `npm install @pesepay/js` ![](/_astro/react.BwygIBQc_Z1z4nbv.svg) [@pesepay/react ](/embedded-checkout/react/)[npm](https://www.npmjs.com/package/@pesepay/react) React components and hooks. React 18 or 19. `npm install @pesepay/js @pesepay/react` ![](/_astro/vue.RJ05orgw_Z1z4nbv.svg) [@pesepay/vue ](/embedded-checkout/vue/)[npm](https://www.npmjs.com/package/@pesepay/vue) Vue components and composables. Vue 3.5 or later. `npm install @pesepay/js @pesepay/vue` ![](/_astro/angular.DgldPURs_Z1z4nbv.svg) [@pesepay/angular ](/embedded-checkout/angular/)[npm](https://www.npmjs.com/package/@pesepay/angular) Standalone Angular components. Angular 22 or later. `npm install @pesepay/js @pesepay/angular` The framework packages wrap the same elements as components and build on `@pesepay/js`. You can also skip npm and load `https://js.pesepay.com/v1/pesepay.js` with a script tag, as the [`@pesepay/js`](/embedded-checkout/javascript/) page shows. The [quickstart](/embedded-checkout/quickstart/) shows all five ways, and every export is in the [Elements SDK reference](/embedded-checkout/reference/). # @pesepay/angular > Standalone Angular components for Pesepay Elements, with signal inputs, injection helpers and server rendering. ![](/_astro/angular.DgldPURs_Z1z4nbv.svg) `@pesepay/angular` [npm](https://www.npmjs.com/package/@pesepay/angular) Standalone Angular components for Pesepay Elements. Angular 22 or later; no zone.js required. `npm install @pesepay/js @pesepay/angular` The components create, mount and destroy the elements from [`@pesepay/js`](/embedded-checkout/javascript/) for you, including under server rendering. They are standalone components with signal inputs. ## Take a payment [Section titled “Take a payment”](#take-a-payment) Your server creates the transaction and passes its reference number to the component: src/app/checkout.component.ts ```ts import { Component, computed, input, output } from "@angular/core"; import type { CheckoutOutcome } from "@pesepay/js"; import { CheckoutElement, Elements } from "@pesepay/angular"; @Component({ selector: "app-checkout", imports: [Elements, CheckoutElement], template: ` `, }) export class CheckoutComponent { readonly referenceNumber = input.required(); /** * The payment has ended and the element shows the result. Fulfil the order * on your server, which Pesepay notifies too. */ readonly finished = output(); protected readonly options = computed(() => ({ referenceNumber: this.referenceNumber(), })); // The methods could not load: Pesepay's hosted checkout takes the payment. leave(fallbackUrl: string | undefined): void { if (fallbackUrl) window.location.assign(fallbackUrl); } } ``` The component and its selector are yours to name. The Pesepay parts are the `` tags inside it. `` lists the methods and pays with its own button. It runs every step itself, including the result when the customer comes back from 3-D Secure, and emits `(finished)` once with `outcome`: `succeeded`, `failed`, `reversed` or `unknown`. For your own Pay button, see [Custom payment flow](/embedded-checkout/custom-payment-flow/). ## `` [Section titled “\”](#pesepay-elements) | Input | Type | Notes | | --------- | --------------------------------------------- | ------------------------------------------------------------------------- | | `pesepay` | `Pesepay \| null \| Promise` | Optional. What `loadPesepay()` returns. Fixed on first render. | | `options` | `ElementsOptions` | `theme`, `fonts`, `locale` for every element inside. Changes are applied. | Left out, `pesepay` defaults to loading Pesepay with the default options in the browser. To set options, such as `apiBaseUrl`, call `loadPesepay({ apiBaseUrl })` once, in a field, and pass the promise. `` creates one elements group after the first render in the browser, once Pesepay has loaded, and destroys it, and every element in it, when it is destroyed. A new `options` object is passed to `elements.update()` unless it equals the one applied. Give it a new object rather than changing one in place. Export it to a template variable with `#checkout="pesepayElements"` to pay from the component that renders it: `checkout.instance()` and `checkout.elements()` are signals. In a component inside it, `injectPesepay()` and `injectElements()` return the same two signals. All of them are `null` while Pesepay loads and during server rendering. The inject functions throw outside ``. ## Element components [Section titled “Element components”](#element-components) | Component | Element | `options` | | ------------------------------- | ------------ | ------------------------------- | | `` | `checkout` | required: `{ referenceNumber }` | | `` | `payment` | required: `{ referenceNumber }` | | `` | `card` | optional | | `` | `mobile` | optional: `{ provider }`, … | | `` | `scan` | optional: `{ provider }` | | `` | `hostedCard` | required: `{ cardCheckout }` | Import each from `@pesepay/angular` as `CheckoutElement`, `PaymentElement`, `CardElement`, `MobileElement`, `ScanElement` and `HostedCardElement`. Each mounts its element into its own host element, which is `display: block`. Outputs are typed for the element: `(ready)`, `(elementChange)`, `(focus)`, `(blur)`, `(escape)` and `(loadError)`, plus `(status)` on the mobile and payment elements and `(finished)` on the checkout element. `elementChange` is the element’s `change` event. It is not called `change` because Angular would also deliver the DOM `change` events that bubble out of the card provider’s form. Changed `options` are passed to the element’s `update()`. A payment or checkout element given a new `referenceNumber` is replaced, since one element pays one transaction. Outside the checkout element, to pay, read the element off the group with `elements.getElement(type)` and pass it to `confirmPayment()`. One `` holds one element of each type; for two card fields, use two ``. ## Server rendering [Section titled “Server rendering”](#server-rendering) `` loads nothing before the first render in the browser, and `loadPesepay()` resolves `null` on the server. On the server each element component renders as an empty host element. See [Server-side rendering](/embedded-checkout/guides/server-rendering/). ## What’s next [Section titled “What’s next”](#whats-next) * [Quickstart](/embedded-checkout/quickstart/): the whole checkout, server included * [Guides](/embedded-checkout/guides/accept-a-payment/): each method, errors and theming, with Angular code * [Elements SDK reference](/embedded-checkout/reference/angular/): every component and injection helper # Custom payment flow > Use the payment element with your own Pay button, and handle each step of the payment in your code. The [Quickstart](/embedded-checkout/quickstart/) uses the checkout element, which pays with its own button and runs every step itself. Use the payment element instead when you want your own Pay button and each step in your code. Your code then handles three things the checkout element does for you: 1. **O’mari’s SMS code.** The first `confirmPayment()` returns `nextAction.type === "enter_otp"` and the element asks for the code. Confirm again once the customer has typed it. 2. **The wait.** EcoCash and scan codes return `outcome === "processing"` while the customer finishes on their phone. Wait with `waitForTransaction()`. 3. **The return page.** A Visa card that needs 3-D Secure, and Mastercard or Zimswitch, leave for the bank and come back to the transaction’s `returnUrl`. Read the result there with `handleRedirectResult()`. Create the payment on your server and install Elements as in the Quickstart: [Create the payment on your server](/embedded-checkout/quickstart/#create-the-payment-on-your-server) and [Install Elements](/embedded-checkout/quickstart/#install-elements). ## Pay with your own button [Section titled “Pay with your own button”](#pay-with-your-own-button) * JavaScript Your server writes the reference number into the form: checkout.html ```html

``` src/custom-pay.ts ```ts import { loadPesepay } from "@pesepay/js"; const form = document.querySelector("#payment-form")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = form.dataset.referenceNumber!; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const payment = pesepay.elements().create("payment", { referenceNumber }); payment.on("change", (event) => { message.textContent = event.error?.message ?? ""; }); // The methods could not load: Pesepay's hosted checkout takes the payment. payment.on("loaderror", (event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }); payment.mount("#payment"); form.addEventListener("submit", async (event) => { event.preventDefault(); // If a card needs 3-D Secure, the browser leaves for the bank here. const result = await pesepay.confirmPayment(referenceNumber, { element: payment }); if (result.error) { message.textContent = result.error.message; return; } // O'mari: the element now asks for the code from the SMS. Pay again once // it is typed. if (result.transaction.nextAction?.type === "enter_otp") return; // EcoCash or a scan code: wait while the customer finishes on their phone. const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(referenceNumber, { timeoutMs: 300_000 }) : result; message.textContent = paid.error ? paid.error.message : paid.transaction.outcome; }); } void start(); ``` * React CheckoutForm.tsx ```tsx import { useState } from "react"; import { Elements, PaymentElement, useElements, usePesepay } from "@pesepay/react"; export function CheckoutForm({ referenceNumber }: { referenceNumber: string }) { return ( ); } function PayForm({ referenceNumber }: { referenceNumber: string }) { const pesepay = usePesepay(); const elements = useElements(); const [message, setMessage] = useState(""); async function pay(): Promise { const payment = elements?.getElement("payment"); if (!pesepay || !payment) return; // If a card needs 3-D Secure, the browser leaves for the bank here. const result = await pesepay.confirmPayment(referenceNumber, { element: payment }); if (result.error) { setMessage(result.error.message); return; } // O'mari: the element now asks for the code from the SMS. Pay again once // it is typed. if (result.transaction.nextAction?.type === "enter_otp") return; // EcoCash or a scan code: wait while the customer finishes on their phone. const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(referenceNumber, { timeoutMs: 300_000 }) : result; setMessage(paid.error ? paid.error.message : paid.transaction.outcome); } return (
{ event.preventDefault(); void pay(); }} > setMessage(event.error?.message ?? "")} // The methods could not load: Pesepay's hosted checkout takes the payment. onLoadError={(event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }} />

{message}

); } ``` `usePesepay()` and `useElements()` return `null` until Pesepay has loaded, which is why `pay()` checks both. * Vue Checkout.vue ```vue ``` `` hands its default slot the Pesepay instance and the elements group, so the component that renders it can pay. A child component can read the same two with `usePesepay()` and `useElements()`. * Angular custom-checkout.component.ts ```ts import { Component, computed, input, signal } from "@angular/core"; import type { Elements as PesepayElements, Pesepay } from "@pesepay/js"; import { Elements, PaymentElement } from "@pesepay/angular"; @Component({ selector: "app-custom-checkout", imports: [Elements, PaymentElement], template: `

{{ message() }}

`, }) export class CustomCheckoutComponent { readonly referenceNumber = input.required(); protected readonly options = computed(() => ({ referenceNumber: this.referenceNumber(), })); readonly message = signal(""); // The methods could not load: Pesepay's hosted checkout takes the payment. leave(fallbackUrl: string | undefined): void { if (fallbackUrl) window.location.assign(fallbackUrl); } async pay( event: Event, pesepay: Pesepay | null, elements: PesepayElements | null, ): Promise { event.preventDefault(); const payment = elements?.getElement("payment"); if (!pesepay || !payment) return; // If a card needs 3-D Secure, the browser leaves for the bank here. const result = await pesepay.confirmPayment(this.referenceNumber(), { element: payment, }); if (result.error) { this.message.set(result.error.message); return; } // O'mari: the element now asks for the code from the SMS. Pay again once // it is typed. if (result.transaction.nextAction?.type === "enter_otp") return; // EcoCash or a scan code: wait while the customer finishes on their phone. const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(this.referenceNumber(), { timeoutMs: 300_000, }) : result; this.message.set(paid.error ? paid.error.message : paid.transaction.outcome); } } ``` `#checkout="pesepayElements"` gives the template the Pesepay instance and the elements group. A component inside it can read the same two with `injectPesepay()` and `injectElements()`. The payment element’s `change` event is the `(elementChange)` output: Angular would also deliver the DOM `change` events that bubble out of the card provider’s form to an output named `change`. ## Handle the return from the bank [Section titled “Handle the return from the bank”](#handle-the-return-from-the-bank) A card that leaves for its bank comes back to the `returnUrl` you set when you created the payment, with `?referenceNumber=` added. On that page, load Elements the same way and read the result: return page ```ts const result = await pesepay.handleRedirectResult(); if (result.error?.code === 'no_redirect_result') { // An ordinary page load, not a return from the bank. } else if (result.error) { showMessage(result.error.message); } else { showMessage(result.transaction.outcome); // for example "succeeded" } ``` ## Confirm the payment on your server [Section titled “Confirm the payment on your server”](#confirm-the-payment-on-your-server) Don’t fulfil the order on what the browser reports. Confirm it on your server as in the Quickstart’s [Confirm the payment on your server](/embedded-checkout/quickstart/#confirm-the-payment-on-your-server). ## What’s next [Section titled “What’s next”](#whats-next) * [Your own method picker](/embedded-checkout/guides/method-picker/): list the methods yourself, with one element per method * [Errors and fallbacks](/embedded-checkout/guides/errors/): what to show for each result # Accept a payment > Take Embedded checkout from a first test payment to production, with one transaction per order, every outcome handled and orders fulfilled from your server. The [Quickstart](/embedded-checkout/quickstart/) takes one payment. This page covers what a live checkout needs on top of it: one transaction per order, an answer for every outcome, fulfilment from your server, a fallback when Elements can’t load, and your Content-Security-Policy. The page code stays the Quickstart’s. ## One transaction per order [Section titled “One transaction per order”](#one-transaction-per-order) Create the transaction when the customer reaches your checkout page, and store its `referenceNumber` with the order. Every later visit to that page renders the stored reference, not a new one: * **A reload** shows the same transaction. If it is already paid, or still being paid, the checkout element shows its result or waits for it instead of offering the methods again. * **A return from the bank** (Visa with 3-D Secure, Mastercard, Zimswitch) comes back to your `returnUrl` with `?referenceNumber=` added. Render the order’s stored reference and the element shows the result. A new transaction for every page load would leave the order with several, and a customer who reloads after paying could be offered the methods again. ## Answer every outcome [Section titled “Answer every outcome”](#answer-every-outcome) The checkout element sends `finished` once, with an `outcome`. It has already shown the customer the result, so your page only decides what happens next. | Outcome | What your page does | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `succeeded` | Move the customer on, for example to an order page that says the payment is being confirmed. Fulfil from your server (below). | | `failed` | Offer to try again. A failed transaction can’t be paid again, so create a new one for the order and render the element with its reference: a new reference replaces the element. | | `reversed` | The money went back to the customer. Treat the order as unpaid, as for `failed`. | | `unknown` | No answer came in time, and the customer may still pay. Don’t offer to pay again. Tell them you will confirm by email, and wait for your result callback. | Caution For `unknown`, wait for the result callback rather than calling the status check in a loop. A transaction that is still being approved needs no help from your server to finish. ## Fulfil from your server [Section titled “Fulfil from your server”](#fulfil-from-your-server) Never fulfil on what the browser reports: a page can be edited, and `finished` only says what the element saw. Pesepay posts the final status to your `resultUrl`. 1. [Verify the callback](/webhooks/verifying-callbacks/) is from Pesepay. 2. [Check the payment status](/api/check-payment-status/) once for its `referenceNumber`, and fulfil only on `SUCCESS`. 3. Fulfil each order once. Failed deliveries are [never retried](/webhooks/retries/), so a reconciliation job checks orders whose callback never came, and it can see the same payment as your handler. Record the reference you fulfilled and ignore repeats. ## When Elements can’t load [Section titled “When Elements can’t load”](#when-elements-cant-load) Two things can stop the checkout element, and both have a way out: * **`loadPesepay()` resolves `null`**: the runtime didn’t load, for example behind a content blocker. The Quickstart shows a message. You can also send the customer to the transaction’s Hosted checkout page: keep the `redirectUrl` your server got when it created the transaction. * **The element sends `loaderror`**: the methods couldn’t load. When the event carries a `fallbackUrl`, send the customer there and Pesepay’s Hosted checkout page takes the payment. The Quickstart’s code already does this. ## Content-Security-Policy [Section titled “Content-Security-Policy”](#content-security-policy) If your checkout page sends a `Content-Security-Policy` header, add the sources for each method you take: | Method | Add | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | Every method | `script-src https://js.pesepay.com` and `connect-src https://api.pesepay.com` | | Visa | `frame-src https://elements.pesepay.com` | | EcoCash and O’mari | Nothing more | | InnBucks | `img-src data:`, for the QR code | | PayGo | `img-src https://api.paygo.co.zw`, for the QR code | | Mastercard and Zimswitch | `https://eu-prod.oppwa.com` in `script-src`, `style-src`, `img-src`, `connect-src` and `form-action`, and `frame-src https:` for 3-D Secure | | The checkout element | `img-src https://elements.pesepay.com`, for the method logos, plus the sources for each method it offers | A page taking every method can start from this, joined into one header line: ```text script-src 'self' https://js.pesepay.com https://eu-prod.oppwa.com; style-src 'self' https://eu-prod.oppwa.com; img-src 'self' data: https://elements.pesepay.com https://api.paygo.co.zw https://eu-prod.oppwa.com; connect-src 'self' https://api.pesepay.com https://eu-prod.oppwa.com; frame-src https:; form-action 'self' https://eu-prod.oppwa.com ``` Mastercard and Zimswitch need the widest policy, because their 3-D Secure step runs in a frame from the customer’s bank, which can be any host. Keep your scripts in their own files, as the Quickstart does, so you don’t need `'unsafe-inline'`. ## Before you go live [Section titled “Before you go live”](#before-you-go-live) Pay a small live amount with each method you will offer, on your production keys: the sandbox simulates outcomes and runs neither 3-D Secure nor the card providers’ forms. Then work through the [go-live checklist](/getting-started/go-live-checklist/). ## What’s next [Section titled “What’s next”](#whats-next) * [Cards and 3-D Secure](/embedded-checkout/guides/cards/), [Mobile money approval](/embedded-checkout/guides/mobile-money/) and [Scan to pay](/embedded-checkout/guides/scan-to-pay/): what each method asks of the customer # Cards and 3-D Secure > How Visa, Mastercard and Zimswitch are paid in Embedded checkout, the 3-D Secure trip to the bank, and the card elements for your own method picker. Card details never reach your page. Visa is typed into Pesepay’s card fields, and Mastercard and Zimswitch into the card provider’s own form, both inside your checkout. When the bank asks for 3-D Secure, the customer goes to the bank and comes back to your page. | Card | Where the customer types it | Element | | ------------------------ | --------------------------- | ------------ | | Visa | Pesepay’s card fields | `card` | | Mastercard and Zimswitch | The card provider’s form | `hostedCard` | ## In the checkout element [Section titled “In the checkout element”](#in-the-checkout-element) There is nothing to code. The customer picks a card method, types the card and presses the element’s Pay button. 1. **3-D Secure.** If the bank asks for it, the browser leaves for the bank. Mastercard and Zimswitch always go to the bank. 2. **The return.** The customer comes back to the `returnUrl` your server set on the transaction, with `?referenceNumber=` added. Point it at your checkout page. 3. **The result.** Render the page with the order’s reference, and the element shows the result and sends `finished`. [Accept a payment](/embedded-checkout/guides/accept-a-payment/) covers reusing the order’s transaction on that return. ## With your own method picker [Section titled “With your own method picker”](#with-your-own-method-picker) Use the card elements when you build the method picker yourself. Each one takes one kind of card, and you pay from your own button. ### Visa [Section titled “Visa”](#visa) The card fields render in a frame on `elements.pesepay.com`. You pass the element to `confirmCardPayment()` and the frame pays. A Mastercard number returns `use_mastercard_option`, so you can send the customer to your Mastercard option. * JavaScript checkout.html ```html

``` src/card-pay.ts ```ts import { loadPesepay } from "@pesepay/js"; const form = document.querySelector("#card-form")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = form.dataset.referenceNumber!; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } // The card fields render in a Pesepay frame: your page never sees the card. const card = pesepay.elements().create("card"); card.on("change", (event) => { message.textContent = event.error?.message ?? ""; }); card.mount("#card"); form.addEventListener("submit", async (event) => { event.preventDefault(); // If the bank asks for 3-D Secure, the browser leaves for it here and // comes back to the transaction's returnUrl. const result = await pesepay.confirmCardPayment(referenceNumber, { element: card }); if (result.error) { // A Mastercard number returns use_mastercard_option: offer your // Mastercard option instead. message.textContent = result.error.message; return; } message.textContent = result.transaction.outcome; }); } void start(); ``` * React CardForm.tsx ```tsx import { useState } from "react"; import { CardElement, Elements, useElements, usePesepay } from "@pesepay/react"; export function CardForm({ referenceNumber }: { referenceNumber: string }) { return ( ); } function PayByCard({ referenceNumber }: { referenceNumber: string }) { const pesepay = usePesepay(); const elements = useElements(); const [message, setMessage] = useState(""); async function pay(): Promise { const card = elements?.getElement("card"); if (!pesepay || !card) return; // If the bank asks for 3-D Secure, the browser leaves for it here and // comes back to the transaction's returnUrl. const result = await pesepay.confirmCardPayment(referenceNumber, { element: card }); // A Mastercard number returns use_mastercard_option: offer your // Mastercard option instead. setMessage(result.error ? result.error.message : result.transaction.outcome); } return (
{ event.preventDefault(); void pay(); }} > {/* The card fields render in a Pesepay frame: your page never sees the card. */} setMessage(event.error?.message ?? "")} />

{message}

); } ``` * Vue CardPay.vue ```vue ``` * Angular card-pay.component.ts ```ts import { Component, input, signal } from "@angular/core"; import type { Elements as PesepayElements, Pesepay } from "@pesepay/js"; import { CardElement, Elements } from "@pesepay/angular"; @Component({ selector: "app-card-pay", imports: [Elements, CardElement], template: `

{{ message() }}

`, }) export class CardPayComponent { readonly referenceNumber = input.required(); readonly message = signal(""); async pay( event: Event, pesepay: Pesepay | null, elements: PesepayElements | null, ): Promise { event.preventDefault(); const card = elements?.getElement("card"); if (!pesepay || !card) return; // If the bank asks for 3-D Secure, the browser leaves for it here and // comes back to the transaction's returnUrl. const result = await pesepay.confirmCardPayment(this.referenceNumber(), { element: card, }); // A Mastercard number returns use_mastercard_option: offer your // Mastercard option instead. this.message.set(result.error ? result.error.message : result.transaction.outcome); } } ``` ### The return from the bank [Section titled “The return from the bank”](#the-return-from-the-bank) On the page your `returnUrl` points at, load Pesepay and call `handleRedirectResult()`. It reads the reference from the URL and waits for the bank’s answer. It finishes Mastercard and Zimswitch payments too, so one return page serves every card, in any framework. return page ```ts import { loadPesepay } from "@pesepay/js"; const message = document.querySelector("#payment-message")!; async function finish(): Promise { const pesepay = await loadPesepay(); if (!pesepay) return; // Reads ?referenceNumber= from the URL and waits for the bank's answer. const result = await pesepay.handleRedirectResult(); if (result.error?.code === "no_redirect_result") { return; // An ordinary page load, not a return from the bank. } message.textContent = result.error ? result.error.message : result.transaction.outcome; } void finish(); ``` ### Mastercard and Zimswitch [Section titled “Mastercard and Zimswitch”](#mastercard-and-zimswitch) These are paid in the card provider’s own form, which the `hostedCard` element shows in your page. `startCardCheckout()` opens a checkout for the method: `PZW205` for Mastercard, `PZW215` or `PZW213` for Zimswitch. Create the element from it and pay from your own button. Start one checkout per payment. Each call makes a new one and only the newest is tracked, so the examples keep it in `sessionStorage` for a reload. If the form refuses the card, `confirmHostedCardPayment()` returns `incomplete_details` and the form shows the customer what to fix. * JavaScript checkout.html ```html

``` src/hosted-card-pay.ts ```ts import { loadPesepay, type CardCheckout, type Pesepay } from "@pesepay/js"; const form = document.querySelector("#card-form")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = form.dataset.referenceNumber!; // Mastercard. Zimswitch is PZW215 or PZW213. const paymentMethodCode = "PZW205"; // One checkout per payment: each start makes a new one and only the newest // is tracked, so a reload reuses the checkout it already has. async function cardCheckoutFor(pesepay: Pesepay): Promise { const key = `pesepay-card-checkout:${referenceNumber}`; const kept = sessionStorage.getItem(key); if (kept) return JSON.parse(kept) as CardCheckout; const result = await pesepay.startCardCheckout(referenceNumber, paymentMethodCode); if (result.error) return result.error.message; const next = result.transaction.nextAction; if (next?.type !== "card_checkout") return "This card can't be paid here."; sessionStorage.setItem(key, JSON.stringify(next.cardCheckout)); return next.cardCheckout; } async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const cardCheckout = await cardCheckoutFor(pesepay); if (typeof cardCheckout === "string") { message.textContent = cardCheckout; return; } // The card provider's own form, shown in your page. const hostedCard = pesepay.elements().create("hostedCard", { cardCheckout }); hostedCard.mount("#card"); form.addEventListener("submit", async (event) => { event.preventDefault(); // The form checks the card, then the browser leaves for the bank and // comes back to the transaction's returnUrl. const result = await pesepay.confirmHostedCardPayment(referenceNumber, { element: hostedCard, }); if (result.error) message.textContent = result.error.message; }); } void start(); ``` * React HostedCardForm.tsx ```tsx import { useEffect, useState } from "react"; import type { CardCheckout, Pesepay } from "@pesepay/js"; import { Elements, HostedCardElement, useElements, usePesepay } from "@pesepay/react"; // Mastercard. Zimswitch is PZW215 or PZW213. const paymentMethodCode = "PZW205"; export function HostedCardForm({ referenceNumber }: { referenceNumber: string }) { return ( ); } // One checkout per payment: each start makes a new one and only the newest // is tracked, so a reload reuses the checkout it already has. async function cardCheckoutFor( pesepay: Pesepay, referenceNumber: string, ): Promise { const key = `pesepay-card-checkout:${referenceNumber}`; const kept = sessionStorage.getItem(key); if (kept) return JSON.parse(kept) as CardCheckout; const result = await pesepay.startCardCheckout(referenceNumber, paymentMethodCode); if (result.error) return result.error.message; const next = result.transaction.nextAction; if (next?.type !== "card_checkout") return "This card can't be paid here."; sessionStorage.setItem(key, JSON.stringify(next.cardCheckout)); return next.cardCheckout; } function PayByHostedCard({ referenceNumber }: { referenceNumber: string }) { const pesepay = usePesepay(); const elements = useElements(); const [cardCheckout, setCardCheckout] = useState(null); const [message, setMessage] = useState(""); useEffect(() => { if (!pesepay) return; void cardCheckoutFor(pesepay, referenceNumber).then((found) => { if (typeof found === "string") setMessage(found); else setCardCheckout(found); }); }, [pesepay, referenceNumber]); async function pay(): Promise { const hostedCard = elements?.getElement("hostedCard"); if (!pesepay || !hostedCard) return; // The form checks the card, then the browser leaves for the bank and // comes back to the transaction's returnUrl. const result = await pesepay.confirmHostedCardPayment(referenceNumber, { element: hostedCard, }); if (result.error) setMessage(result.error.message); } return (
{ event.preventDefault(); void pay(); }} > {/* The card provider's own form, shown in your page. */} {cardCheckout && }

{message}

); } ``` * Vue HostedCardPay.vue ```vue ``` * Angular hosted-card-pay.component.ts ```ts import { Component, input, signal, type OnInit } from "@angular/core"; import { loadPesepay, type CardCheckout, type Elements as PesepayElements, type Pesepay, } from "@pesepay/js"; import { Elements, HostedCardElement } from "@pesepay/angular"; // Mastercard. Zimswitch is PZW215 or PZW213. const paymentMethodCode = "PZW205"; @Component({ selector: "app-hosted-card-pay", imports: [Elements, HostedCardElement], template: `
@if (cardCheckout(); as cardCheckout) { }

{{ message() }}

`, }) export class HostedCardPayComponent implements OnInit { readonly referenceNumber = input.required(); readonly message = signal(""); readonly cardCheckout = signal(null); // Loaded once, and shared with . protected readonly loading = loadPesepay(); ngOnInit(): void { void this.loading.then(async (pesepay) => { if (!pesepay) return; // On the server, or the runtime could not load. const found = await this.cardCheckoutFor(pesepay); if (typeof found === "string") this.message.set(found); else this.cardCheckout.set(found); }); } // One checkout per payment: each start makes a new one and only the newest // is tracked, so a reload reuses the checkout it already has. private async cardCheckoutFor(pesepay: Pesepay): Promise { const key = `pesepay-card-checkout:${this.referenceNumber()}`; const kept = sessionStorage.getItem(key); if (kept) return JSON.parse(kept) as CardCheckout; const result = await pesepay.startCardCheckout( this.referenceNumber(), paymentMethodCode, ); if (result.error) return result.error.message; const next = result.transaction.nextAction; if (next?.type !== "card_checkout") return "This card can't be paid here."; sessionStorage.setItem(key, JSON.stringify(next.cardCheckout)); return next.cardCheckout; } async pay( event: Event, pesepay: Pesepay | null, elements: PesepayElements | null, ): Promise { event.preventDefault(); const hostedCard = elements?.getElement("hostedCard"); if (!pesepay || !hostedCard) return; // The form checks the card, then the browser leaves for the bank and // comes back to the transaction's returnUrl. const result = await pesepay.confirmHostedCardPayment(this.referenceNumber(), { element: hostedCard, }); if (result.error) this.message.set(result.error.message); } } ``` The provider’s form needs the widest Content-Security-Policy of any method; see [Accept a payment](/embedded-checkout/guides/accept-a-payment/#content-security-policy). ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): every outcome, and fulfilling from your server # CDN, pinning and integrity > Which Embedded checkout runtime path to load, why /v1/ gets security fixes without a redeploy, and how to pin a version with a subresource integrity hash. The runtime is served from `js.pesepay.com`. The npm package is a small loader that fetches it from there, and a script tag loads it directly. Either way, the path you load decides whether the file can change under you. | Path | Cached | Promise | | ---------------------- | ------------------- | ---------------------------------------------------------- | | `/v1/pesepay.js` | 5 minutes | Never breaks. Moves under you, including security patches. | | `/v/pesepay.js` | 1 year, `immutable` | Never changes, never withdrawn, and never patched. | ## Use /v1/ [Section titled “Use /v1/”](#use-v1) `/v1/` is the one to use, and the one the npm loader loads. It is versioned by the runtime’s compatibility contract, not by its release number: a breaking change becomes `/v2/` with a new loader major version, so `/v1/` can be patched for every merchant at once. A fix reaches your checkout within five minutes, with no `npm update` and no redeploy. ```html ``` Don’t add an `integrity` hash to `/v1/`. It is meant to change, and the first patch after you pin a hash would stop your checkout from loading. There is deliberately no published hash for it. ## Pinning a version [Section titled “Pinning a version”](#pinning-a-version) If an auditor requires a fixed file, load a numbered version with its subresource integrity hash. Every pinned build’s `sha384` hash is published at [`https://js.pesepay.com/integrity.json`](https://js.pesepay.com/integrity.json), with the newest as `version`: ```json { "version": "0.2.1", "files": { "/v0.2.1/pesepay.js": "sha384-…", "/v0.1.12/pesepay.js": "sha384-…" } } ``` Load that path with its hash: ```html ``` Pinned builds are never withdrawn, and `integrity.json` keeps listing every one. Use a pinned build from a script tag, as in the [Quickstart](/embedded-checkout/quickstart/)’s script tag tab. The npm loader always loads `/v1/` and has no option to pin. Pinning opts you out of security patches A pinned build is frozen by design, so a fix shipped to `/v1/` does not reach you. You take on watching releases and redeploying a file on your checkout’s critical path. Treat upgrading it as scheduled work. ## Self-hosting [Section titled “Self-hosting”](#self-hosting) `loadPesepay({ scriptOrigin })` loads the runtime from another origin, for local development. Overriding it means you no longer receive patches, the same as pinning, and you take on serving the file yourself. ## Content-Security-Policy [Section titled “Content-Security-Policy”](#content-security-policy) Whichever path you load, your page’s Content-Security-Policy needs `script-src https://js.pesepay.com`. The other sources depend on the methods you take: see [Accept a payment](/embedded-checkout/guides/accept-a-payment/#content-security-policy). ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): taking Embedded checkout to production # Errors and fallbacks > How Embedded checkout reports errors, what to show the customer for each result, and what to do when the elements can't load. Anything a customer, a card or a network causes is **returned**, never thrown. Every confirm and wait resolves to `{ transaction }` or `{ error }`, and the error’s `code` comes from a closed list. Only programmer errors throw: a selector that matches nothing, an element used after `destroy()`, a missing argument. So a `try`/`catch` around a confirm catches your bugs, not declines. The checkout element handles all of this itself and sends one `finished` event: see [Answer every outcome](/embedded-checkout/guides/accept-a-payment/#answer-every-outcome). This page is for the [Custom payment flow](/embedded-checkout/custom-payment-flow/) and [your own method picker](/embedded-checkout/guides/method-picker/), where your code reads each result. ## Branch on the outcome [Section titled “Branch on the outcome”](#branch-on-the-outcome) `transaction.outcome` says what a result means for your checkout. Branch on it, not on `status`, which is Pesepay’s own vocabulary. This function is built and type-checked against the published packages: show-result.ts ```ts import type { ConfirmResult } from "@pesepay/js"; const CHECKING = "We're checking your payment. Please don't pay again."; // What to tell the customer after any confirm or wait. Fulfil the order on // your server, never on this. export function describeResult(result: ConfirmResult): string { // The payment was sent, but its answer was lost: the customer may have paid. if (result.error?.code === "outcome_unknown") return CHECKING; if (result.error) return result.error.message; switch (result.transaction.outcome) { case "succeeded": return "Paid. Thank you!"; case "failed": return result.transaction.message ?? "The payment didn't go through."; case "processing": case "unknown": return CHECKING; case "reversed": return "The payment was reversed, and the money returned."; } } ``` ## “Checking”, not “failed” [Section titled ““Checking”, not “failed””](#checking-not-failed) Two results mean the customer may have paid: * **`outcome: "unknown"`**: Pesepay has no final answer from the provider. * **`error.code === "outcome_unknown"`**: the payment request was sent, but its answer was lost to a timeout, a dropped connection or a server error. Show “checking” for both, and don’t let the customer pay again. Wait for your result callback, or check the transaction from your server first. Never call the confirm again for that payment: it may start a second one. A `timeout` error from a read or a wait means the same: the transaction may still complete. ## Showing an error [Section titled “Showing an error”](#showing-an-error) `error.message` is readable text you can show. `error.type` says how to react: | Type | What happened | What to do | | ----------------------- | ---------------------------------------- | ---------------------------------------------- | | `validation_error` | Checked in the browser; nothing was sent | Show the message; the customer can fix it | | `card_error` | The issuer or processor refused | Show the message; offer another card or method | | `invalid_request_error` | Your integration is wrong | Fix the code; show a generic message | | `authentication_error` | The transaction credential was rejected | Fix the server setup | | `api_error` | Pesepay failed | Retry a read; never retry a confirm blindly | | `network_error` | No response arrived | Retry a read; see `outcome_unknown` above | | `rate_limit_error` | Too many requests | Slow down | Pesepay sends no `429` today, so `rate_limit_error` doesn’t occur yet. Handle it anyway: it keeps your code correct if limits are added. Branch on `error.code`, never on the message. These codes ask for something specific: | Code | What to do | | ------------------------------------ | ----------------------------------------------------------------------------- | | `use_mastercard_option` | A Mastercard number in the Visa card fields. Offer your Mastercard option. | | `card_brand_not_supported` | Amex, JCB or another brand. Ask for another card. | | `wrong_network_phone` | A number EcoCash doesn’t serve, such as NetOne. Ask for an EcoCash number. | | `incomplete_otp` / `invalid_otp` | O’mari’s code is missing digits or isn’t six digits. The customer retypes it. | | `scan_code_unavailable` | No code came back to scan. Create a new transaction. | | `no_redirect_result` | `handleRedirectResult()` on an ordinary page load. Not a failure. | | `frame_load_error` / `frame_timeout` | The card fields didn’t load. Usually a missing `frame-src` in your CSP. | The full list is `PESEPAY_ERROR_CODES`, exported for an exhaustive `switch`. To narrow a caught value, use `isPesepayError(value)` rather than `instanceof`: the loader and the runtime are bundled separately. ## When the elements can’t load [Section titled “When the elements can’t load”](#when-the-elements-cant-load) 1. **The runtime didn’t load**, for example behind a content blocker. `loadPesepay()` resolves `null`. Show a message, or send the customer to the transaction’s Hosted checkout page: keep the `redirectUrl` your server got when it created the transaction. 2. **The payment element couldn’t list the methods**, or a method’s fields failed. It sends `loaderror` with `fallbackUrl`, Pesepay’s Hosted checkout page for the same transaction. Send the customer there, as the [Custom payment flow](/embedded-checkout/custom-payment-flow/) does. 3. **A single-method element couldn’t load**, such as the card fields (`frame_load_error`). Its `loaderror` has no `fallbackUrl`. Offer another method, and check your page’s [Content-Security-Policy](/embedded-checkout/guides/accept-a-payment/#content-security-policy). With your own picker, `listPaymentMethods()` returns `{ error }` when the methods can’t be listed; show the message, or send the customer to the Hosted checkout page at the transaction’s `redirectUrl`, as when the runtime doesn’t load. ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): fulfilling from your server # Your own method picker > List the payment methods yourself, show the total with its fee, and pay with one element per method and one Pay button. The checkout element lists the methods for you. Build your own picker when the methods have to sit in your own layout, for example beside your other ways to pay: 1. `listPaymentMethods()` returns what Pesepay offers in the transaction’s currency. Each method is marked `available` when the order’s amount is within its limits. Show unavailable methods as disabled rather than hiding them. 2. When the customer picks one, `selectPaymentMethod()` returns the total they will pay, fee included. Show it next to the button. 3. Create the element for that method, and destroy the last one. 4. Pay with `confirmPayment()`. It takes any element and calls the right confirm, so one button serves every method. ## The element for each method [Section titled “The element for each method”](#the-element-for-each-method) | Method | Code | Element | | -------- | ------------------ | ------------------------------------ | | Visa | `PZW204` | `card` | | EcoCash | `PZW211`, `PZW201` | `mobile`, with `provider: "EcoCash"` | | O’mari | `PZW216`, `PZW217` | `mobile`, with `provider: "Omari"` | | InnBucks | `PZW212` | `scan`, with `provider: "InnBucks"` | | PayGo | `PZW210` | `scan`, with `provider: "PayGo"` | The first code of each pair is for USD, the second for ZiG. Mastercard (`PZW205`) and Zimswitch (`PZW215`, `PZW213`) pay in the `hostedCard` element, which starts from `startCardCheckout()`: see [Cards and 3-D Secure](/embedded-checkout/guides/cards/). The examples leave them out, and skip any code they don’t know. ## The picker [Section titled “The picker”](#the-picker) The code is built and type-checked against the published packages. * JavaScript checkout.html ```html
Pay with

``` src/picker-pay.ts ```ts import { loadPesepay, type CardElement, type Elements, type MobileElement, type MobileProvider, type ScanElement, type ScanProvider, } from "@pesepay/js"; const form = document.querySelector("#picker-form")!; const methods = document.querySelector("#methods")!; const total = document.querySelector("#total")!; const button = form.querySelector("button")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = form.dataset.referenceNumber!; // The element for each method this page takes. Mastercard and Zimswitch pay // in the hostedCard element, which starts from startCardCheckout(). type Choice = | { type: "card" } | { type: "mobile"; provider: MobileProvider } | { type: "scan"; provider: ScanProvider }; const ELEMENT_FOR: Record = { PZW204: { type: "card" }, // Visa PZW211: { type: "mobile", provider: "EcoCash" }, // USD PZW201: { type: "mobile", provider: "EcoCash" }, // ZiG PZW216: { type: "mobile", provider: "Omari" }, // USD PZW217: { type: "mobile", provider: "Omari" }, // ZiG PZW212: { type: "scan", provider: "InnBucks" }, // USD PZW210: { type: "scan", provider: "PayGo" }, // ZiG }; type MethodElement = CardElement | MobileElement | ScanElement; function create(elements: Elements, choice: Choice): MethodElement { switch (choice.type) { case "card": return elements.create("card"); case "mobile": return elements.create("mobile", { provider: choice.provider }); case "scan": return elements.create("scan", { provider: choice.provider }); } } async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const listed = await pesepay.listPaymentMethods(referenceNumber); if (listed.error) { message.textContent = listed.error.message; return; } const elements = pesepay.elements(); let element: MethodElement | null = null; let paymentMethodCode = ""; const pick = async (code: string): Promise => { paymentMethodCode = code; button.disabled = true; button.textContent = "Pay"; message.textContent = ""; // The total the customer pays with this method, fee included. const priced = await pesepay.selectPaymentMethod(referenceNumber, code); if (priced.error) { message.textContent = priced.error.message; return; } const { currency, total: amount } = priced.amount; total.textContent = `Total: ${amount.toFixed(2)} ${currency}`; // One element at a time: destroy the last method's before creating the next. element?.destroy(); element = create(elements, ELEMENT_FOR[code]!); element.on("change", (event) => { message.textContent = event.error?.message ?? ""; // O'mari has sent its SMS code, and the field now asks for it. if ("step" in event && event.step === "otp") button.textContent = "Confirm code"; }); element.mount("#method-fields"); button.disabled = false; }; // Unavailable methods are shown disabled: the amount is outside their limits. for (const method of listed.paymentMethods) { if (!ELEMENT_FOR[method.code]) continue; const label = document.createElement("label"); const radio = document.createElement("input"); radio.type = "radio"; radio.name = "method"; radio.value = method.code; radio.disabled = !method.available; radio.addEventListener("change", () => void pick(method.code)); label.append(radio, ` ${method.name}`); methods.append(label); } form.addEventListener("submit", async (event) => { event.preventDefault(); if (!element) return; // One confirm for every element. If a card needs 3-D Secure, the browser // leaves for the bank here and comes back to the transaction's returnUrl. const result = await pesepay.confirmPayment(referenceNumber, { element, paymentMethodCode, }); if (result.error) { message.textContent = result.error.message; return; } // O'mari: the element now asks for the code from the SMS. Pay again once // it is typed. if (result.transaction.nextAction?.type === "enter_otp") return; // EcoCash or a scan code: wait while the customer finishes on their phone. const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(referenceNumber, { timeoutMs: 300_000 }) : result; message.textContent = paid.error ? paid.error.message : paid.transaction.outcome; }); } void start(); ``` * React PickerForm.tsx ```tsx import { useEffect, useState } from "react"; import type { MobileProvider, PaymentMethod, ScanProvider } from "@pesepay/js"; import { CardElement, Elements, MobileElement, ScanElement, useElements, usePesepay, } from "@pesepay/react"; // The element for each method this page takes. Mastercard and Zimswitch pay // in the hostedCard element, which starts from startCardCheckout(). type Choice = | { type: "card" } | { type: "mobile"; provider: MobileProvider } | { type: "scan"; provider: ScanProvider }; const ELEMENT_FOR: Record = { PZW204: { type: "card" }, // Visa PZW211: { type: "mobile", provider: "EcoCash" }, // USD PZW201: { type: "mobile", provider: "EcoCash" }, // ZiG PZW216: { type: "mobile", provider: "Omari" }, // USD PZW217: { type: "mobile", provider: "Omari" }, // ZiG PZW212: { type: "scan", provider: "InnBucks" }, // USD PZW210: { type: "scan", provider: "PayGo" }, // ZiG }; export function PickerForm({ referenceNumber }: { referenceNumber: string }) { return ( ); } function PayByPicker({ referenceNumber }: { referenceNumber: string }) { const pesepay = usePesepay(); const elements = useElements(); const [methods, setMethods] = useState([]); const [picked, setPicked] = useState(""); const [total, setTotal] = useState(""); const [label, setLabel] = useState("Pay"); const [message, setMessage] = useState(""); const choice = ELEMENT_FOR[picked]; useEffect(() => { if (!pesepay) return; void pesepay.listPaymentMethods(referenceNumber).then((listed) => { if (listed.error) setMessage(listed.error.message); else setMethods(listed.paymentMethods.filter((method) => ELEMENT_FOR[method.code])); }); }, [pesepay, referenceNumber]); async function pick(code: string): Promise { if (!pesepay) return; setPicked(code); setTotal(""); setLabel("Pay"); setMessage(""); // The total the customer pays with this method, fee included. const priced = await pesepay.selectPaymentMethod(referenceNumber, code); if (priced.error) setMessage(priced.error.message); else setTotal(`Total: ${priced.amount.total.toFixed(2)} ${priced.amount.currency}`); } async function pay(): Promise { const element = choice && elements?.getElement(choice.type); if (!pesepay || !element) return; // One confirm for every element. If a card needs 3-D Secure, the browser // leaves for the bank here and comes back to the transaction's returnUrl. const result = await pesepay.confirmPayment(referenceNumber, { element, paymentMethodCode: picked, }); if (result.error) { setMessage(result.error.message); return; } // O'mari: the element now asks for the code from the SMS. Pay again once // it is typed. if (result.transaction.nextAction?.type === "enter_otp") return; // EcoCash or a scan code: wait while the customer finishes on their phone. const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(referenceNumber, { timeoutMs: 300_000 }) : result; setMessage(paid.error ? paid.error.message : paid.transaction.outcome); } return (
{ event.preventDefault(); void pay(); }} >
Pay with {/* Unavailable methods are shown disabled: the amount is outside their limits. */} {methods.map((method) => ( ))}
{/* One element at a time: each unmounts when another method is picked. */} {choice?.type === "card" && ( setMessage(event.error?.message ?? "")} /> )} {choice?.type === "mobile" && ( { setMessage(event.error?.message ?? ""); // O'mari has sent its SMS code, and the field now asks for it. if (event.step === "otp") setLabel("Confirm code"); }} /> )} {choice?.type === "scan" && ( )}

{total}

{message}

); } ``` * Vue PickerPay.vue ```vue ``` * Angular picker-pay.component.ts ```ts import { Component, computed, input, signal, type OnInit } from "@angular/core"; import { loadPesepay, type ContactChangeEvent, type Elements as PesepayElements, type MobileProvider, type PaymentMethod, type Pesepay, type ScanProvider, } from "@pesepay/js"; import { CardElement, Elements, MobileElement, ScanElement } from "@pesepay/angular"; // The element for each method this page takes. Mastercard and Zimswitch pay // in the hostedCard element, which starts from startCardCheckout(). type Choice = | { type: "card" } | { type: "mobile"; provider: MobileProvider } | { type: "scan"; provider: ScanProvider }; const ELEMENT_FOR: Record = { PZW204: { type: "card" }, // Visa PZW211: { type: "mobile", provider: "EcoCash" }, // USD PZW201: { type: "mobile", provider: "EcoCash" }, // ZiG PZW216: { type: "mobile", provider: "Omari" }, // USD PZW217: { type: "mobile", provider: "Omari" }, // ZiG PZW212: { type: "scan", provider: "InnBucks" }, // USD PZW210: { type: "scan", provider: "PayGo" }, // ZiG }; @Component({ selector: "app-picker-pay", imports: [Elements, CardElement, MobileElement, ScanElement], template: `
Pay with @for (method of methods(); track method.code) { }
@for (choice of [choice()]; track picked()) { @if (choice?.type === "card") { } @else if (choice?.type === "mobile") { } @else if (choice?.type === "scan") { } }

{{ total() }}

{{ message() }}

`, }) export class PickerPayComponent implements OnInit { readonly referenceNumber = input.required(); readonly methods = signal([]); readonly picked = signal(""); readonly total = signal(""); readonly label = signal("Pay"); readonly message = signal(""); protected readonly choice = computed( () => ELEMENT_FOR[this.picked()], ); // Loaded once, and shared with . protected readonly loading = loadPesepay(); ngOnInit(): void { void this.loading.then(async (pesepay) => { if (!pesepay) return; // On the server, or the runtime could not load. const listed = await pesepay.listPaymentMethods(this.referenceNumber()); if (listed.error) this.message.set(listed.error.message); else this.methods.set( listed.paymentMethods.filter((method) => ELEMENT_FOR[method.code]), ); }); } async pick(pesepay: Pesepay | null, code: string): Promise { if (!pesepay) return; this.picked.set(code); this.total.set(""); this.label.set("Pay"); this.message.set(""); // The total the customer pays with this method, fee included. const priced = await pesepay.selectPaymentMethod(this.referenceNumber(), code); if (priced.error) this.message.set(priced.error.message); else this.total.set( `Total: ${priced.amount.total.toFixed(2)} ${priced.amount.currency}`, ); } onChange(event: ContactChangeEvent): void { this.message.set(event.error?.message ?? ""); // O'mari has sent its SMS code, and the field now asks for it. if (event.step === "otp") this.label.set("Confirm code"); } async pay( event: Event, pesepay: Pesepay | null, elements: PesepayElements | null, ): Promise { event.preventDefault(); const choice = this.choice(); const element = choice && elements?.getElement(choice.type); if (!pesepay || !element) return; // One confirm for every element. If a card needs 3-D Secure, the browser // leaves for the bank here and comes back to the transaction's returnUrl. const result = await pesepay.confirmPayment(this.referenceNumber(), { element, paymentMethodCode: this.picked(), }); if (result.error) { this.message.set(result.error.message); return; } // O'mari: the element now asks for the code from the SMS. Pay again once // it is typed. if (result.transaction.nextAction?.type === "enter_otp") return; // EcoCash or a scan code: wait while the customer finishes on their phone. const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(this.referenceNumber(), { timeoutMs: 300_000, }) : result; this.message.set(paid.error ? paid.error.message : paid.transaction.outcome); } } ``` Pass the picked code as `paymentMethodCode`, so the payment uses the method you priced. An element typed as a union, such as `CardElement | MobileElement | ScanElement`, takes only the options every member can use: `customer`, `metadata`, `paymentMethodCode` and `signal`. ## What each method does next [Section titled “What each method does next”](#what-each-method-does-next) `confirmPayment()` returns what the element’s own confirm returns: | Method | `confirmPayment()` returns | Then | | ----------------- | -------------------------------------------------------------- | ------------------------------------------------- | | Visa | the outcome, or the browser leaves for the bank’s 3-D Secure | `handleRedirectResult()` on your return page | | EcoCash | `processing`; the element shows “Check your phone” | `waitForTransaction()` while they approve | | O’mari | `nextAction.type === "enter_otp"`; the field asks for the code | `confirmPayment()` again with the same element | | InnBucks or PayGo | `processing`, with `nextAction.type === "scan_code"` | `waitForTransaction()` with a five-minute timeout | ## What’s next [Section titled “What’s next”](#whats-next) * [Cards and 3-D Secure](/embedded-checkout/guides/cards/), [Mobile money approval](/embedded-checkout/guides/mobile-money/) and [Scan to pay](/embedded-checkout/guides/scan-to-pay/): each method in full, with the card return page * [Errors and fallbacks](/embedded-checkout/guides/errors/): what to show for each result # Mobile money approval > How EcoCash and O'mari payments are approved in Embedded checkout, and the mobile element for your own method picker. The customer types their phone number and approves the payment from their phone. The two methods approve it in different ways: | Method | How the customer approves it | USD | ZiG | | ------- | ----------------------------------------------------------- | -------- | -------- | | EcoCash | Enters their PIN in a prompt on their phone | `PZW211` | `PZW201` | | O’mari | Types the code from an SMS into the same field on your page | `PZW216` | `PZW217` | The method follows the transaction’s currency. ## In the checkout element [Section titled “In the checkout element”](#in-the-checkout-element) There is nothing to code. * **EcoCash.** After the customer presses Pay, the element shows “Check your phone” with a countdown and waits for their answer. The customer enters their PIN on their phone, never on your page. * **O’mari.** The first press sends an SMS code, and the field asks for it. The customer types the code and presses Pay again. Either way the element then shows the result and sends `finished`. An `unknown` outcome means no answer came in time: the customer may still approve, so don’t let them pay again (see [Accept a payment](/embedded-checkout/guides/accept-a-payment/#answer-every-outcome)). ## With your own method picker [Section titled “With your own method picker”](#with-your-own-method-picker) Use the `mobile` element when you build the method picker yourself. Your code differs by method: * **EcoCash: confirm once.** `confirmMobilePayment()` returns at `processing`, and the element waits for the customer’s answer itself. Each step arrives as a `status` event: `awaiting_approval`, then `succeeded`, `failed`, `reversed` or `unknown`. There is no resend: while a prompt is live, EcoCash refuses another. * **O’mari: confirm twice.** The first confirm sends the SMS and returns `nextAction.type === "enter_otp"`, and the element’s `change` events report `step: "otp"`, your cue to relabel the button. Confirm again with the same reference and element, then wait with `waitForTransaction()`. - JavaScript checkout.html ```html

``` src/mobile-pay.ts ```ts import { loadPesepay, type MobileProvider } from "@pesepay/js"; const form = document.querySelector("#mobile-form")!; const button = form.querySelector("button")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = form.dataset.referenceNumber!; // "EcoCash" or "Omari": the method the customer picked. const provider = form.dataset.provider as MobileProvider; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const mobile = pesepay.elements().create("mobile", { provider }); mobile.on("change", (event) => { message.textContent = event.error?.message ?? ""; // O'mari has sent its SMS code, and the field now asks for it. if (event.step === "otp") button.textContent = "Confirm code"; }); // EcoCash: the element shows "Check your phone" and waits for the // customer's answer itself, reporting it here. mobile.on("status", ({ status }) => { if (status !== "awaiting_approval") message.textContent = status; }); mobile.mount("#phone"); form.addEventListener("submit", async (event) => { event.preventDefault(); const result = await pesepay.confirmMobilePayment(referenceNumber, { element: mobile, }); if (result.error) { message.textContent = result.error.message; return; } // O'mari, first submit: the customer types the code and submits again. if (result.transaction.nextAction?.type === "enter_otp") return; // O'mari, second submit: wait for the result. EcoCash reports through // the status event instead. if (provider === "Omari") { const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(referenceNumber) : result; message.textContent = paid.error ? paid.error.message : paid.transaction.outcome; } }); } void start(); ``` - React MobileForm.tsx ```tsx import { useState } from "react"; import type { MobileProvider } from "@pesepay/js"; import { Elements, MobileElement, useElements, usePesepay } from "@pesepay/react"; interface MobileFormProps { referenceNumber: string; /** "EcoCash" or "Omari": the method the customer picked. */ provider: MobileProvider; } export function MobileForm(props: MobileFormProps) { return ( ); } function PayByMobile({ referenceNumber, provider }: MobileFormProps) { const pesepay = usePesepay(); const elements = useElements(); const [label, setLabel] = useState("Pay"); const [message, setMessage] = useState(""); async function pay(): Promise { const mobile = elements?.getElement("mobile"); if (!pesepay || !mobile) return; const result = await pesepay.confirmMobilePayment(referenceNumber, { element: mobile, }); if (result.error) { setMessage(result.error.message); return; } // O'mari, first submit: the customer types the code and submits again. if (result.transaction.nextAction?.type === "enter_otp") return; // O'mari, second submit: wait for the result. EcoCash reports through // onStatus instead. if (provider === "Omari") { const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(referenceNumber) : result; setMessage(paid.error ? paid.error.message : paid.transaction.outcome); } } return (
{ event.preventDefault(); void pay(); }} > { setMessage(event.error?.message ?? ""); // O'mari has sent its SMS code, and the field now asks for it. if (event.step === "otp") setLabel("Confirm code"); }} // EcoCash: the element shows "Check your phone" and waits for the // customer's answer itself, reporting it here. onStatus={({ status }) => { if (status !== "awaiting_approval") setMessage(status); }} />

{message}

); } ``` - Vue MobilePay.vue ```vue ``` - Angular mobile-pay.component.ts ```ts import { Component, computed, input, signal } from "@angular/core"; import type { ContactChangeEvent, ElementStatusEvent, Elements as PesepayElements, MobileProvider, Pesepay, } from "@pesepay/js"; import { Elements, MobileElement } from "@pesepay/angular"; @Component({ selector: "app-mobile-pay", imports: [Elements, MobileElement], template: `

{{ message() }}

`, }) export class MobilePayComponent { readonly referenceNumber = input.required(); /** "EcoCash" or "Omari": the method the customer picked. */ readonly provider = input.required(); protected readonly options = computed(() => ({ provider: this.provider() })); readonly label = signal("Pay"); readonly message = signal(""); onChange(event: ContactChangeEvent): void { this.message.set(event.error?.message ?? ""); // O'mari has sent its SMS code, and the field now asks for it. if (event.step === "otp") this.label.set("Confirm code"); } // EcoCash: the element shows "Check your phone" and waits for the // customer's answer itself, reporting it here. onStatus({ status }: ElementStatusEvent): void { if (status !== "awaiting_approval") this.message.set(status); } async pay( event: Event, pesepay: Pesepay | null, elements: PesepayElements | null, ): Promise { event.preventDefault(); const mobile = elements?.getElement("mobile"); if (!pesepay || !mobile) return; const result = await pesepay.confirmMobilePayment(this.referenceNumber(), { element: mobile, }); if (result.error) { this.message.set(result.error.message); return; } // O'mari, first submit: the customer types the code and submits again. if (result.transaction.nextAction?.type === "enter_otp") return; // O'mari, second submit: wait for the result. EcoCash reports through // (status) instead. if (this.provider() === "Omari") { const paid = result.transaction.outcome === "processing" ? await pesepay.waitForTransaction(this.referenceNumber()) : result; this.message.set(paid.error ? paid.error.message : paid.transaction.outcome); } } } ``` A transaction gets one O’mari SMS. If the page reloads after it went out, create the element with `resumeOtpFor: referenceNumber` to start it on the code step, but only when you know no code has been submitted. To pay again after a failure, with either method, create a new transaction and a new element. ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): every outcome, and fulfilling from your server # Scan to pay > How InnBucks and PayGo payments work in Embedded checkout, where the customer scans a code in their app, and the scan element for your own method picker. The customer pays in their InnBucks or PayGo app. Your page shows a short code and a QR code; the customer scans the QR or types the code in the app, and approves the payment there. | Method | Currency | Code | | -------- | -------- | -------- | | InnBucks | USD | `PZW212` | | PayGo | ZiG | `PZW210` | ## In the checkout element [Section titled “In the checkout element”](#in-the-checkout-element) There is nothing to code. After the customer presses Pay, the element shows the code and the QR code, and waits while they pay in their app. That can take a few minutes. The element then shows the result and sends `finished`. ## With your own method picker [Section titled “With your own method picker”](#with-your-own-method-picker) Use the `scan` element when you build the method picker yourself. `confirmScanPayment()` returns a `scan_code` next action, and the element shows the code and the QR. Nothing is paid until the customer pays in their app, so follow it with `waitForTransaction()` and a long timeout, such as five minutes. * JavaScript checkout.html ```html

``` src/scan-pay.ts ```ts import { loadPesepay, type ScanProvider } from "@pesepay/js"; const form = document.querySelector("#scan-form")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = form.dataset.referenceNumber!; // "InnBucks" for USD or "PayGo" for ZiG. const provider = form.dataset.provider as ScanProvider; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const scan = pesepay.elements().create("scan", { provider }); scan.mount("#scan"); form.addEventListener("submit", async (event) => { event.preventDefault(); // The element now shows a short code and a QR code for the customer's app. const sent = await pesepay.confirmScanPayment(referenceNumber, { element: scan }); if (sent.error) { message.textContent = sent.error.message; return; } if (sent.transaction.nextAction?.type !== "scan_code") { message.textContent = sent.transaction.outcome; return; } // Nothing is paid until the customer pays in their app, which can take // a few minutes. const paid = await pesepay.waitForTransaction(referenceNumber, { timeoutMs: 300_000, }); message.textContent = paid.error ? paid.error.message : paid.transaction.outcome; }); } void start(); ``` * React ScanForm.tsx ```tsx import { useState } from "react"; import type { ScanProvider } from "@pesepay/js"; import { Elements, ScanElement, useElements, usePesepay } from "@pesepay/react"; interface ScanFormProps { referenceNumber: string; /** "InnBucks" for USD or "PayGo" for ZiG. */ provider: ScanProvider; } export function ScanForm(props: ScanFormProps) { return ( ); } function PayByScan({ referenceNumber, provider }: ScanFormProps) { const pesepay = usePesepay(); const elements = useElements(); const [message, setMessage] = useState(""); async function pay(): Promise { const scan = elements?.getElement("scan"); if (!pesepay || !scan) return; // The element now shows a short code and a QR code for the customer's app. const sent = await pesepay.confirmScanPayment(referenceNumber, { element: scan }); if (sent.error) { setMessage(sent.error.message); return; } if (sent.transaction.nextAction?.type !== "scan_code") { setMessage(sent.transaction.outcome); return; } // Nothing is paid until the customer pays in their app, which can take // a few minutes. const paid = await pesepay.waitForTransaction(referenceNumber, { timeoutMs: 300_000, }); setMessage(paid.error ? paid.error.message : paid.transaction.outcome); } return (
{ event.preventDefault(); void pay(); }} >

{message}

); } ``` * Vue ScanPay.vue ```vue ``` * Angular scan-pay.component.ts ```ts import { Component, computed, input, signal } from "@angular/core"; import type { Elements as PesepayElements, Pesepay, ScanProvider } from "@pesepay/js"; import { Elements, ScanElement } from "@pesepay/angular"; @Component({ selector: "app-scan-pay", imports: [Elements, ScanElement], template: `

{{ message() }}

`, }) export class ScanPayComponent { readonly referenceNumber = input.required(); /** "InnBucks" for USD or "PayGo" for ZiG. */ readonly provider = input.required(); protected readonly options = computed(() => ({ provider: this.provider() })); readonly message = signal(""); async pay( event: Event, pesepay: Pesepay | null, elements: PesepayElements | null, ): Promise { event.preventDefault(); const scan = elements?.getElement("scan"); if (!pesepay || !scan) return; // The element now shows a short code and a QR code for the customer's app. const sent = await pesepay.confirmScanPayment(this.referenceNumber(), { element: scan, }); if (sent.error) { this.message.set(sent.error.message); return; } if (sent.transaction.nextAction?.type !== "scan_code") { this.message.set(sent.transaction.outcome); return; } // Nothing is paid until the customer pays in their app, which can take // a few minutes. const paid = await pesepay.waitForTransaction(this.referenceNumber(), { timeoutMs: 300_000, }); this.message.set(paid.error ? paid.error.message : paid.transaction.outcome); } } ``` A `timeout` error from `waitForTransaction()` means the SDK stopped looking, not that the payment failed: the customer may still pay. Your result callback gets the outcome either way. The QR image is a `data:` URL for InnBucks and an image on PayGo’s host for PayGo. If your page sends a Content-Security-Policy, allow both in `img-src`; see [Accept a payment](/embedded-checkout/guides/accept-a-payment/#content-security-policy). ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): every outcome, and fulfilling from your server # Server-side rendering > Use Embedded checkout in server-rendered apps such as Next.js, Nuxt and Angular SSR. Nothing loads on the server, and nothing throws. The elements run in the browser only, and every package is safe to import and render on the server. Nothing loads there, and nothing throws. * **`loadPesepay()`** resolves `null` when there is no DOM, whatever options you pass. Guard with `if (!pesepay) return;` rather than checking `typeof window`. An invalid option is reported in the browser, never as an error in a server render. * **React.** `` loads nothing on the server and renders its children; each element component renders an empty `
`. The components are marked `"use client"`, so the Next.js App Router can import them from a server component. * **Vue.** `` loads nothing before it is mounted, and each element component renders an empty `
` on the server, in Nuxt too. * **Angular.** `` loads nothing before the first render in the browser, and each element component renders as an empty host element. The elements load once the page hydrates. A container you give the element can hold a loading placeholder: `mount()` appends rather than clearing. ## Next.js [Section titled “Next.js”](#nextjs) With the App Router, the page stays a server component and the checkout is a client component: its event handlers are functions, which a server component can’t pass down. This example is built and prerendered with `next build` against the published packages. app/pay/page.tsx ```tsx import { Checkout } from "./checkout"; // A server component. It renders on the server; the checkout inside it loads // in the browser once the page hydrates. export default function PayPage() { // Your server created the transaction for this order and has its reference // number. const referenceNumber = "REF-1"; return (

Checkout

); } ``` app/pay/checkout.tsx ```tsx "use client"; import { useRouter } from "next/navigation"; import { CheckoutElement, Elements } from "@pesepay/react"; // A client component, because its event handlers run in the browser. On the // server loads nothing and the element renders an empty
. export function Checkout({ referenceNumber }: { referenceNumber: string }) { const router = useRouter(); return ( { if (event.outcome === "succeeded") router.push("/order-complete"); }} // The methods could not load: Pesepay's hosted checkout takes the payment. onLoadError={(event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }} /> ); } ``` ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): one transaction per order, and fulfilling from your server # Appearance and theming > Match Embedded checkout to your site with a theme of colours, fonts, spacing and labels, and load a web font into the card fields. Every element takes a theme: colours, fonts, spacing, labels and states, from a fixed list of tokens. Set it once for a group of elements, and every element in the group uses it. The elements are isolated from your page’s CSS. The in-page elements render inside a shadow root and the card fields inside a frame on a Pesepay origin, so a rule in your stylesheet doesn’t reach them, and theirs don’t reach your page. The theme is how you style them. ## A theme [Section titled “A theme”](#a-theme) appearance.ts ```ts import type { ElementsOptions } from "@pesepay/js"; // One look for every element in the group. Only these token names are // accepted: the theme is a fixed vocabulary, not a stylesheet. export const appearance: ElementsOptions = { // The card fields are in their own frame, so they need the font passed here. fonts: [{ cssSrc: "https://fonts.googleapis.com/css2?family=Inter:wght@400;600" }], theme: { preset: "flat", labels: "floating", colors: { primary: "#0f766e", borderFocus: "#0f766e", error: "#b91c1c" }, fonts: { family: "Inter, system-ui, sans-serif", size: "15px" }, spacing: { borderRadius: "8px", padding: "12px", gap: "16px" }, }, }; ``` * `preset` starts from a ready-made look: `"night"` (dark fields) or `"flat"` (no visible border, on a light grey fill). Any token you set overrides the preset’s value. A preset sets colours, border radius and the focus ring only. * `labels` is `"above"`, `"floating"` (inside the field, moving up once it has focus or a value) or `"hidden"`. A hidden label is still read by screen readers. * `colors.primary` colours the picked method and the checkout element’s Pay button; `colors.primaryText` is the button’s text. Every token, with its default, is on the [PesepayTheme](/embedded-checkout/reference/js/pesepay-theme/) reference page. ## Pass it to the elements [Section titled “Pass it to the elements”](#pass-it-to-the-elements) Pass the theme and fonts where the group is created: `elements()` in JavaScript, the `options` of `` in the components. A change to them is applied to every element in the group. The code is built and type-checked against the published packages. * JavaScript src/themed-checkout.ts ```ts import { loadPesepay } from "@pesepay/js"; import { appearance } from "./appearance.js"; const container = document.querySelector("#checkout")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = container.dataset.referenceNumber!; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } // Every element created from this group takes the theme and the font. const elements = pesepay.elements(appearance); const checkout = elements.create("checkout", { referenceNumber }); checkout.on("finished", (event) => { if (event.outcome === "succeeded") window.location.assign("/order-complete"); }); checkout.on("loaderror", (event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }); checkout.mount(container); } void start(); ``` * React ThemedCheckout.tsx ```tsx import type { CheckoutOutcome } from "@pesepay/js"; import { CheckoutElement, Elements } from "@pesepay/react"; import { appearance } from "./appearance.js"; export function ThemedCheckout({ referenceNumber, onFinished, }: { referenceNumber: string; onFinished: (outcome: CheckoutOutcome) => void; }) { return ( // Every element inside takes the theme and the font. onFinished(event.outcome)} onLoadError={(event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }} /> ); } ``` * Vue ThemedCheckout.vue ```vue ``` * Angular themed-checkout.component.ts ```ts import { Component, computed, input, output } from "@angular/core"; import type { CheckoutOutcome } from "@pesepay/js"; import { CheckoutElement, Elements } from "@pesepay/angular"; import { appearance } from "./appearance"; @Component({ selector: "app-themed-checkout", imports: [Elements, CheckoutElement], template: ` `, }) export class ThemedCheckoutComponent { readonly referenceNumber = input.required(); readonly finished = output(); protected readonly appearance = appearance; protected readonly options = computed(() => ({ referenceNumber: this.referenceNumber(), })); leave(fallbackUrl: string | undefined): void { if (fallbackUrl) window.location.assign(fallbackUrl); } } ``` A theme can also be set on the instance, with `loadPesepay({ theme })`, and on one element, with its `theme` option. The three are merged in that order, section by section, so an element that overrides `colors` keeps the group’s `fonts`. ## Web fonts [Section titled “Web fonts”](#web-fonts) The card fields are in their own frame, so a font your page loads does not reach them. Pass it in `fonts` and name it in `theme.fonts.family`, as above. * `cssSrc` must be a Google Fonts `css2` URL. Any other URL throws, and so do more than 8 fonts. A stylesheet you write yourself is not accepted, because a font can be built so that each digit typed fetches its own file. * Your page’s Content-Security-Policy needs nothing more: the fonts load inside the frame. * The mobile and scan elements render in your page, so they use the fonts your page already loads. The Mastercard and Zimswitch form is the card provider’s own; it uses `theme.fonts.family` only if the customer has the font installed. ## What a theme can’t do [Section titled “What a theme can’t do”](#what-a-theme-cant-do) Only known token names are accepted, and a value is dropped (the default is used) if it is longer than 200 characters or contains `;`, `{`, `}`, `<`, `>`, `\` or `/*`. Arbitrary CSS is left out on purpose: in card fields it would let a stylesheet read what the customer types, for example through `background-image: url(...)` rules. ## What’s next [Section titled “What’s next”](#whats-next) * [Your own method picker](/embedded-checkout/guides/method-picker/): one element per method, all sharing one theme # @pesepay/js > The Pesepay Elements loader for any page or framework: loading the runtime, creating elements, and handling results and errors. ![](/_astro/javascript.BxUIoaTT_Z1z4nbv.svg) `@pesepay/js` [npm](https://www.npmjs.com/package/@pesepay/js) The loader for Pesepay Elements, with TypeScript types. The React, Vue and Angular packages build on it. `npm install @pesepay/js` `@pesepay/js` is a small loader. It adds the Elements runtime from `js.pesepay.com` to your page and returns a typed handle to it, so a fix reaches your checkout in one Pesepay deploy, without an `npm update`. It has no dependencies. You can skip npm and load the same runtime with a script tag: ```html ``` The script sets `window.Pesepay`, and `Pesepay.create()` returns the same instance `loadPesepay()` resolves. Which path to load, and how to pin a version, is in [CDN, pinning and integrity](/embedded-checkout/guides/cdn-and-pinning/). ## Take a payment [Section titled “Take a payment”](#take-a-payment) Your server creates the transaction and puts its reference number on the page. The checkout element pays it with its own button: src/pay.ts ```ts import { loadPesepay } from "@pesepay/js"; const container = document.querySelector("#checkout")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = container.dataset.referenceNumber!; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const checkout = pesepay.elements().create("checkout", { referenceNumber }); // The payment has ended and the element shows the result. Fulfil the order // on your server, which Pesepay notifies too; this only moves the customer on. checkout.on("finished", (event) => { if (event.outcome === "succeeded") window.location.assign("/order-complete"); }); // The methods could not load: Pesepay's hosted checkout takes the payment. checkout.on("loaderror", (event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }); checkout.mount(container); } void start(); ``` The [Quickstart](/embedded-checkout/quickstart/) builds the whole page, server included. ## Load Pesepay [Section titled “Load Pesepay”](#load-pesepay) `loadPesepay()` resolves the Pesepay instance, or `null` when there is no browser or the runtime can’t load, such as during server-side rendering or behind a content blocker. It is safe to call in a component that also renders on the server. ```ts import { loadPesepay } from '@pesepay/js'; const pesepay = await loadPesepay(); if (!pesepay) return showUnavailable(); ``` Call it once per page. Its options, such as `apiBaseUrl`, are in the [reference](/embedded-checkout/reference/js/load-pesepay/). ## Create and mount elements [Section titled “Create and mount elements”](#create-and-mount-elements) `pesepay.elements()` creates an elements group. Its options (`theme`, `fonts`, `locale`) apply to every element in it; see [Appearance and theming](/embedded-checkout/guides/theming/). `elements.create(type, options)` creates an element but does not mount it. Attach your listeners first, then call `mount()` with a selector or an element. | Type | What it is | Guide | | ------------ | --------------------------------------------------------------- | ---------------------------------------------------------------- | | `checkout` | Every method, the total and fee, and a Pay button | [Quickstart](/embedded-checkout/quickstart/) | | `payment` | Every method, without a button: you pay with `confirmPayment()` | [Custom payment flow](/embedded-checkout/custom-payment-flow/) | | `card` | Visa card fields | [Cards and 3-D Secure](/embedded-checkout/guides/cards/) | | `hostedCard` | Mastercard and Zimswitch, in the card provider’s form | [Cards and 3-D Secure](/embedded-checkout/guides/cards/) | | `mobile` | EcoCash and O’mari | [Mobile money approval](/embedded-checkout/guides/mobile-money/) | | `scan` | InnBucks and PayGo codes | [Scan to pay](/embedded-checkout/guides/scan-to-pay/) | If the methods can’t be listed or a method’s fields fail to load, the `loaderror` event carries `fallbackUrl`: Pesepay’s Hosted checkout page for the same transaction. ## Results and errors [Section titled “Results and errors”](#results-and-errors) The checkout element reports once, with the `finished` event. Everywhere else, every confirm resolves `{ transaction }` or `{ error }`. Branch on `transaction.outcome`, not on `status`: ```ts if (result.error?.code === 'outcome_unknown') return showChecking(); if (result.error) return showError(result.error.message); switch (result.transaction.outcome) { case 'succeeded': return showPaid(); // then confirm on your server case 'failed': return showError(result.transaction.message); case 'processing': case 'unknown': return showChecking(); case 'reversed': return showRefunded(); } ``` `unknown` and `outcome_unknown` both mean the customer may have paid. Check the transaction before letting them pay again. Anything a customer, card or network causes is **returned** as `{ error }`, with a `code` from a closed list (`PESEPAY_ERROR_CODES`). Only programmer errors **throw**, such as a selector that matches nothing, so a `try`/`catch` around a confirm catches your bugs, not declines. Every code is in [Errors and fallbacks](/embedded-checkout/guides/errors/). ## Cancel a payment [Section titled “Cancel a payment”](#cancel-a-payment) `pesepay.cancelTransaction(referenceNumber)` cancels a payment nothing can have been taken for: one not yet sent, or an O’mari payment waiting for its code. Anything a provider may still complete returns `cancel_not_allowed`, including an EcoCash prompt and Mastercard or Zimswitch once selected. ## Confirm on your server [Section titled “Confirm on your server”](#confirm-on-your-server) A result in the browser is for your page. Don’t fulfil an order on it, because anyone who controls the browser can forge it. Pesepay posts the outcome to your server’s `resultUrl`; check the transaction from your server and fulfil only on `SUCCESS`. See [The result callback](/webhooks/result-callback/) and [Accept a payment](/embedded-checkout/guides/accept-a-payment/). ## TypeScript and modules [Section titled “TypeScript and modules”](#typescript-and-modules) The types ship with the package, and your editor shows the same documentation inline. The package is ESM only: from CommonJS, use a dynamic `import()`. ## What’s next [Section titled “What’s next”](#whats-next) * [React](/embedded-checkout/react/), [Vue](/embedded-checkout/vue/) and [Angular](/embedded-checkout/angular/): the same elements as components * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): taking Embedded checkout to production * [Elements SDK reference](/embedded-checkout/reference/js/): every option, event and error code # Migrate from the Direct API > Move a Direct API (formerly Seamless) integration to Embedded checkout, with what stays, what changes and where each request field goes. This page is for a merchant who already runs the [Direct API](/payments/direct-api/) (formerly Seamless) on a web checkout and wants more payment methods. It shows what changes, side by side, rather than starting from scratch. ## Why move [Section titled “Why move”](#why-move) * **Cards with 3-D Secure.** Visa, Mastercard and Zimswitch work in the element. The Direct API takes no cards. * **Every method in one component.** The checkout element lists each method the transaction can be paid with, priced per method. * **No card data on your servers.** Card fields run in a frame on a Pesepay origin, so your page cannot read them. * **The waiting is handled.** The element asks for the O’mari code, waits for the EcoCash approval or the scanned code, and shows the result. ## What stays [Section titled “What stays”](#what-stays) * Your integration key and encryption key. * Your result callback handler at `resultUrl`. * Your server-side status check before you fulfil an order. A payment is paid only when its [`transactionStatus`](/resources/transaction-statuses/) is `SUCCESS`. ## What changes [Section titled “What changes”](#what-changes) The single encrypted charge call splits in two. Your server **creates** the payment, and the customer **pays** in the element on your page. Your own phone-number form and waiting screen go away. ### On your server [Section titled “On your server”](#on-your-server) * Node.js Before: Direct API ```js const payment = pesepay.createPayment('USD', 'PZW211', email, phone, name); const requiredFields = { customerPhoneNumber: phone }; const response = await pesepay.makeSeamlessPayment(payment, 'Order #1042', 10.0, requiredFields); // then poll response.pollUrl while the customer approves ``` After: Embedded checkout ```js pesepay.resultUrl = 'https://example.com/payments/result'; pesepay.returnUrl = 'https://example.com/checkout'; const transaction = pesepay.createTransaction(10.0, 'USD', 'Order #1042'); const response = await pesepay.initiateTransaction(transaction); const referenceNumber = response.referenceNumber; // send this to your page ``` * Python Before: Direct API ```python payment = pesepay.create_payment("USD", "PZW211", email, phone, name) required_fields = {"customerPhoneNumber": phone} response = pesepay.make_seamless_payment(payment, "Order #1042", 10.0, required_fields) # then poll response.poll_url while the customer approves ``` After: Embedded checkout ```python pesepay.result_url = "https://example.com/payments/result" pesepay.return_url = "https://example.com/checkout" transaction = pesepay.create_transaction(10.0, "USD", "Order #1042") response = pesepay.initiate_transaction(transaction) reference_number = response.reference_number # send this to your page ``` * PHP Before: Direct API ```php $payment = $pesepay->createPayment('USD', 'PZW211', $email, $phone, $name); $requiredFields = ['customerPhoneNumber' => $phone]; $response = $pesepay->makeSeamlessPayment($payment, 'Order #1042', 10.0, $requiredFields); // then poll $response->pollUrl() while the customer approves ``` After: Embedded checkout ```php $pesepay->resultUrl = 'https://example.com/payments/result'; $pesepay->returnUrl = 'https://example.com/checkout'; $transaction = $pesepay->createTransaction(10.0, 'USD', 'Order #1042'); $response = $pesepay->initiateTransaction($transaction); $referenceNumber = $response->referenceNumber(); // send this to your page ``` * Java Before: Direct API ```java Payment payment = pesepay.createPayment("USD", "PZW211", email); Map requiredFields = new HashMap<>(); requiredFields.put("customerPhoneNumber", phone); Response response = pesepay.makeSeamlessPayment(payment, "Order #1042", 10.0, requiredFields); // then poll response.getPollUrl() while the customer approves ``` After: Embedded checkout ```java pesepay.setResultUrl("https://example.com/payments/result"); pesepay.setReturnUrl("https://example.com/checkout"); Transaction transaction = pesepay.createTransaction(10.0, "USD", "Order #1042"); Response response = pesepay.initiateTransaction(transaction); String referenceNumber = response.getReferenceNumber(); // send this to your page ``` The new call is the one Hosted checkout uses ([Initiate Transaction](/api/initiate-transaction/)). You keep the `referenceNumber` instead of redirecting to `redirectUrl`, and `returnUrl` points at your checkout page, where a card payment comes back after 3-D Secure. ### On your page [Section titled “On your page”](#on-your-page) Your method picker, phone-number field and waiting screen are replaced by the checkout element: src/pay.ts ```ts import { loadPesepay } from "@pesepay/js"; const container = document.querySelector("#checkout")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = container.dataset.referenceNumber!; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const checkout = pesepay.elements().create("checkout", { referenceNumber }); // The payment has ended and the element shows the result. Fulfil the order // on your server, which Pesepay notifies too; this only moves the customer on. checkout.on("finished", (event) => { if (event.outcome === "succeeded") window.location.assign("/order-complete"); }); // The methods could not load: Pesepay's hosted checkout takes the payment. checkout.on("loaderror", (event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }); checkout.mount(container); } void start(); ``` The [quickstart](/embedded-checkout/quickstart/) has the same code for a script tag, React, Vue and Angular. Want your own Pay button? See [Custom payment flow](/embedded-checkout/custom-payment-flow/). ## Where each field goes [Section titled “Where each field goes”](#where-each-field-goes) | Direct API (`make-payment`) | Embedded checkout | | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `amountDetails`, `reasonForPayment`, `resultUrl`, `merchantReference`, `paymentMetadata` | The server’s create call, unchanged | | `returnUrl` | The server’s create call, where it is required. Set it to your checkout page | | `paymentMethodCode` | The element: the customer picks the method. On the create call it only preselects one | | `paymentMethodRequiredFields` (phone number, O’mari code) | The element asks for them | | `customer` | Not sent by the checkout element. With your own Pay button, pass it to `confirmPayment()` as `customer` | | The encrypted `make-payment` call | Gone: the customer confirms in the element | | Polling `pollUrl` | The element waits for the outcome. Your server still confirms through the result callback and a status check | ## Running both [Section titled “Running both”](#running-both) You don’t have to switch every checkout at once. Offer Embedded checkout to a share of your customers and keep the Direct API for the rest. Both paths report to the same result URL, so your callback handler and status checks work unchanged for each. # Quickstart: Embedded checkout > Take your first payment on your own page with Pesepay Elements, in plain HTML, JavaScript, React, Vue or Angular. This page takes a real payment: by the end of it you will have paid a small amount, with your own card or EcoCash number and production keys, on your own checkout page, and your server will know about it. Pick your framework once in any tab and every tab on the page follows. ### Prerequisites [Section titled “Prerequisites”](#prerequisites) * A [Pesepay account](/getting-started/onboarding/) with a production **integration key** and **encryption key** * A server that can create a payment, as in the [Hosted checkout quickstart](/getting-started/quickstart/) * A web page you can edit, served over `http://localhost` or HTTPS 1. ### Create the payment on your server [Section titled “Create the payment on your server”](#create-the-payment-on-your-server) Create and initiate a transaction exactly as for Hosted checkout, but keep the `referenceNumber` instead of redirecting to `redirectUrl`. Set `returnUrl` to your checkout page itself: a card that goes to its bank comes back there (see [Coming back from the bank](#coming-back-from-the-bank)). * Node.js ```js pesepay.resultUrl = 'https://example.com/payments/result'; pesepay.returnUrl = 'https://example.com/checkout'; const transaction = pesepay.createTransaction(10.0, 'USD', 'Order #1042'); const response = await pesepay.initiateTransaction(transaction); const referenceNumber = response.referenceNumber; // send this to your page ``` * Python ```python pesepay.result_url = "https://example.com/payments/result" pesepay.return_url = "https://example.com/checkout" transaction = pesepay.create_transaction(10.0, "USD", "Order #1042") response = pesepay.initiate_transaction(transaction) reference_number = response.reference_number # send this to your page ``` * PHP ```php $pesepay->resultUrl = 'https://example.com/payments/result'; $pesepay->returnUrl = 'https://example.com/checkout'; $transaction = $pesepay->createTransaction(10.0, 'USD', 'Order #1042'); $response = $pesepay->initiateTransaction($transaction); $referenceNumber = $response->referenceNumber(); // send this to your page ``` * Java ```java pesepay.setResultUrl("https://example.com/payments/result"); pesepay.setReturnUrl("https://example.com/checkout"); Transaction transaction = pesepay.createTransaction(10.0, "USD", "Order #1042"); Response response = pesepay.initiateTransaction(transaction); String referenceNumber = response.getReferenceNumber(); // send this to your page ``` Pass the reference number to your checkout page however your app renders it: in the HTML, as a prop, or from an API call. 2. ### Install Elements [Section titled “Install Elements”](#install-elements) * Script tag Nothing to install. The page in the next step loads `https://js.pesepay.com/v1/pesepay.js`. * JavaScript ```bash npm i @pesepay/js ``` * React ```bash npm i @pesepay/js @pesepay/react ``` * Vue ```bash npm i @pesepay/js @pesepay/vue ``` * Angular ```bash npm i @pesepay/js @pesepay/angular ``` 3. ### Add the checkout element [Section titled “Add the checkout element”](#add-the-checkout-element) The checkout element lists every method the transaction can be paid with, shows the total and fee for the one the customer picks, shows that method’s fields, and pays with its own button. Your code listens for one event, `finished`. * Script tag Your server writes the reference number into the page: checkout.html ```html Checkout

``` Keep the script in its own file, so a `Content-Security-Policy` without `'unsafe-inline'` allows it: checkout.js ```js const container = document.getElementById("checkout"); const message = document.getElementById("payment-message"); const referenceNumber = container.dataset.referenceNumber; // Unset if the script tag was blocked, for example by a content blocker. const pesepay = window.Pesepay?.create({}); if (pesepay) { const checkout = pesepay.elements().create("checkout", { referenceNumber }); // The payment has ended and the element shows the result. Fulfil the order // on your server, which Pesepay notifies too; this only moves the customer on. checkout.on("finished", (event) => { if (event.outcome === "succeeded") window.location.assign("/order-complete"); }); // The methods could not load: Pesepay's hosted checkout takes the payment. checkout.on("loaderror", (event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }); checkout.mount(container); } else { message.textContent = "Payments are unavailable. Please try again later."; } ``` Don’t add an `integrity` hash to `/v1/pesepay.js`: it is patched in place so security fixes reach you without a redeploy, and a patched file no longer matches the hash. * JavaScript Your server writes the reference number into the page: checkout.html ```html

``` src/pay.ts ```ts import { loadPesepay } from "@pesepay/js"; const container = document.querySelector("#checkout")!; const message = document.querySelector("#payment-message")!; // Your server created the transaction and wrote its reference number here. const referenceNumber = container.dataset.referenceNumber!; async function start(): Promise { // Null if the runtime could not load, for example behind a content blocker. const pesepay = await loadPesepay(); if (!pesepay) { message.textContent = "Payments are unavailable. Please try again later."; return; } const checkout = pesepay.elements().create("checkout", { referenceNumber }); // The payment has ended and the element shows the result. Fulfil the order // on your server, which Pesepay notifies too; this only moves the customer on. checkout.on("finished", (event) => { if (event.outcome === "succeeded") window.location.assign("/order-complete"); }); // The methods could not load: Pesepay's hosted checkout takes the payment. checkout.on("loaderror", (event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }); checkout.mount(container); } void start(); ``` `loadPesepay()` resolves `null` on the server, so it is safe to import during server-side rendering. * React CheckoutForm.tsx ```tsx import type { CheckoutOutcome } from "@pesepay/js"; import { CheckoutElement, Elements } from "@pesepay/react"; export function CheckoutForm({ referenceNumber, onFinished, }: { referenceNumber: string; onFinished: (outcome: CheckoutOutcome) => void; }) { return ( onFinished(event.outcome)} // The methods could not load: Pesepay's hosted checkout takes the payment. onLoadError={(event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }} /> ); } ``` Render it with the reference number, and say what happens next: ```tsx { if (outcome === 'succeeded') navigate('/order-complete'); }} /> ``` Using Next.js? Add `"use client"` at the top of the file; Elements renders nothing on the server. * Vue Checkout.vue ```vue ``` Render it with the reference number, and say what happens next: ```vue ``` It is safe with server-side rendering, including Nuxt. * Angular checkout.component.ts ```ts import { Component, computed, input, output } from "@angular/core"; import type { CheckoutOutcome } from "@pesepay/js"; import { CheckoutElement, Elements } from "@pesepay/angular"; @Component({ selector: "app-checkout", imports: [Elements, CheckoutElement], template: ` `, }) export class CheckoutComponent { readonly referenceNumber = input.required(); /** * The payment has ended and the element shows the result. Fulfil the order * on your server, which Pesepay notifies too. */ readonly finished = output(); protected readonly options = computed(() => ({ referenceNumber: this.referenceNumber(), })); // The methods could not load: Pesepay's hosted checkout takes the payment. leave(fallbackUrl: string | undefined): void { if (fallbackUrl) window.location.assign(fallbackUrl); } } ``` Render it with the reference number, and say what happens next: ```html ``` It is safe with server-side rendering. For O’mari, the element’s button then asks for the code from the SMS. For EcoCash and scan codes, the element waits while the customer finishes on their phone. `finished` is sent once, with an `outcome`: | Outcome | What it means | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `succeeded` | The customer paid. | | `failed` | The customer did not pay: declined, cancelled or closed. A declined transaction can’t be paid again: create a new one to let the customer retry. | | `reversed` | The customer paid, then the money was returned. | | `unknown` | No answer came in time. The customer may still pay, so don’t let them pay again until your server has the result. | Want your own Pay button, with each step in your code? See [Custom payment flow](/embedded-checkout/custom-payment-flow/). 4. ### Coming back from the bank [Section titled “Coming back from the bank”](#coming-back-from-the-bank) A Visa card that needs 3-D Secure, and Mastercard or Zimswitch, take the customer to their bank. They come back to the `returnUrl` you set when you [created the payment](#create-the-payment-on-your-server), your checkout page, with `?referenceNumber=` added. Render the page with the same reference number, reusing the order’s transaction rather than creating a new one. The element shows the result in place of the methods and sends `finished`. A transaction that is already paid, or still being paid, is never offered the methods again: the element shows its result, or waits for it. 5. ### Make a small live payment [Section titled “Make a small live payment”](#make-a-small-live-payment) Open your checkout page with the order’s reference number and pay a small amount, such as USD 1, with your own card or EcoCash number. A Visa card shows its bank’s 3-D Secure check and comes back to your checkout page ([Coming back from the bank](#coming-back-from-the-bank)); EcoCash sends a prompt to your phone while the element waits. 6. ### Confirm the payment on your server [Section titled “Confirm the payment on your server”](#confirm-the-payment-on-your-server) Don’t fulfil the order on what the browser reports. Pesepay posts the outcome to your `resultUrl` ([The result callback](/webhooks/result-callback/)); treat the post as a prompt, then [check the payment status](/api/check-payment-status/) from your server and fulfil only on `SUCCESS`. ## What’s next [Section titled “What’s next”](#whats-next) * [Accept a payment](/embedded-checkout/guides/accept-a-payment/): what a live checkout needs on top of this page * [Embedded checkout overview](/embedded-checkout/): how the pieces fit and where card details go * [Custom payment flow](/embedded-checkout/custom-payment-flow/): your own Pay button, with each step in your code * [Go-live checklist](/getting-started/go-live-checklist/): what to check before you take real orders # @pesepay/react > React components for Pesepay Elements, with hooks, Strict Mode and server rendering. ![](/_astro/react.BwygIBQc_Z1z4nbv.svg) `@pesepay/react` [npm](https://www.npmjs.com/package/@pesepay/react) React components for Pesepay Elements. React 18 or 19. `npm install @pesepay/js @pesepay/react` The components create, mount and destroy the elements from [`@pesepay/js`](/embedded-checkout/javascript/) for you, including under Strict Mode and server rendering. ## Take a payment [Section titled “Take a payment”](#take-a-payment) Your server creates the transaction and passes its reference number to the component: src/CheckoutForm.tsx ```tsx import type { CheckoutOutcome } from "@pesepay/js"; import { CheckoutElement, Elements } from "@pesepay/react"; export function CheckoutForm({ referenceNumber, onFinished, }: { referenceNumber: string; onFinished: (outcome: CheckoutOutcome) => void; }) { return ( onFinished(event.outcome)} // The methods could not load: Pesepay's hosted checkout takes the payment. onLoadError={(event) => { if (event.fallbackUrl) window.location.assign(event.fallbackUrl); }} /> ); } ``` `` lists the methods and pays with its own button. It runs every step itself, including the result when the customer comes back from 3-D Secure, and calls `onFinished` once with `outcome`: `succeeded`, `failed`, `reversed` or `unknown`. For your own Pay button, see [Custom payment flow](/embedded-checkout/custom-payment-flow/). ## `` [Section titled “\”](#elements) | Prop | Type | Notes | | ---------- | --------------------------------------------- | ------------------------------------------------------------------------- | | `pesepay` | `Pesepay \| null \| Promise` | Optional. What `loadPesepay()` returns. Fixed on first render. | | `options` | `ElementsOptions` | `theme`, `fonts`, `locale` for every element inside. Changes are applied. | | `children` | `ReactNode` | | Left out, `pesepay` defaults to loading Pesepay with the default options in the browser. To set options, such as `apiBaseUrl`, call `loadPesepay({ apiBaseUrl })` once, outside the component, and pass the promise. `` creates one elements group and destroys it, and every element in it, when it unmounts. Group-wide options that change are passed to `elements.update()`. `usePesepay()` and `useElements()` return the instance and the group, or `null` while Pesepay loads and during server rendering. Both throw outside ``. ## Element components [Section titled “Element components”](#element-components) | Component | Element | `options` | | --------------------- | ------------ | ------------------------------- | | `` | `checkout` | required: `{ referenceNumber }` | | `` | `payment` | required: `{ referenceNumber }` | | `` | `card` | optional | | `` | `mobile` | optional: `{ provider }`, … | | `` | `scan` | optional: `{ provider }` | | `` | `hostedCard` | required: `{ cardCheckout }` | Each renders a `
`, with your `id` and `className`, and mounts its element into it. Event props are typed for the element: `onReady`, `onChange`, `onFocus`, `onBlur`, `onEscape` and `onLoadError`, plus `onStatus` on the mobile and payment elements and `onFinished` on the checkout element. A new handler on each render is fine; it does not subscribe again. Changed `options` are passed to the element’s `update()`. A payment or checkout element given a new `referenceNumber` is replaced, since one element pays one transaction. Outside the checkout element, to pay, read the element off the group with `elements.getElement(type)` and pass it to `confirmPayment()`. One `` holds one element of each type; for two card fields, use two ``. ## Server rendering [Section titled “Server rendering”](#server-rendering) `` loads nothing on the server, and `loadPesepay()` resolves `null` there, so `` renders its children and each element component renders an empty `
`. The components are marked `"use client"`, so the Next.js App Router can import them from a server component. See [Server-side rendering](/embedded-checkout/guides/server-rendering/) for a Next.js checkout page. ## What’s next [Section titled “What’s next”](#whats-next) * [Quickstart](/embedded-checkout/quickstart/): the whole checkout, server included * [Guides](/embedded-checkout/guides/accept-a-payment/): each method, errors and theming, with React code * [Elements SDK reference](/embedded-checkout/reference/react/): every component, prop and hook # @pesepay/vue > Vue components for Pesepay Elements, with composables and server rendering, including Nuxt. ![](/_astro/vue.RJ05orgw_Z1z4nbv.svg) `@pesepay/vue` [npm](https://www.npmjs.com/package/@pesepay/vue) Vue components for Pesepay Elements. Vue 3.5 or later. `npm install @pesepay/js @pesepay/vue` The components create, mount and destroy the elements from [`@pesepay/js`](/embedded-checkout/javascript/) for you, including under server rendering. ## Take a payment [Section titled “Take a payment”](#take-a-payment) Your server creates the transaction and passes its reference number to the component: src/Checkout.vue ```vue ``` `` lists the methods and pays with its own button. It runs every step itself, including the result when the customer comes back from 3-D Secure, and emits `finished` once with `outcome`: `succeeded`, `failed`, `reversed` or `unknown`. For your own Pay button, see [Custom payment flow](/embedded-checkout/custom-payment-flow/). ## `` [Section titled “\”](#elements) | Prop | Type | Notes | | --------- | --------------------------------------------- | ------------------------------------------------------------------------- | | `pesepay` | `Pesepay \| null \| Promise` | Optional. What `loadPesepay()` returns. Fixed on first render. | | `options` | `ElementsOptions` | `theme`, `fonts`, `locale` for every element inside. Changes are applied. | Left out, `pesepay` defaults to loading Pesepay with the default options in the browser. To set options, such as `apiBaseUrl`, call `loadPesepay({ apiBaseUrl })` once, outside the component, and pass the promise. `` creates one elements group once it is mounted and Pesepay has loaded, and destroys it, and every element in it, when it unmounts. Group-wide options that change, including a reactive object changed in place, are passed to `elements.update()`. Its default slot receives `{ pesepay, elements }`, so the component that renders `` can pay. In a child component, `usePesepay()` and `useElements()` return the same two as shallow refs. All of them are `null` while Pesepay loads and during server rendering. The composables throw outside ``. ## Element components [Section titled “Element components”](#element-components) | Component | Element | `options` | | --------------------- | ------------ | ------------------------------- | | `` | `checkout` | required: `{ referenceNumber }` | | `` | `payment` | required: `{ referenceNumber }` | | `` | `card` | optional | | `` | `mobile` | optional: `{ provider }`, … | | `` | `scan` | optional: `{ provider }` | | `` | `hostedCard` | required: `{ cardCheckout }` | Each renders a `
`, with your `id` and `class`, and mounts its element into it. Events are typed for the element: `@ready`, `@change`, `@focus`, `@blur`, `@escape` and `@load-error`, plus `@status` on the mobile and payment elements and `@finished` on the checkout element. Changed `options` are passed to the element’s `update()`. A payment or checkout element given a new `referenceNumber` is replaced, since one element pays one transaction. Outside the checkout element, to pay, read the element off the group with `elements.getElement(type)` and pass it to `confirmPayment()`. One `` holds one element of each type; for two card fields, use two ``. ## Server rendering [Section titled “Server rendering”](#server-rendering) `` loads nothing before it is mounted, and `loadPesepay()` resolves `null` on the server. On the server, and in Nuxt, each element component renders an empty `
`. See [Server-side rendering](/embedded-checkout/guides/server-rendering/). ## What’s next [Section titled “What’s next”](#whats-next) * [Quickstart](/embedded-checkout/quickstart/): the whole checkout, server included * [Guides](/embedded-checkout/guides/accept-a-payment/): each method, errors and theming, with Vue code * [Elements SDK reference](/embedded-checkout/reference/vue/): every component, prop and composable