Xendit Invoices: hosted payment links with verified callbacks

Create a Xendit Invoice, send the buyer to its hosted invoice_url, verify the x-callback-token on the invoice callback, confirm the status with the API and fulfil once. Covers expiry, refunds and Southeast Asian payment channels.

Provider
Xendit
Level
Beginner
Stacks
Node.js (Express), Python (FastAPI)
Code maturity
Simplified
Last verified
25 Nov 2026

Introduction

Xendit is a payments provider focused on Southeast Asia (notably Indonesia and the Philippines). Its Invoices product gives you a hosted payment page: you create an invoice on your server, Xendit returns an invoice_url, the buyer chooses a payment channel there, and Xendit calls your server back when the invoice is paid.

This is the fastest way to accept many local channels with one integration. This guide covers creation, the callback, verification, status checks and refunds.

Warning: Xendit's API reference pages could not be opened directly on 2026-11-25 (they render client-side); field names here come from Xendit's official SDK docs on GitHub, which are generated from the API spec. Re-check against the dashboard docs before going live.

What Invoices do

  • POST https://api.xendit.co/v2/invoices with external_id (your order id) and amount creates an invoice.
  • The response includes id, invoice_url, status (PENDING) and the expiry time.
  • The buyer pays on the hosted page. Status moves to PAID (and later SETTLED when funds settle) or EXPIRED.
  • Xendit sends an invoice callback to the URL configured in the dashboard, with an x-callback-token header you must check.

Countries

Xendit's primary markets are Indonesia (IDR) and the Philippines (PHP), with other Southeast Asian markets supported for some products. Channel and currency availability depends on your account's country and activation — check the dashboard rather than assuming.

Payment methods

One invoice can expose several channel types, depending on country and activation: cards, bank transfer / virtual accounts, e-wallets, QR payments and retail outlets. You can restrict channels with payment_methods on the invoice.

E-wallet availability is per country (local wallets in Indonesia and the Philippines); see the Xendit docs for the current list for your account.

When to use it

  • You sell in Indonesia or the Philippines and want virtual accounts, e-wallets and cards behind one link.
  • You need payment links for B2B invoicing, chat commerce or email (invoice_url can be shared).
  • You want minimal PCI scope and no frontend payment SDK.

When not to use it

  • You need a fully embedded card form or native mobile checkout — Xendit's Payments API / SDKs fit better.
  • Your buyers and entity are outside Xendit's markets.

Example scenarios

  • Indonesian online shop offering virtual accounts and e-wallets from one checkout link.
  • Philippine SaaS emailing invoices for annual plans.
  • Social-commerce seller pasting invoice_url into a chat conversation.

Registration

Sign up at the Xendit dashboard. You get test mode immediately; live mode requires business verification and channel activation per country.

Test mode

Test mode uses test API keys (separate from live keys). Invoices created in test mode can be paid with simulated payments from the dashboard or the hosted page's test flow, which triggers real callbacks to your URL.

Credentials

  • Secret API key — server only; create it in the dashboard with the minimum permissions you need (write for Money-in/Invoices, refunds if used).
  • Webhook verification token — shown on the dashboard's Webhook settings page; every callback carries it in x-callback-token.

Security: The verification token is a shared secret, not a signature. Keep it out of logs and rotate it if it leaks.

Environment configuration

Keep secrets in environment variables and commit only placeholders:

.env.example

# Xendit — test mode keys first
XENDIT_SECRET_KEY=replace-with-test-secret-key
XENDIT_CALLBACK_TOKEN=replace-with-webhook-verification-token
APP_BASE_URL=https://your-public-tunnel.example.com

Authentication

Xendit uses HTTP Basic auth: the secret key is the username and the password is empty (Authorization: Basic base64(secret_key + ":")). The SDKs do this when you pass the key: new Xendit({ secretKey }) in Node, xendit.set_api_key(...) in Python.

curl — create a test invoice

curl https://api.xendit.co/v2/invoices -X POST \
  -u "$XENDIT_SECRET_KEY:" \
  -H 'Content-Type: application/json' \
  -d '{"external_id":"order-1001","amount":150000,"currency":"IDR","description":"Order 1001"}'

Backend: create an invoice

Load the amount from your database. amount is a plain number in the currency's major unit (e.g. 150000 IDR). Use your order id as external_id.

server.js — xendit-node v7 · Node.js (Express)

import express from 'express';
import { Xendit } from 'xendit-node';

const app = express();
const { Invoice } = new Xendit({ secretKey: process.env.XENDIT_SECRET_KEY });
const BASE = process.env.APP_BASE_URL;

