Lập trình thanh toán chuyển khoản trong ba bước
Tạo yêu cầu thanh toán, cho khách quét VietQR, nhận webhook và xác nhận đơn. Mã mẫu PHP, Laravel, Node.js và Python, chạy được ngay với khóa thử nghiệm.

1. Tạo yêu cầu thanh toán
Từ server, gọi API với khóa API dạng Bearer base64(accessKey:secretKey). Truyền bankPublicId của tài khoản nhận tiền, số tiền và nội dung chuyển khoản. API trả về payUrl và 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. Hiển thị VietQR cho khách
Chuyển khách tới payUrl (trang thanh toán có sẵn QR, nút mở app ngân hàng, đồng hồ hết hạn), hoặc hiển thị ảnh qrUrl ngay trên trang thanh toán của bạn.
<!-- Cách 1: chuyển khách tới trang thanh toán -->
<a href="https://pay.apipay.vn/APIPAYJSC69C3F00A3212">Thanh toán / Pay</a>
<!-- Cách 2: hiển thị QR trên trang của bạn -->
<img
src="https://app.apipay.vn/v1/payment-requests/APIPAYJSC69C3F00A3212/qr-image"
alt="VietQR"
width="280"
height="280"
/>3. Nhận webhook và xác nhận đơn
Đăng ký URL webhook trong Dashboard. Khi tiền vào, kiểm tra header ApiPay-Signature (HMAC-SHA256 của body gốc), bỏ qua sự kiện sandbox, rồi xác nhận đơn theo nội dung và số tiền.
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) {
// Xác nhận đơn theo nội dung và số tiền: 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 # Xác nhận đơn theo nội dung và số tiền: 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'])) {
// Xác nhận đơn theo nội dung và số tiền: $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'])) {
// Xác nhận đơn theo nội dung và số tiền: $payload['data']['content'], $payload['data']['amount']
}
return response()->json(['received' => true]);
});Trang thanh toán khách nhìn thấy
Đây là trang payUrl dựng sẵn: số tiền, ngân hàng, số tài khoản, nội dung và mã VietQR, kèm thời gian hết hạn của đơn.
Đọc thêm
Những điều cần biết trước khi viết code
Ví dụ: shop bán khóa học online
Khách bấm Mua
Server của shop gọi API tạo yêu cầu thanh toán 500.000đ với nội dung ORDER-12345 và chuyển khách tới payUrl.
Khách quét QR
Khách quét VietQR bằng app ngân hàng. Số tiền và nội dung đã điền sẵn.
Shop mở khóa học
Webhook về server, chữ ký hợp lệ, nội dung khớp ORDER-12345. Shop đánh dấu đơn đã trả và gửi email mở khóa học.
Câu hỏi thường gặp
Lấy khóa API và chạy thử
Tài liệu có đầy đủ payload, mã lỗi và ví dụ. AI agent của bạn cũng đọc được qua MCP.
