Sample code for developers

Code a bank transfer checkout in three steps

Create a payment request, let the customer scan VietQR, receive the webhook and confirm the order. Sample code in PHP, Laravel, Node.js and Python that runs with a test key.

Sample code for developers
Integrating ApiPay bank transfer payments into a website or app

1. Create a payment request

From your server, call the API with the API key as Bearer base64(accessKey:secretKey). Send the receiving account’s bankPublicId, the amount and the transfer note. The API returns payUrl and qrUrl.

const auth = Buffer.from('your_access_key:your_secret_key').toString('base64');

const response = await fetch('https://app.apipay.vn/v1/client/payment-requests', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${auth}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    bankPublicId: 'bnk_abc123',
    amount: 500000,
    content: 'ORDER-12345',
  }),
});

const {data} = await response.json();
console.log(data.payUrl);
import base64
import requests

token = base64.b64encode(b'your_access_key:your_secret_key').decode()

response = requests.post(
    'https://app.apipay.vn/v1/client/payment-requests',
    headers={
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
    },
    json={
        'bankPublicId': 'bnk_abc123',
        'amount': 500000,
        'content': 'ORDER-12345',
    },
    timeout=30,
)

print(response.json()['data']['payUrl'])
<?php
$auth = base64_encode('your_access_key:your_secret_key');

$ch = curl_init('https://app.apipay.vn/v1/client/payment-requests');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer $auth", 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode([
        'bankPublicId' => 'bnk_abc123',
        'amount' => 500000,
        'content' => 'ORDER-12345',
    ]),
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);

echo $result['data']['payUrl'];
use Illuminate\Support\Facades\Http;

$response = Http::withToken(base64_encode('your_access_key:your_secret_key'))
    ->post('https://app.apipay.vn/v1/client/payment-requests', [
        'bankPublicId' => 'bnk_abc123',
        'amount' => 500000,
        'content' => 'ORDER-12345',
    ]);

return redirect()->away($response->json('data.payUrl'));

2. Show the VietQR

Send the customer to payUrl (a ready payment page with the QR, open-in-bank-app buttons and an expiry timer), or show the qrUrl image on your own checkout page.

<!-- Option 1: send the customer to the payment page -->
<a href="https://pay.apipay.vn/APIPAYJSC69C3F00A3212">Thanh toán / Pay</a>

<!-- Option 2: show the QR on your page -->
<img
  src="https://app.apipay.vn/v1/payment-requests/APIPAYJSC69C3F00A3212/qr-image"
  alt="VietQR"
  width="280"
  height="280"
/>

3. Receive the webhook and confirm the order

Register a webhook URL in the Dashboard. When money arrives, check the ApiPay-Signature header (HMAC-SHA256 of the raw body), skip sandbox events, then confirm the order by note and amount.

const crypto = require('crypto');
const express = require('express');

const app = express();

function isValidSignature(rawBody, signature, secret) {
  const expected = Buffer.from(crypto.createHmac('sha256', secret).update(rawBody).digest('hex'), 'hex');
  const received = Buffer.from(String(signature || ''), 'hex');
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

app.post('/webhooks/apipay', express.raw({type: '*/*'}), (req, res) => {
  if (!isValidSignature(req.body, req.headers['apipay-signature'], process.env.APIPAY_WEBHOOK_SECRET)) {
    return res.status(401).json({error: 'Invalid signature'});
  }

  const {event, sandbox, data} = JSON.parse(req.body.toString('utf8'));
  if (event === 'transaction.in' && !sandbox) {
    // Confirm the order by note and amount: data.content, data.amount
  }

  res.status(200).json({received: true});
});
import hashlib
import hmac
import json
import os

from flask import Flask, request

app = Flask(__name__)


def is_valid_signature(raw_body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature or "")


@app.post("/webhooks/apipay")
def apipay_webhook():
    raw_body = request.get_data()
    if not is_valid_signature(raw_body, request.headers.get("ApiPay-Signature"), os.environ["APIPAY_WEBHOOK_SECRET"]):
        return {"error": "Invalid signature"}, 401

    payload = json.loads(raw_body)
    if payload["event"] == "transaction.in" and not payload.get("sandbox"):
        pass  # Confirm the order by note and amount: payload["data"]["content"], payload["data"]["amount"]

    return {"received": True}, 200
<?php
$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_APIPAY_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $rawBody, getenv('APIPAY_WEBHOOK_SECRET'));

if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}

$payload = json_decode($rawBody, true);
if ($payload['event'] === 'transaction.in' && empty($payload['sandbox'])) {
    // Confirm the order by note and amount: $payload['data']['content'], $payload['data']['amount']
}

http_response_code(200);
echo json_encode(['received' => true]);
// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/apipay', function (Request $request) {
    $rawBody = $request->getContent();
    $expected = hash_hmac('sha256', $rawBody, config('services.apipay.webhook_secret'));

    if (!hash_equals($expected, (string) $request->header('ApiPay-Signature'))) {
        abort(401);
    }

    $payload = json_decode($rawBody, true);
    if ($payload['event'] === 'transaction.in' && empty($payload['sandbox'])) {
        // Confirm the order by note and amount: $payload['data']['content'], $payload['data']['amount']
    }

    return response()->json(['received' => true]);
});

The payment page your customer sees

This is the ready-made payUrl page: amount, bank, account number, note and VietQR code, with the order’s expiry time.

Read more

Know this before you code

API keys stay on the server; never ship the secretKey to a browser or app
Get bankPublicId from GET /v1/client/banks or the Dashboard
Verify the signature on the raw body, not on re-serialised JSON
An event can arrive more than once; handle each payment once
Use an ak_test_ key and a sandbox bank to test without real money
Selling one price many times? Send a Commerce priceId instead of amount

Example: a store selling online courses

01

The customer clicks Buy

The store’s server creates a 500,000 VND payment request with the note ORDER-12345 and sends the customer to payUrl.

02

The customer scans

They scan the VietQR in their banking app with the amount and note already filled in.

03

The store unlocks the course

The webhook arrives, the signature is valid and the note matches ORDER-12345. The store marks the order paid and emails the course access.

Frequently asked questions

Get an API key and try it

The docs have every payload, error code and example. Your AI agent can read them through MCP too.