# XMPayment Merchant API — Full Specification for AI Agents Welcome to the XMPayment Developer Reference. This document is specifically formatted for AI coding agents (Claude, ChatGPT, Cursor, Windsurf, Devin, GitHub Copilot) to implement end-to-end QRIS payment integration, balance management, and DANA withdrawals into any merchant backend application. --- ## 1. Overview & Key Concepts XMPayment is an automated Indonesian QRIS payment gateway. - **Dynamic QRIS**: For each transaction, a unique 1-3 digit suffix is appended to the requested base amount (e.g. Base: Rp 50.000 + Unique Code: 23 = Payable Total: Rp 50.023). - **Automated Settlement & Reconciliation**: When the customer scans and transfers the exact amount (Rp 50.023) via any Indonesian banking or e-wallet app (BCA, Mandiri, BRI, BNI, DANA, GoPay, OVO, ShopeePay), the system matches it instantly and sends a webhook to the merchant. - **Settlement Window**: Merchant funds settle on a rolling 24-hour escrow schedule (T+1 / H+1) from Saldo Diproses (Processing Balance) into Saldo Tersedia (Available Balance), ready for withdrawal/payout. - **DANA Payouts**: Merchants can query real-time balance and request withdrawals directly to their DANA E-Wallet account via API. --- ## 2. Authentication & Environments All API requests to the gateway must include the merchant API key in either of the following HTTP headers: ```http Authorization: Bearer ``` or ```http x-api-key: ``` *(For balance & withdrawal endpoints, `live_apikey` can also be passed as query parameter `?live_apikey=...` or in the JSON request body).* ### Environments 1. **Sandbox / Test**: - API Key Prefix: `xmp_test_` - Test transactions do not deduct real balance. - You can test instant payment simulation by opening the checkout URL in a browser and clicking "Simulasikan Bayar (Sandbox)". - Payout and balance endpoints strictly reject Sandbox keys. 2. **Production / Live**: - API Key Prefix: `xmp_live_` - Real QRIS transactions through the national QRIS network. - Full access to balance inquiry and DANA withdrawal endpoints. - Available after KYC identity verification is approved by Super Admin. --- ## 3. REST API Endpoints ### 3.1. Create Transaction (Charge) Create a new transaction invoice and obtain the dynamic QR code string and hosted checkout URL. - **Method**: `POST` - **Path**: `/api/v1/create` (or `/api/v1/invoices`) - **Headers**: ```http Authorization: Bearer Content-Type: application/json ``` #### Request Body (JSON) | Field | Type | Required | Description | |---|---|---|---| | `order_id` | string | Yes | Unique reference or invoice ID from your system (e.g. `"ORD-2026-001"`). | | `amount` | integer/number | Yes | Base transaction amount in IDR without decimal (e.g. `50000` for Rp 50.000). | | `customer_name` | string | No | Customer's full name (e.g. `"Budi Santoso"`). | | `customer_email` | string | No | Customer's email address. | | `customer_phone` | string | No | Customer's WhatsApp/phone number. | | `description` | string | No | Order note or product summary. | | `callback_url` | string | No | Optional webhook override for this specific invoice. | | `return_url` / `redirect_url` | string | No | URL redirect halaman sukses merchant tempat pembeli dialihkan otomatis setelah pembayaran berhasil. | | `expiry_minutes` | integer | No | Expiration time in minutes (2 - 30 minutes, default: 15). | #### Example Request Body ```json { "order_id": "ORD-2026-001", "amount": 50000, "customer_name": "Budi Santoso", "customer_email": "budi@example.com", "redirect_url": "https://toko-anda.com/pembayaran-sukses" } ``` #### Response Body (Status: 201 Created) ```json { "success": true, "message": "Transaction created successfully", "data": { "id": "cly1234567890abcdef", "transaction_id": "cly1234567890abcdef", "order_id": "ORD-2026-001", "invoice_number": "INV-20260926-XXXX", "payment_method": "QRIS", "status": "PENDING", "base_amount": 50000, "unique_code": 23, "total_amount": 50023, "checkout_url": "https://xmpayment.my.id/pay/cly1234567890abcdef", "payment_token": "eyJhbGciOiJIUzI1NiIsIn...", "qr_string": "00020101021226...", "qr_code_url": "https://xmpayment.my.id/api/public/invoices/cly1234567890abcdef/qr", "expires_at": "2026-09-26T16:00:00.000Z", "is_sandbox": true } } ``` --- ### 3.2. Check Transaction Status Query the real-time status of a transaction at any time. - **Method**: `GET` - **Path**: `/api/v1/status/:order_id` (or `/api/v1/invoices/:id`) - **Headers**: ```http Authorization: Bearer ``` #### Response Body (Status: 200 OK) ```json { "success": true, "data": { "id": "cly1234567890abcdef", "order_id": "ORD-2026-001", "invoice_number": "INV-20260926-XXXX", "status": "SETTLED", "is_paid": true, "payment_method": "QRIS", "base_amount": 50000, "total_amount": 50023, "created_at": "2026-09-26T15:00:00.000Z", "paid_at": "2026-09-26T15:05:12.000Z", "expires_at": "2026-09-26T15:15:00.000Z" } } ``` #### Transaction Status Values - `PENDING`: Waiting for customer payment. - `SETTLED`: Payment successfully received and confirmed. - `EXPIRED`: Time limit exceeded without payment. - `CANCELLED`: Cancelled manually or via API. --- ### 3.3. Cancel Transaction Proactively cancels a pending invoice if the customer abandons checkout, immediately releasing the unique nominal slot. - **Method**: `POST` - **Path**: `/api/v1/cancel/:order_id` (or `/api/v1/invoices/:id/cancel`) - **Headers**: ```http Authorization: Bearer ``` #### Response Body (Status: 200 OK) ```json { "success": true, "message": "Transaction cancelled successfully", "data": { "order_id": "ORD-2026-001", "status": "CANCELLED", "cancelled_at": "2026-09-26T15:10:00.000Z" } } ``` --- ### 3.4. Check Merchant Balance (Live-Only) Retrieve real-time merchant balance metrics: Saldo Tersedia (available for withdrawal), Saldo Diproses (settlement hold window T+1), and Saldo Sedang Dicairkan (locked for pending payouts). - **Method**: `GET` or `POST` - **Path**: `/api/v1/balance` - **Headers**: ```http Authorization: Bearer ``` *(Or send query param `?live_apikey=` or JSON body `{"live_apikey": "..."}`)* - **Security**: Strictly requires Live API key (`xmp_live_...`). Requests with Sandbox keys will be rejected with HTTP 403 Forbidden. #### Example Request ```bash curl -X GET "https://xmpayment.my.id/api/v1/balance" \ -H "Authorization: Bearer xmp_live_xxxxxxxxxxxxxxxx" ``` #### Response Body (Status: 200 OK) ```json { "success": true, "message": "Data saldo berhasil diambil", "data": { "merchant_id": "cmu1234567890", "store_name": "Toko Berkah Mandiri", "mode": "live", "currency": "IDR", "available_balance": 500000, "available_balance_formatted": "Rp 500.000", "processing_balance": 250000, "processing_balance_formatted": "Rp 250.000", "withdrawing_balance": 100000, "withdrawing_balance_formatted": "Rp 100.000", "total_balance": 850000, "total_balance_formatted": "Rp 850.000", "pending_settlements_count": 2, "pending_payouts_count": 1, "saldo_tersedia": 500000, "saldo_proses": 250000, "saldo_sedang_dicairkan": 100000 } } ``` #### Error Response (Status: 403 Forbidden) ```json { "success": false, "message": "Akses ditolak: Endpoint cek saldo hanya dapat diakses menggunakan API key Live. Sandbox API key tidak diperbolehkan.", "error": { "code": "LIVE_API_KEY_REQUIRED", "message": "Akses ditolak: Endpoint cek saldo hanya dapat diakses menggunakan API key Live. Sandbox API key tidak diperbolehkan." } } ``` --- ### 3.5. Request Payout / Withdrawal to DANA (Live-Only) Dispatches an automated withdrawal request from the merchant's available balance to a DANA E-Wallet account. - **Method**: `POST` - **Path**: `/api/v1/payout` (alias: `/api/v1/withdraw`) - **Headers**: ```http Authorization: Bearer Content-Type: application/json ``` - **Security & Safeguards**: 1. **Live-Only**: Strictly rejects sandbox API keys with 403 Forbidden. 2. **Atomic Deduction**: Available balance is immediately deducted and locked in a single atomic database transaction. 3. **Phone Format**: Indonesian mobile format (`08...`, `628...`, or `+628...`). 4. **Minimum Amount**: Rp 10.000. 5. **Anti-Duplicate Window**: Identical withdrawal requests (same DANA number & amount) within 60 seconds are rejected with 409 Conflict. #### Request Body (JSON) | Field | Type | Required | Description | |---|---|---|---| | `nama_akun_dana` | string | Yes | Full name registered on the destination DANA account (min 2 chars). | | `nomor_dana` | string | Yes | DANA phone number (e.g. `"081234567890"` or `"6281234567890"`). | | `jumlah_pencairan` | integer | Yes | Withdrawal amount in IDR (min `10000`, whole integer). | | `live_apikey` | string | Optional | Can be passed in body if not using Authorization header. | #### Example Request Body ```json { "live_apikey": "xmp_live_xxxxxxxxxxxxxxxx", "nama_akun_dana": "Budi Santoso", "nomor_dana": "081234567890", "jumlah_pencairan": 50000 } ``` #### Response Body (Status: 201 Created) ```json { "success": true, "message": "Permintaan pencairan dana ke DANA E-Wallet berhasil dibuat dan sedang diproses", "data": { "payout_id": "cmupout12345678", "merchant_id": "cmu1234567890", "store_name": "Toko Berkah Mandiri", "status": "PENDING", "method": "DANA", "bank_name": "DANA E-Wallet", "nama_akun_dana": "Budi Santoso", "nomor_dana": "081234567890", "jumlah_pencairan": 50000, "jumlah_pencairan_formatted": "Rp 50.000", "created_at": "2026-10-02T02:00:00.000Z", "wallet": { "sisa_saldo_tersedia": 450000, "sisa_saldo_tersedia_formatted": "Rp 450.000", "saldo_sedang_dicairkan": 50000, "saldo_sedang_dicairkan_formatted": "Rp 50.000" } } } ``` #### Error Responses - **400 Bad Request (Insufficient Balance)**: ```json { "success": false, "message": "Insufficient available balance. Available: Rp 30.000", "error": { "code": "INSUFFICIENT_BALANCE", "message": "Insufficient available balance. Available: Rp 30.000" } } ``` - **409 Conflict (Duplicate Request)**: ```json { "success": false, "message": "Permintaan pencairan serupa ke nomor dan nominal yang sama baru saja dibuat. Harap tunggu 1 menit sebelum mengajukan kembali untuk mencegah pencairan ganda.", "error": { "code": "DUPLICATE_PAYOUT_REQUEST", "message": "Permintaan pencairan serupa ke nomor dan nominal yang sama baru saja dibuat..." } } ``` --- ## 4. Webhook Notifications When a transaction event occurs, XMPayment dispatches an HTTP POST request to your configured **Webhook URL** (set in Dashboard > Developers). ### 4.1. Security & Signature Verification Every webhook request includes the following headers: - `x-xmp-signature: sha256=` — Primary signature HMAC-SHA256 calculated over the exact raw body. - `x-signature-key: ` — Alternative signature HMAC-SHA256 calculated over `${order_id}:${status}:${total_amount}` using webhook secret. Also provided in `data.signature_key`. - `x-xmp-event: ` — e.g. `invoice.paid`, `invoice.expired`, `invoice.cancelled`, or `test.ping`. - `x-xmp-delivery: ` — Unique delivery ID for deduplication and replay attack prevention. #### Verification Algorithm: 1. Retrieve the raw HTTP request body as a string or binary buffer (do NOT parse JSON before computing the hash). 2. Calculate HMAC-SHA256 using your **Webhook Signing Secret** (from Dashboard > Developers > Webhook). 3. Prefix the resulting hexadecimal digest with `sha256=`. 4. Perform a timing-safe equality check between the header value and your calculated signature. 5. Alternatively, compare `x-signature-key` with `HMAC-SHA256(`${order_id}:${status}:${total_amount}`, secret)`. 6. If invalid, reject the request with HTTP `401 Unauthorized`. 7. If valid, process the event and respond with HTTP `200 OK` and JSON `{"received": true}`. ### 4.2. ⚠️ CRITICAL SECURITY WARNING & FRAUD DISCLAIMER (MUST READ) - **Sole Responsibility of Merchant Server**: As a Payment Gateway, XMPayment cryptographically signs every outgoing webhook payload using HMAC-SHA256. However, verifying the `x-xmp-signature` header on your incoming endpoint is **STRICTLY AND SOLELY THE RESPONSIBILITY OF THE MERCHANT BACKEND**. - **Fraud Risk Without Secret Verification**: Webhook URLs are publicly accessible on the internet. If your backend processes incoming webhook notifications without validating the `x-xmp-signature` header using your secret, any malicious actor or attacker can send forged HTTP POST requests (`curl`, Postman) directly to your server, causing your system to mark orders as "PAID" without any actual payment ever reaching the gateway. - **Payment Gateway Liability Disclaimer**: XMPayment will NOT be held liable for fraudulent order fulfillments, financial losses, or unauthorized credit grants arising from a merchant's failure or omission to verify webhook signatures or check transaction statuses via API. - **Two Safe Implementation Options for Merchants**: 1. **Option 1 (Recommended - HMAC Verification)**: Validate the `x-xmp-signature` header against HMAC-SHA256 of the raw payload using your Webhook Secret before updating order status. 2. **Option 2 (Safe Alternative - Double-Check via API)**: If you cannot easily calculate HMAC-SHA256 in your environment, do NOT trust the webhook payload blindly. Instead, when a webhook is received, have your backend call `GET /api/v1/status/:order_id` (or `/api/v1/invoices/:id`) using your API Key to verify with the XMPayment server that the transaction status is truly `SETTLED` before granting products or services. ### 4.3. Webhook Event Types - `invoice.paid`: Customer transferred the required amount. Transaction is settled (`status: SETTLED`). - `invoice.expired`: Invoice expired without receiving payment (`status: EXPIRED`). - `invoice.cancelled`: Invoice was cancelled (`status: CANCELLED`). - `test.ping`: Test webhook sent from Dashboard > Developers > Webhooks ("Kirim Uji Coba"). Responding with HTTP 200 confirms endpoint readiness. ### 4.4. Webhook Payload Example (`invoice.paid`) ```json { "event": "invoice.paid", "timestamp": "2026-09-26T15:05:12.000Z", "data": { "id": "cly1234567890abcdef", "order_id": "ORD-2026-001", "invoice_number": "INV-20260926-XXXX", "base_amount": 50000, "unique_code": 23, "total_amount": 50023, "status": "SETTLED", "paid_at": "2026-09-26T15:05:12.000Z" } } ``` --- ## 5. Ready-to-Use SDK Implementations ### 5.1. TypeScript / Node.js (Full Client & Webhook Handler) ```typescript import crypto from 'node:crypto'; import express, { Request, Response } from 'express'; const XMPAY_BASE_URL = 'https://xmpayment.my.id'; const XMPAY_API_KEY = process.env.XMPAY_API_KEY || 'xmp_test_...'; const XMPAY_WEBHOOK_SECRET = process.env.XMPAY_WEBHOOK_SECRET || 'secret_...'; // 1. Create Invoice Function export async function createQrisPayment(orderId: string, amount: number, customerName: string, customerEmail?: string) { const response = await fetch(`${XMPAY_BASE_URL}/api/v1/create`, { method: 'POST', headers: { 'Authorization': `Bearer ${XMPAY_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ order_id: orderId, amount, customer_name: customerName, customer_email: customerEmail, }), }); const result = await response.json(); if (!response.ok || !result.success) { throw new Error(result.message || 'Failed to create QRIS payment'); } // Returns { checkout_url, total_amount, qr_string, qr_code_url, expires_at } return result.data; } // 2. Check Balance (Live Key Required) export async function checkMerchantBalance(liveApiKey?: string) { const key = liveApiKey || XMPAY_API_KEY; const response = await fetch(`${XMPAY_BASE_URL}/api/v1/balance`, { headers: { 'Authorization': `Bearer ${key}` }, }); return response.json(); } // 3. Request Payout to DANA (Live Key Required) export async function withdrawToDana(danaName: string, danaPhone: string, amount: number, liveApiKey?: string) { const key = liveApiKey || XMPAY_API_KEY; const response = await fetch(`${XMPAY_BASE_URL}/api/v1/payout`, { method: 'POST', headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ nama_akun_dana: danaName, nomor_dana: danaPhone, jumlah_pencairan: amount, }), }); return response.json(); } // 4. Express Webhook Handler with Raw Body Signature Check const app = express(); app.post( '/api/webhook/xmpay', express.raw({ type: 'application/json' }), (req: Request, res: Response) => { const rawBody = (req.body as Buffer).toString('utf-8'); const signatureHeader = req.headers['x-xmp-signature'] as string; const expectedSignature = 'sha256=' + crypto.createHmac('sha256', XMPAY_WEBHOOK_SECRET).update(rawBody).digest('hex'); if (!crypto.timingSafeEqual(Buffer.from(signatureHeader || ''), Buffer.from(expectedSignature))) { return res.status(401).json({ message: 'Invalid webhook signature' }); } const payload = JSON.parse(rawBody); const { event, data } = payload; if (event === 'invoice.paid' && data.status === 'SETTLED') { const { order_id, total_amount } = data; console.log(`Order ${order_id} PAID: Rp ${total_amount}`); // TODO: Update database status to PAID } return res.status(200).json({ received: true }); } ); ``` --- ### 5.2. Python (FastAPI & Requests) ```python import hmac import hashlib import requests from fastapi import FastAPI, Request, HTTPException from fastapi.responses import JSONResponse XMPAY_BASE_URL = "https://xmpayment.my.id" XMPAY_API_KEY = "xmp_test_..." XMPAY_WEBHOOK_SECRET = "secret_..." # 1. Create Transaction def create_qris_payment(order_id: str, amount: int, customer_name: str, customer_email: str = None): url = f"{XMPAY_BASE_URL}/api/v1/create" headers = { "Authorization": f"Bearer {XMPAY_API_KEY}", "Content-Type": "application/json" } payload = { "order_id": order_id, "amount": amount, "customer_name": customer_name, "customer_email": customer_email } res = requests.post(url, json=payload, headers=headers) res.raise_for_status() return res.json()["data"] # 2. Check Balance (Live Key Required) def check_balance(live_api_key: str = None): key = live_api_key or XMPAY_API_KEY url = f"{XMPAY_BASE_URL}/api/v1/balance" headers = {"Authorization": f"Bearer {key}"} res = requests.get(url, headers=headers) return res.json() # 3. Withdraw to DANA (Live Key Required) def withdraw_to_dana(dana_name: str, dana_phone: str, amount: int, live_api_key: str = None): key = live_api_key or XMPAY_API_KEY url = f"{XMPAY_BASE_URL}/api/v1/payout" headers = { "Authorization": f"Bearer {key}", "Content-Type": "application/json" } payload = { "nama_akun_dana": dana_name, "nomor_dana": dana_phone, "jumlah_pencairan": amount } res = requests.post(url, json=payload, headers=headers) return res.json() # 4. Webhook Receiver app = FastAPI() @app.post("/api/webhook/xmpay") async def xmpay_webhook(request: Request): raw_body = await request.body() signature = request.headers.get("x-xmp-signature") expected_sig = "sha256=" + hmac.new( XMPAY_WEBHOOK_SECRET.encode(), raw_body, hashlib.sha256 ).hexdigest() if not hmac.compare_digest(str(signature), expected_sig): raise HTTPException(status_code=401, detail="Invalid signature") payload = await request.json() if payload.get("event") == "invoice.paid": order_id = payload["data"]["order_id"] # TODO: Mark order as PAID in database return JSONResponse(content={"received": True}, status_code=200) ``` --- ### 5.3. PHP / Laravel (Guzzle & Controller) ```php apiKey) ->post("{$this->baseUrl}/api/v1/create", [ 'order_id' => $orderId, 'amount' => $amount, 'customer_name' => $customerName, 'customer_email' => $customerEmail, ]); if ($response->successful() && $response->json('success')) { return $response->json('data'); } throw new \Exception($response->json('message', 'Failed to create payment')); } // 2. Check Merchant Balance (Live Key Required) public function checkBalance(?string $liveKey = null) { return Http::withToken($liveKey ?? $this->apiKey) ->get("{$this->baseUrl}/api/v1/balance") ->json(); } // 3. Request DANA Payout (Live Key Required) public function withdrawToDana(string $danaName, string $danaPhone, int $amount, ?string $liveKey = null) { return Http::withToken($liveKey ?? $this->apiKey) ->post("{$this->baseUrl}/api/v1/payout", [ 'nama_akun_dana' => $danaName, 'nomor_dana' => $danaPhone, 'jumlah_pencairan' => $amount, ]) ->json(); } // 4. Webhook Callback Handler public function handleWebhook(Request $request) { $rawPayload = $request->getContent(); $signature = $request->header('x-xmp-signature'); $expectedSignature = 'sha256=' . hash_hmac('sha256', $rawPayload, $this->webhookSecret); if (!hash_equals($expectedSignature, (string)$signature)) { return response()->json(['message' => 'Invalid signature'], 401); } $payload = json_decode($rawPayload, true); $event = $payload['event'] ?? ''; $data = $payload['data'] ?? []; if ($event === 'invoice.paid' && ($data['status'] ?? '') === 'SETTLED') { $orderId = $data['order_id']; $totalAmount = $data['total_amount']; // TODO: Mark Order as PAID in database } return response()->json(['received' => true], 200); } } ``` --- ## 6. Implementation Checklist for AI Agents When building an integration for this merchant, follow this checklist: 1. **Store Secrets Securely**: Put `XMPAY_API_KEY` and `XMPAY_WEBHOOK_SECRET` into environment variables (`.env`), never hardcode them. 2. **Handle Total vs Base Amount**: The customer must pay `total_amount` (which includes the unique anti-collision code). Save both `base_amount` and `total_amount` in your database. 3. **Verify Webhooks First**: Always verify the `x-xmp-signature` header against the raw body before parsing or processing order events. 4. **Idempotent Webhooks**: Check if the order was already marked as paid before granting credits to avoid duplicate fulfillment. 5. **Return HTTP 200**: Always return HTTP status 200 with `{"received": true}` so the webhook dispatcher knows delivery succeeded. 6. **Balance & Payout Integration**: Live key (`xmp_live_...`) is strictly required for `/api/v1/balance` and `/api/v1/payout`. Handle 403 Forbidden gracefully when developing in Sandbox mode.