Skip to main content

Integrate Papi with a headless WordPress

This guide is for developers who build a separate front end (Next.js, Nuxt, Astro, mobile application…) on top of a WooCommerce back office. It describes, step by step, what to configure in WordPress and what to code in the front end to accept Papi payments (MVola, Airtel Money, Orange Money, bank card).

info

Headless mode is optional and can be combined with the classic WordPress checkout: the same store can serve its WordPress theme and several front ends at the same time.

Headless mode is available from version 1.1.0 of the plugin. See the Downloads page.

How it works​

Payment uses a redirect flow: the customer leaves the front end for the Papi-hosted payment page, then comes back to a page of the front end. The payment confirmation arrives server to server (Papi webhook → WordPress), independently of the browser.

Front end                               WordPress / WooCommerce                 Papi
───────── ─────────────────────── ────
1. GET /wc/store/v1/cart ───► Cart-Token + payment_methods
2. POST /wc/store/v1/checkout ───► order created + Papi link ───►
payment_method: papi_gateway
papi_return_url: <return page> ◄─── payment_result.redirect_url ◄───
3. browser redirect ─────────────────────────────────────────► payment page
4. webhook (server to server) ◄─── payment finished
→ order "Processing"
5. browser returns to <return page>?papi_result=…&order_id=…&key=… ◄────
6. GET /papi/v1/order-status (polling) ───► payment_status: paid | pending | failed
warning

The browser return (step 5) can arrive before the webhook (step 4). The return page must never rely on the papi_result parameter alone: it must query the real payment status (step 6).

Prerequisites​

ItemRequirement
PluginPapi Payment Gateway for WooCommerce 1.1.0 or later, activated
WooCommerceStore API available (WooCommerce 8.x or later)
CurrencyMGA (Malagasy Ariary): amounts are sent to Papi as-is
WordPress back endPublicly reachable over HTTPS by the Papi servers (for the webhook)
API keyPapi store API key (dashboard.papi.mg → Boutiques → Developer)
Front endAble to send custom HTTP headers (Cart-Token)

WordPress permalinks do not matter: all examples use /wp-json/…, but the /?rest_route=/… form also works.

Configure the gateway in WordPress​

Open WooCommerce → Settings → Payments → Papi Payment.

  1. Check Enable/Disable, fill in the Papi API key, the Title and the Description.
  2. Fill in the Headless front (optional) section:
