Use it in Next.js
app/pay/checkout.tsx
"use client";
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { init, createElement } from "@airwallex/components-sdk";
import CardCheckout, { type CardFieldsSlot } from "@/components/CardCheckout";
type Intent = { id: string; client_secret: string };
type Confirm = () => Promise<string | undefined>;
type Field = "number" | "expiry" | "cvc";
// init() loads Airwallex.js once per page, even when Strict Mode runs effects twice.
let sdk: ReturnType<typeof init> | undefined;
const loadAirwallex = () => (sdk ??= init({ env: "demo", enabledElements: ["payments"] }));
// The fields are iframes and don't read your CSS, so their text is styled here.
const style = { base: { color: "#f4f5f7", fontSize: "16px" } };
// getBinInfo's card_brand to the two marks the card draws. Other brands still pay, with no logo.
const brandOf = (b?: string) => {
const s = (b ?? "").toLowerCase();
return s.includes("visa") ? "visa" : s.includes("master") ? "mastercard" : null;
};
function AirwallexFields({ slot, intent, onReady }: {
slot: CardFieldsSlot;
intent: Intent;
onReady: (confirm: Confirm | null) => void;
}) {
const numberBox = useRef<HTMLDivElement>(null);
const expiryBox = useRef<HTMLDivElement>(null);
const cvcBox = useRef<HTMLDivElement>(null);
useEffect(() => {
let gone = false;
let cleanup = () => {};
const done: Record<Field, boolean> = { number: false, expiry: false, cvc: false };
const changed = (field: Field, completed: boolean) => {
done[field] = completed;
slot.onChange({ complete: done.number && done.expiry && done.cvc });
};
(async () => {
await loadAirwallex();
// In 1.36.0 createElement returns a Promise, so await it.
const [cardNumber, expiry, cvc] = await Promise.all([
createElement("cardNumber", { style }),
createElement("expiry", { style }),
createElement("cvc", { style }),
]);
cleanup = () => [cardNumber, expiry, cvc].forEach((el) => el.destroy());
if (gone) return cleanup();
cardNumber.on("change", (e) => {
changed("number", e.detail.completed);
if (!e.detail.completed) return slot.onChange({ brand: null });
// The change event carries no brand, so ask Airwallex once the number is complete.
cardNumber.getBinInfo(intent.client_secret)
.then((bin) => !gone && slot.onChange({ brand: brandOf(bin.card_brand) }))
.catch(() => {});
});
expiry.on("change", (e) => changed("expiry", e.detail.completed));
cvc.on("change", (e) => changed("cvc", e.detail.completed));
cardNumber.on("focus", () => slot.onChange({ focus: "number" }));
expiry.on("focus", () => slot.onChange({ focus: "expiry" }));
cvc.on("focus", () => slot.onChange({ focus: "cvc" })); // flips the card
cvc.on("blur", () => slot.onChange({ focus: null }));
cardNumber.mount(numberBox.current!);
expiry.mount(expiryBox.current!);
cvc.mount(cvcBox.current!);
// confirm() goes on the card number element; it picks up expiry and CVC by itself.
onReady(async () => {
const result = await cardNumber.confirm({ intent_id: intent.id, client_secret: intent.client_secret });
return result.status;
});
})();
return () => {
gone = true;
onReady(null);
cleanup();
};
}, [slot, intent, onReady]);
return (
<div className="space-y-3">
<div>
<label className={slot.labelClassName}>Card number</label>
<div ref={numberBox} className={slot.fieldClassName} />
</div>
<div className="flex gap-3">
<div className="flex-1">
<label className={slot.labelClassName}>Expiry</label>
<div ref={expiryBox} className={slot.fieldClassName} />
</div>
<div className="flex-1">
<label className={slot.labelClassName}>CVC</label>
<div ref={cvcBox} className={slot.fieldClassName} />
</div>
</div>
</div>
);
}
export default function AirwallexCardCheckout({ intent, amount }: { intent: Intent; amount: number }) {
const router = useRouter();
const confirm = useRef<Confirm | null>(null);
const setConfirm = useRef((c: Confirm | null) => (confirm.current = c)).current;
return (
<CardCheckout
amount={amount}
currency="USD"
resetAfter={null}
renderCardFields={(slot) => <AirwallexFields slot={slot} intent={intent} onReady={setConfirm} />}
onConfirm={async () => {
if (!confirm.current) throw new Error("The card fields haven't loaded yet.");
let status: string | undefined;
try {
status = await confirm.current();
} catch (err) {
const message = (err as { message?: string })?.message;
throw new Error(message || "That card didn't go through.");
}
if (status !== "SUCCEEDED") throw new Error("That card didn't go through.");
router.push("/thanks");
}}
/>
);
}
app/pay/page.tsx
import { createIntent } from "@/lib/airwallex";
import AirwallexCardCheckout from "./checkout";
export const dynamic = "force-dynamic";
export default async function PayPage() {
// The amount is set here on the server. A new PaymentIntent for every visit.
const intent = await createIntent(10, "USD");
return <AirwallexCardCheckout intent={intent} amount={10} />;
}
lib/airwallex.ts
// Server only. Your API key never reaches the browser.
const BASE = process.env.AIRWALLEX_API_URL ?? "https://api.sandbox.airwallex.com";
async function accessToken() {
const res = await fetch(`${BASE}/api/v1/authentication/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.AIRWALLEX_API_KEY!,
"x-client-id": process.env.AIRWALLEX_CLIENT_ID!,
},
cache: "no-store",
});
if (!res.ok) throw new Error(`Airwallex login failed (${res.status})`);
const { token } = (await res.json()) as { token: string };
return token; // reusable until expires_at; cache it in production
}
export async function createIntent(amount: number, currency: string) {
const res = await fetch(`${BASE}/api/v1/pa/payment_intents/create`, {
method: "POST",
headers: { Authorization: `Bearer ${await accessToken()}`, "Content-Type": "application/json" },
body: JSON.stringify({
request_id: crypto.randomUUID(),
amount, // major units: 10 is 10.00
currency,
merchant_order_id: crypto.randomUUID(),
return_url: `${process.env.NEXT_PUBLIC_SITE_URL}/pay`,
}),
cache: "no-store",
});
if (!res.ok) throw new Error(`Airwallex PaymentIntent failed (${res.status})`);
const { id, client_secret } = (await res.json()) as { id: string; client_secret: string };
return { id, client_secret };
}