Your own method picker
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:
listPaymentMethods()returns what Pesepay offers in the transaction’s currency. Each method is markedavailablewhen the order’s amount is within its limits. Show unavailable methods as disabled rather than hiding them.- When the customer picks one,
selectPaymentMethod()returns the total they will pay, fee included. Show it next to the button. - Create the element for that method, and destroy the last one.
- 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”| 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. The examples leave
them out, and skip any code they don’t know.
The picker
Section titled “The picker”The code is built and type-checked against the published packages.
<form id="picker-form" data-reference-number="REF-1"> <fieldset id="methods"> <legend>Pay with</legend> </fieldset> <div id="method-fields"></div> <p id="total"></p> <button type="submit" disabled>Pay</button> <p id="payment-message"></p></form><script type="module" src="/src/picker-pay.ts"></script>import { loadPesepay, type CardElement, type Elements, type MobileElement, type MobileProvider, type ScanElement, type ScanProvider,} from "@pesepay/js";
const form = document.querySelector<HTMLFormElement>("#picker-form")!;const methods = document.querySelector<HTMLElement>("#methods")!;const total = document.querySelector<HTMLElement>("#total")!;const button = form.querySelector<HTMLButtonElement>("button")!;const message = document.querySelector<HTMLElement>("#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<string, Choice> = { 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<void> { // 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<void> => { 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();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<string, Choice> = { 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 ( <Elements> <PayByPicker referenceNumber={referenceNumber} /> </Elements> );}
function PayByPicker({ referenceNumber }: { referenceNumber: string }) { const pesepay = usePesepay(); const elements = useElements(); const [methods, setMethods] = useState<PaymentMethod[]>([]); 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<void> { 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<void> { 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 ( <form onSubmit={(event) => { event.preventDefault(); void pay(); }} > <fieldset> <legend>Pay with</legend> {/* Unavailable methods are shown disabled: the amount is outside their limits. */} {methods.map((method) => ( <label key={method.code}> <input type="radio" name="method" checked={picked === method.code} disabled={!method.available} onChange={() => void pick(method.code)} />{" "} {method.name} </label> ))} </fieldset>
{/* One element at a time: each unmounts when another method is picked. */} {choice?.type === "card" && ( <CardElement onChange={(event) => setMessage(event.error?.message ?? "")} /> )} {choice?.type === "mobile" && ( <MobileElement key={picked} options={{ provider: choice.provider }} onChange={(event) => { 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" && ( <ScanElement key={picked} options={{ provider: choice.provider }} /> )}
<p>{total}</p> <button type="submit" disabled={!total}> {label} </button> <p>{message}</p> </form> );}<script setup lang="ts">import { computed, ref, shallowRef } from "vue";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/vue";
const props = defineProps<{ referenceNumber: string }>();
// 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<string, Choice> = { 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};
const methods = shallowRef<PaymentMethod[]>([]);const picked = ref("");const choice = computed<Choice | undefined>(() => ELEMENT_FOR[picked.value]);const total = ref("");const label = ref("Pay");const message = ref("");
// Loaded once, and shared with <Elements>.const loading = loadPesepay();void loading.then(async (pesepay) => { if (!pesepay) return; // On the server, or the runtime could not load. const listed = await pesepay.listPaymentMethods(props.referenceNumber); if (listed.error) message.value = listed.error.message; else methods.value = listed.paymentMethods.filter((method) => ELEMENT_FOR[method.code]);});
async function pick(pesepay: Pesepay | null, code: string): Promise<void> { if (!pesepay) return; picked.value = code; total.value = ""; label.value = "Pay"; message.value = "";
// The total the customer pays with this method, fee included. const priced = await pesepay.selectPaymentMethod(props.referenceNumber, code); if (priced.error) message.value = priced.error.message; else total.value = `Total: ${priced.amount.total.toFixed(2)} ${priced.amount.currency}`;}
function onChange(event: ContactChangeEvent): void { message.value = event.error?.message ?? ""; // O'mari has sent its SMS code, and the field now asks for it. if (event.step === "otp") label.value = "Confirm code";}
async function pay( pesepay: Pesepay | null, elements: PesepayElements | null,): Promise<void> { const element = choice.value && elements?.getElement(choice.value.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(props.referenceNumber, { element, paymentMethodCode: picked.value, }); if (result.error) { message.value = 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(props.referenceNumber, { timeoutMs: 300_000 }) : result; message.value = paid.error ? paid.error.message : paid.transaction.outcome;}</script>
<template> <Elements :pesepay="loading" v-slot="{ pesepay, elements }"> <form @submit.prevent="pay(pesepay, elements)"> <fieldset> <legend>Pay with</legend> <!-- Unavailable methods are shown disabled: the amount is outside their limits. --> <label v-for="method in methods" :key="method.code"> <input type="radio" name="method" :checked="picked === method.code" :disabled="!method.available" @change="pick(pesepay, method.code)" /> {{ method.name }} </label> </fieldset>
<!-- One element at a time: each unmounts when another method is picked. --> <CardElement v-if="choice?.type === 'card'" @change="(event) => (message = event.error?.message ?? '')" /> <MobileElement v-else-if="choice?.type === 'mobile'" :key="picked" :options="{ provider: choice.provider }" @change="onChange" /> <ScanElement v-else-if="choice?.type === 'scan'" :key="picked" :options="{ provider: choice.provider }" />
<p>{{ total }}</p> <button type="submit" :disabled="!total">{{ label }}</button> <p>{{ message }}</p> </form> </Elements></template>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<string, Choice> = { 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: ` <pesepay-elements [pesepay]="loading" #checkout="pesepayElements"> <form (submit)="pay($event, checkout.instance(), checkout.elements())"> <fieldset> <legend>Pay with</legend> <!-- Unavailable methods are shown disabled: the amount is outside their limits. --> @for (method of methods(); track method.code) { <label> <input type="radio" name="method" [checked]="picked() === method.code" [disabled]="!method.available" (change)="pick(checkout.instance(), method.code)" /> {{ method.name }} </label> } </fieldset>
<!-- One element at a time, tracked by method: picking another destroys this one and creates the next. --> @for (choice of [choice()]; track picked()) { @if (choice?.type === "card") { <pesepay-card-element (elementChange)="message.set($event.error?.message ?? '')" /> } @else if (choice?.type === "mobile") { <pesepay-mobile-element [options]="{ provider: choice.provider }" (elementChange)="onChange($event)" /> } @else if (choice?.type === "scan") { <pesepay-scan-element [options]="{ provider: choice.provider }" /> } }
<p>{{ total() }}</p> <button type="submit" [disabled]="!total()">{{ label() }}</button> <p>{{ message() }}</p> </form> </pesepay-elements> `,})export class PickerPayComponent implements OnInit { readonly referenceNumber = input.required<string>(); readonly methods = signal<PaymentMethod[]>([]); readonly picked = signal(""); readonly total = signal(""); readonly label = signal("Pay"); readonly message = signal(""); protected readonly choice = computed<Choice | undefined>( () => ELEMENT_FOR[this.picked()], ); // Loaded once, and shared with <pesepay-elements>. 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<void> { 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<void> { 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”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”- Cards and 3-D Secure, Mobile money approval and Scan to pay: each method in full, with the card return page
- Errors and fallbacks: what to show for each result