app.post('/checkout/:orderId', async (req, res) => {
  const order = await db.orders.findById(req.params.orderId); // your data layer
  if (!order || order.status !== 'unpaid') return res.status(404).end();

  const invoice = await Invoice.createInvoice({
    data: {
      externalId: order.id,
      amount: order.total,          // major units, e.g. 150000 for IDR
      currency: order.currency,     // 'IDR' | 'PHP' ...
      description: `Order ${order.id}`,
      payerEmail: order.email,
      invoiceDuration: 86400,       // seconds
      successRedirectUrl: `${BASE}/orders/${order.id}/return`,
      failureRedirectUrl: `${BASE}/orders/${order.id}/return`,
    },
  });

  await db.orders.update(order.id, { xenditInvoiceId: invoice.id, status: 'awaiting_payment' });
  res.json({ redirectUrl: invoice.invoiceUrl });
});

app.listen(3000);

main.py — xendit-python InvoiceApi · Python (FastAPI)

import os, xendit
from fastapi import FastAPI, HTTPException
from xendit.apis import InvoiceApi
from xendit.invoice.model.create_invoice_request import CreateInvoiceRequest

xendit.set_api_key(os.environ['XENDIT_SECRET_KEY'])
invoice_api = InvoiceApi(xendit.ApiClient())
BASE = os.environ['APP_BASE_URL']
app = FastAPI()

@app.post('/checkout/{order_id}')
def checkout(order_id: str):
    order = orders.get(order_id)  # your data layer
    if not order or order['status'] != 'unpaid':
        raise HTTPException(404)
    invoice = invoice_api.create_invoice(create_invoice_request=CreateInvoiceRequest(
        external_id=order_id,
        amount=float(order['total']),
        currency=order['currency'],
        description=f'Order {order_id}',
        payer_email=order['email'],
        invoice_duration=86400,
        success_redirect_url=f'{BASE}/orders/{order_id}/return',
        failure_redirect_url=f'{BASE}/orders/{order_id}/return',
    ))
    orders.update(order_id, xendit_invoice_id=invoice.id, status='awaiting_payment')
    return {'redirectUrl': invoice.invoice_url}

Tip: Generated SDK models use camelCase in Node (externalId, invoiceUrl) and snake_case in Python and in the raw REST API (external_id, invoice_url).

Frontend

No payment SDK is needed: the button calls your /checkout/:orderId route and redirects to redirectUrl (the invoice_url). The frontend never sends the amount and never decides an order is paid.

Initiating the payment

  • Create the invoice server-side with external_id = order.id.
  • Save the invoice id on the order and redirect to invoice_url.
  • If the buyer comes back later, reuse the existing PENDING invoice instead of creating another, so one order cannot be paid twice.

Confirmation and redirects

success_redirect_url only means the buyer's browser came back. Show "confirming your payment" and read your own order status (updated by the callback), or fetch the invoice server-side with GET /v2/invoices/{id}.

Security: Never fulfil on the success redirect — the URL can be visited without paying.

Invoice callback: verify x-callback-token

Set the Invoices paid callback URL in the dashboard's webhook settings. Each callback has an x-callback-token header; compare it (constant-time) with your verification token and reject mismatches.

Return a 2xx quickly and do slow work afterwards. If Xendit does not get a 2xx it retries up to six times with exponential backoff, and you can re-send from the dashboard — so handle duplicates. Deduplicate on the invoice id plus status, and re-fetch the invoice before fulfilling.

webhook.js — token check + idempotent update · Node.js (Express)

import express from 'express';
import { timingSafeEqual } from 'node:crypto';
import { Xendit } from 'xendit-node';

const router = express.Router();
const { Invoice } = new Xendit({ secretKey: process.env.XENDIT_SECRET_KEY });

function tokenOk(received) {
  const a = Buffer.from(String(received ?? ''));
  const b = Buffer.from(process.env.XENDIT_CALLBACK_TOKEN);
  return a.length === b.length && timingSafeEqual(a, b);
}

router.post('/webhooks/xendit/invoice', express.json(), async (req, res) => {
  if (!tokenOk(req.get('x-callback-token'))) return res.status(401).end();
  res.sendStatus(200); // acknowledge first

  try {
    // The callback body is a hint; read the invoice from the API
    const inv = await Invoice.getInvoiceById({ invoiceId: req.body.id });
    const order = await db.orders.findById(inv.externalId);
    if (!order) return;
    const paid = ['PAID', 'SETTLED'].includes(inv.status)
      && Number(inv.amount) === Number(order.total) && inv.currency === order.currency;
    if (paid) {
      const won = await db.orders.updateWhere(
        { id: order.id, status: { $ne: 'paid' } },
        { status: 'paid', xenditInvoiceId: inv.id },
      );
      if (won) await fulfil(order.id);
    } else if (inv.status === 'EXPIRED') {
      await db.orders.updateWhere({ id: order.id, status: 'awaiting_payment' }, { status: 'expired' });
    }
  } catch (e) {
    console.error('xendit callback processing failed', e.message); // re-queue in production
  }
});