SettingRoleExample
Allowed front originsAllow list of front ends, one origin per line (scheme://host[:port], without a path). Only return URLs on these origins are accepted. These origins are also allowed in CORS on the Store API.https://shop.example.mg
https://m.example.mg
http://localhost:3000
Default return URLFront-end page used when the front end does not send its own URL. Its origin is automatically allowed.https://shop.example.mg/order/return
note

In the WordPress back office, these settings are labeled in French: Front headless (optionnel), Origines front autorisées and URL de retour par défaut.

Which mode should you choose?​

SituationAllowed originsDefault return URLFront end sends papi_return_url?
Single front end, no WordPress checkoutOptionalFilled inOptional
Mixed: WordPress checkout + one or more front endsAll front endsLeave emptyRequired
Classic WordPress onlyEmptyEmptyNot applicable
warning

In mixed mode, the default return URL must stay empty. Otherwise, customers who pay through the WordPress checkout would also be sent back to the front end after payment.

The webhook URL is displayed in the header of this section. You do not need to do anything with it: the plugin sends it to Papi with every payment (see The Papi webhook).

Front-end integration, step by step​

The examples use fetch (browser or Node.js 18+). Replace WP with the URL of your WordPress back end.

const WP = 'https://admin.example.mg';          // WordPress back end
const STORE = `${WP}/wp-json/wc/store/v1`;
const PAPI = `${WP}/wp-json/papi/v1`;
const RETURN_URL = 'https://shop.example.mg/order/return'; // return page of THIS front end

Step 1: get and keep a Cart-Token​

The Store API identifies a visitor's cart with the Cart-Token header (a JWT). The first /cart response provides one. Store it (localStorage, cookie on your domain, server session) and send it back on every following request. With a valid Cart-Token, no Nonce header is required.

async function storeFetch(path, { method = 'GET', body } = {}) {
const headers = { 'Content-Type': 'application/json' };
const token = localStorage.getItem('cartToken');
if (token) headers['Cart-Token'] = token;

const res = await fetch(`${STORE}${path}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});

const newToken = res.headers.get('Cart-Token');
if (newToken) localStorage.setItem('cartToken', newToken);

const data = await res.json();
if (!res.ok) throw Object.assign(new Error(data.message), { code: data.code, data });
return data;
}

const cart = await storeFetch('/cart');
await storeFetch('/cart/add-item', { method: 'POST', body: { id: 20, quantity: 1 } });

Step 2: display Papi in the list of payment methods​

GET /cart returns the available payment methods, but only their identifiers (payment_methods: ["papi_gateway", …]). The label, description and logo are available from the plugin endpoint:

const papi = await fetch(`${PAPI}/payment-method`).then(r => r.json());
// { id: "papi_gateway", enabled: true, title: "...", description: "...", icon: "https://…/logo-papi-full.svg" }

const showPapi = papi.enabled && cart.payment_methods.includes('papi_gateway');

Step 3: place the order​

Send the checkout with payment_method: "papi_gateway" and the URL of your return page in payment_data, under the papi_return_url key:

async function payWithPapi(billing, shipping) {
const order = await storeFetch('/checkout', {
method: 'POST',
body: {
billing_address: billing, // first_name, last_name, address_1, city, postcode, country, state, email, phone
shipping_address: shipping,
payment_method: 'papi_gateway',
payment_data: [
{ key: 'papi_return_url', value: RETURN_URL },
],
},
});

// Response: { order_id, order_key, status: "pending", payment_result: { payment_status, redirect_url } }
return order;
}

Rules for papi_return_url:

  • Its origin must be listed in Allowed front origins. Otherwise it is ignored: the plugin falls back to the default return URL, then to the WooCommerce pages, and a warning is logged.
  • It can contain a path and query parameters. The plugin appends papi_result, order_id and key.

If an error occurs (missing API key, Papi unreachable…), the request fails with an HTTP 4xx status and a message you can display:

{ "code": "woocommerce_rest_checkout_process_payment_error",
"message": "Erreur de configuration du paiement. Contactez le support." }

Step 4: redirect to Papi​

try {
const order = await payWithPapi(billing, shipping);
// Keep what you need to find the order again (for example to retry the payment, see step 6)
sessionStorage.setItem('lastOrder', JSON.stringify({ id: order.order_id, key: order.order_key }));
window.location.assign(order.payment_result.redirect_url);
} catch (e) {
showError(e.message);
}

The WooCommerce cart is cleared as soon as the Papi payment link is created.

Step 5: return page, check the real status​

Papi sends the browser back to:

https://shop.example.mg/order/return?papi_result=success&order_id=123&key=wc_order_AbC…
https://shop.example.mg/order/return?papi_result=failure&order_id=123&key=wc_order_AbC…

papi_result is only an indication. The return page queries /papi/v1/order-status until it gets a final status:

async function waitForPayment(orderId, key, { timeoutMs = 120000, intervalMs = 3000 } = {}) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const res = await fetch(`${PAPI}/order-status?order_id=${orderId}&key=${encodeURIComponent(key)}`);
if (res.status === 404) return { payment_status: 'not_found' };
const status = await res.json();
if (status.payment_status !== 'pending') return status; // "paid" or "failed"
await new Promise(r => setTimeout(r, intervalMs));
}
return { payment_status: 'pending' }; // still pending
}

const p = new URLSearchParams(location.search);
const result = await waitForPayment(p.get('order_id'), p.get('key'));
payment_statusRecommended display
paidOrder confirmation (order_number, total, currency).
failed"Payment declined" with a Retry button (step 6).
pending after the timeout"Payment is being confirmed, you will receive an email." Do not display a failure: the webhook can arrive later.
not_foundInvalid or expired link.

If papi_result=failure and the status stays pending, the customer probably abandoned the payment: offer to retry.

Step 6: retry the payment of an existing order (optional)​

To retry the payment without creating a new order, use the Store API "pay for order" route. It requires key, billing_email, both addresses and a Cart-Token:

const order = await storeFetch(`/checkout/${orderId}`, {
method: 'POST',
body: {
key: orderKey,
billing_email: billing.email,
billing_address: billing,
shipping_address: shipping, // required: WooCommerce 10.9 returns a 500 error without it
payment_method: 'papi_gateway',
payment_data: [{ key: 'papi_return_url', value: RETURN_URL }],
},
});
window.location.assign(order.payment_result.redirect_url);
Known limitation

Each new attempt generates a new Papi payment link and invalidates the notification of the previous link. If the customer still pays with an old browser tab, the order stays in Pending payment and must be validated manually. Always ask the customer to use the latest link.

A simpler alternative is to leave the order as failed and go through step 3 again with a new cart.

Server-rendered front ends (SSR / BFF)​

If the calls are made from your server (Next.js route handlers, Nuxt server routes…):

  • CORS does not apply.
  • Keep one Cart-Token per visitor (httpOnly cookie on your domain) and forward it with every call. Never share a token between visitors.
  • The redirect to Papi (redirect_url) must still happen in the browser.

The Papi webhook​

There is nothing to code in the front end. With every payment, the plugin sends Papi the following URL:

https://<back-end>/<WordPress path>/?rest_route=/papi/v1/webhook

It is built on the WordPress Address (siteurl) and not on the Site Address (home), which often points to the front end in a headless setup.

Check the following points:

  • The URL displayed in the settings is reachable from the Internet: no VPN, basic authentication, firewall or maintenance mode in front of /?rest_route=/papi/v1/webhook.
  • A call without a valid body must return 400 {"error":"Invalid notification data"}:
curl -X POST -H "Content-Type: application/json" -d '{}' "<webhook URL displayed in the settings>"

Received notifications are logged in WooCommerce → Status → Logs, source papi-gateway.

The legacy endpoint /?wc-api=wc_gateway_papi remains active for orders created before version 1.1.0.

Endpoint reference​

WooCommerce Store API (/wp-json/wc/store/v1)​

MethodRouteUsage
GET/cartCart, Cart-Token, payment_methods
POST/cart/add-itemAdd an item to the cart
POST/checkoutCreate the order and the Papi link (payment_result.redirect_url)
POST/checkout/{order_id}New payment attempt for an existing order

Papi-specific field in payment_data:

KeyTypeRequiredDescription
papi_return_urlstring (URL)No*Return page of the front end. *Required in mixed mode.

Plugin endpoints (/wp-json/papi/v1)​

GET /payment-method: public.

{ "id": "papi_gateway", "enabled": true, "title": "Paiement Mobile Money / Carte",
"description": "Payez par MVola, Airtel Money, Orange Money ou carte bancaire",
"icon": "https://admin.example.mg/wp-content/plugins/papi-woocommerce-gateway/assets/logo-papi-full.svg" }

GET /order-status?order_id={id}&key={order_key}: protected by the order key.

{ "order_id": 123, "order_number": "123", "order_status": "processing",
"payment_status": "paid", "total": "13000", "currency": "MGA" }

payment_status is paid, pending or failed. The response is 404 if the order does not exist, if the key is wrong, or if the order was not paid with Papi.

POST /webhook: reserved for Papi (authenticated by the notificationToken).

PHP filters​

Place these filters in a must-use plugin or in the theme, for cases the settings do not cover.

FilterParametersUsage
papi_gateway_front_return_url?string $url, WC_Order $orderChoose the front-end return URL (for example by order language or channel). null = WooCommerce pages.
papi_gateway_success_urlstring $url, WC_Order $orderRewrite the final success URL sent to Papi.
papi_gateway_failure_urlstring $url, WC_Order $orderRewrite the final failure URL sent to Papi.
papi_gateway_allowed_originsstring[] $originsAdd origins in code (for example from an environment variable).
papi_gateway_notification_urlstring $urlForce the webhook URL (for example behind a reverse proxy).

Example: origins from the environment.

add_filter('papi_gateway_allowed_origins', function ($origins) {
return array_merge($origins, array_filter(explode(',', getenv('PAPI_FRONT_ORIGINS') ?: '')));
});

Security​

  • The Papi API key never leaves WordPress. The front end never calls Papi directly.
  • Return URLs are allow-listed: a URL outside the allowed origins is ignored (no open redirect).
  • key in the return URL: this is the WooCommerce order key, the one already used by the "Order received" page. It only gives access to the payment status through /papi/v1/order-status.
  • Never validate an order in the front end based on papi_result: only the webhook is authoritative.
  • CORS: only allowed origins (and requests with a valid Cart-Token) can read Store API responses from a browser. Do not add *.
  • Do not enable the woocommerce_store_api_disable_nonce_check filter in production: use the Cart-Token.

Go-live checklist​

  • WooCommerce currency set to MGA
  • Production Papi API key filled in
  • Production front-end origins added (HTTPS, no trailing slash, no path)
  • Development origins (http://localhost:3000…) removed
  • Default return URL filled in (single front end) or empty (mixed mode)
  • The front end sends papi_return_url (required in mixed mode)
  • Webhook reachable from the Internet (curl test from The Papi webhook returns 400)
  • Return page polls order-status with a maximum delay and a "pending" message
  • Flows tested: successful payment, declined payment, abandonment on the Papi page, return before the webhook
  • papi-gateway logs checked after the first real payments

Troubleshooting​

SymptomLikely causeSolution
The customer returns to a WordPress page instead of the front endpapi_return_url missing, or origin not allowedCheck the list of origins. Search for URL de retour refusée in the papi-gateway logs.
CORS error on /wc/store/v1/cartFront-end origin not declaredAdd it to Allowed front origins.
401 woocommerce_rest_missing_nonceWrite request without Cart-TokenSend the Cart-Token obtained in step 1.
papi_gateway missing from payment_methodsGateway disabledCheck Enable/Disable in the gateway settings.
Order stuck in Pending payment although the customer paidWebhook not received (back end unreachable) or a new payment attempt in the meantimeTest the webhook URL, check the logs, and check the payment in the Papi dashboard.
403 {"error":"Invalid token"} in the logsNotification for an old payment link (see the known limitation in step 6)Validate the order manually after checking the Papi dashboard.
500 on POST /checkout/{id}shipping_address missing (WooCommerce 10.9 bug)Always send both addresses.