export default router;

webhook.py — token check · Python (FastAPI)

import hmac, os
from fastapi import APIRouter, Request, BackgroundTasks, Response

router = APIRouter()
TOKEN = os.environ['XENDIT_CALLBACK_TOKEN']

@router.post('/webhooks/xendit/invoice')
async def invoice_callback(request: Request, tasks: BackgroundTasks):
    received = request.headers.get('x-callback-token', '')
    if not hmac.compare_digest(received, TOKEN):
        return Response(status_code=401)
    body = await request.json()
    tasks.add_task(apply_invoice, body.get('id'))  # fetch + idempotent update
    return Response(status_code=200)

def apply_invoice(invoice_id: str):
    inv = invoice_api.get_invoice_by_id(invoice_id)
    order = orders.get(inv.external_id)
    if order and str(inv.status) in ('PAID', 'SETTLED') \
            and float(inv.amount) == float(order['total']):
        # conditional update: UPDATE ... SET status='paid' WHERE id=? AND status<>'paid'
        if orders.mark_paid_once(order['id'], inv.id):
            fulfil(order['id'])

Warning: The webhook docs do not name a dedicated event-id header for Invoices; dedupe with the invoice id and status, and rely on the conditional update for safety.

Status check

GET /v2/invoices/{invoice_id} returns the current invoice. Statuses: PENDING, PAID, SETTLED, EXPIRED. You can also list invoices filtered by external_id (GET /v2/invoices?external_id=...) for a reconciliation job.

To cancel an unpaid invoice (e.g. the cart changed), expire it with POST /invoices/{invoice_id}/expire! (Node: Invoice.expireInvoice({ invoiceId })).

Refunds

Refunds go through the Refunds API: POST /refunds with invoice_id (or payment_request_id), amount, reason and an idempotency key. In Node (the SDK example uses reason CANCELLATION): new Xendit({ secretKey }).Refund.createRefund({ idempotencyKey, data: { invoiceId, amount, reason: 'CANCELLATION' } }).

Refunds are asynchronous; track their status rather than assuming success.

Warning: Refund support depends on the channel the buyer used (cards and some e-wallets support API refunds; virtual accounts and retail channels may not). We did not verify per-channel eligibility or the accepted reason values on 2026-11-25 — check the Refunds docs for your country.

Errors

  • 401/403 — wrong key, test/live mix-up, or a key without the needed permission.
  • 400 — validation errors (e.g. amount below the channel minimum, invalid currency for your account).
  • Duplicate external_id is allowed by default, so it does not protect you from double invoices — reuse an existing pending invoice yourself.
  • The SDKs throw on non-2xx responses (the Python SDK documents BadRequestError, UnauthorizedError, ForbiddenError and InvoiceNotFoundError models); log the API error_code and message, never the key.

Warning: Whether external_id uniqueness can be enforced by account setting was not verified; treat it as non-unique.

Going to production

  • Complete business verification and activate each channel you show.
  • Swap to live keys and a live callback token; use HTTPS callback URLs.
  • Run a reconciliation job for orders stuck in awaiting_payment.

Security checklist

  • Verify x-callback-token with a constant-time comparison.
  • Re-fetch the invoice and compare amount, currency and external_id with your order.
  • Idempotent fulfilment (conditional update or unique constraint).
  • Least-privilege secret key; secrets only in env vars.

Testing

Create invoices with test keys, open invoice_url, and complete a simulated payment (the test-mode page and dashboard offer simulation). Expose your server through a tunnel so the callback reaches it, and use the dashboard's webhook test/resend button to check duplicate handling.

Common mistakes

  • Fulfilling on success_redirect_url.
  • Comparing the callback token with == and logging it.
  • Sending amounts in cents (15000000 instead of 150000 IDR).
  • Treating SETTLED as a separate first payment and fulfilling twice — PAID then SETTLED are two updates for one payment.

Troubleshooting

  • Callbacks return 401 — the token in your env is from the other mode (test vs live) or has whitespace.
  • No callbacks — the callback URL is not set for the Invoices product, or it is not publicly reachable.
  • Channel missing on the invoice page — the channel is not activated for your account/country or excluded by payment_methods.

Further reading

Official documentation

Official documentation

Sources

More payment guides