Cấu hình & Xử lý IPN (Instant Payment Notification)

Cơ chế nhận webhook thông báo tự động khi khách hàng thanh toán xong, xác thực chữ ký số HMAC và xử lý giao dịch an toàn.

Xem Markdown

IPN (Instant Payment Notification) là luồng thông báo bất đồng bộ gửi trực tiếp từ máy chủ HiTechCloud Pay tới máy chủ của bạn để thông báo kết quả thanh toán. IPN là kênh xác thực chính xác nhất để kích hoạt đơn hàng, cộng tiền hoặc mở khóa dịch vụ cho khách.

Quy chuẩn phản hồi IPN từ Server của bạn

Tiêu chíQuy định bắt buộc
HTTP Status CodeBắt buộc trả về 200 hoặc 201
Response BodyBắt buộc trả về JSON chính xác: {"success": true}
Thời gian phản hồiTối đa trong vòng 30 giây (khuyến nghị dưới 2 giây)
Header xác thựcKiểm tra chữ ký số trong header X-HiTechCloud-Signature
Nếu server của bạn trả về HTTP khác 200/201, hoặc nội dung JSON khác {"success": true}, hoặc bị timeout quá 30 giây, hệ thống HiTechCloud Pay sẽ coi như thất bại và tự động thử gửi lại (retry) theo lịch trình lũy tiến.

Payload JSON mẫu do HiTechCloud Pay gửi đến IPN

Cấu trúc dữ liệu IPN đầy đủ
{
  "timestamp": 1759134682,
  "notification_type": "ORDER_PAID",
  "signature": "c5a892b45e9981fcae12760...",
  "order": {
    "id": "e2c195be-c721-47eb-b323-99ab24e52d85",
    "order_id": "HTC-68DA43D73C1A5",
    "order_status": "CAPTURED",
    "order_currency": "VND",
    "order_amount": "250000.00",
    "order_invoice_number": "INV-1759134677",
    "order_description": "Thanh toan don hang #INV-1234"
  },
  "transaction": {
    "id": "384c66dd-41e6-4316-a544-b4141682595c",
    "payment_method": "BANK_TRANSFER",
    "transaction_id": "68da43da2d9de",
    "transaction_type": "PAYMENT",
    "transaction_date": "2026-10-31 09:12:14",
    "transaction_status": "APPROVED",
    "transaction_amount": "250000.00",
    "transaction_currency": "VND",
    "bank_name": "Vietcombank",
    "bank_account_number": "9988776655",
    "reference_number": "FT261031998877"
  }
}

Mã nguồn xử lý IPN hoàn chỉnh bằng PHP

IPN Receiver an toàn trong PHP (với xác thực chữ ký & chống trùng)
<?php
header('Content-Type: application/json');

$secret_key = "YOUR_SECRET_KEY";

// 1. Nhận raw body
$raw_body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_HITECHCLOUD_SIGNATURE'] ?? '';

if (empty($raw_body)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Empty request body']);
    exit;
}

// 2. Xác thực chữ ký HMAC-SHA256
$expected_sig = hash_hmac('sha256', $raw_body, $secret_key);
if (!hash_equals($expected_sig, $signature)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Invalid signature']);
    exit;
}

$data = json_decode($raw_body, true);

// 3. Xử lý sự kiện ORDER_PAID
if ($data['notification_type'] === 'ORDER_PAID') {
    $invoice_number = $data['order']['order_invoice_number'];
    $amount         = (float)$data['transaction']['transaction_amount'];
    $trans_id       = $data['transaction']['transaction_id'];

    // Kết nối CSDL PDO
    $pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'user', 'pass');
    $pdo->beginTransaction();

    try {
        // Chống trùng lặp bằng transaction_id
        $check = $pdo->prepare("SELECT id FROM payment_transactions WHERE transaction_id = ?");
        $check->execute([$trans_id]);
        if ($check->fetch()) {
            $pdo->rollBack();
            // Đã xử lý trước đó, trả về success ngay để HiTechCloud Pay dừng retry
            echo json_encode(['success' => true, 'message' => 'Already processed']);
            exit;
        }

        // Ghi nhận giao dịch
        $ins = $pdo->prepare("INSERT INTO payment_transactions (transaction_id, invoice_number, amount, created_at) VALUES (?, ?, ?, NOW())");
        $ins->execute([$trans_id, $invoice_number, $amount]);

        // Cập nhật trạng thái đơn hàng sang PAID
        $upd = $pdo->prepare("UPDATE orders SET status = 'PAID', paid_at = NOW() WHERE invoice_number = ?");
        $upd->execute([$invoice_number]);

        $pdo->commit();
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        exit;
    }
}

// 4. Bắt buộc phản hồi HTTP 200 {"success": true}
http_response_code(200);
echo json_encode(['success' => true]);
IPN Receiver an toàn trong Node.js (Express)
import express from 'express';
import crypto from 'node:crypto';

const app = express();
// Lưu ý: Cần raw body để xác thực HMAC
app.use(express.json({
  verify: (req: any, _res, buf) => {
    req.rawBody = buf;
  }
}));

app.post('/api/hitechcloud-ipn', async (req: any, res) => {
  const signature = req.headers['x-hitechcloud-signature'] as string;
  const secretKey = process.env.HTC_SECRET_KEY!;

  // 1. Xác thực HMAC-SHA256
  const hmac = crypto.createHmac('sha256', secretKey);
  hmac.update(req.rawBody);
  const expectedSig = hmac.digest('hex');

  if (!signature || signature !== expectedSig) {
    return res.status(401).json({ success: false, message: 'Invalid signature' });
  }

  const { notification_type, order, transaction } = req.body;

  if (notification_type === 'ORDER_PAID') {
    const invoiceNumber = order.order_invoice_number;
    const transId = transaction.transaction_id;

    // 2. Chống xử lý trùng và kích hoạt đơn hàng
    console.log(`Đơn hàng ${invoiceNumber} đã thanh toán thành công qua GD ${transId}`);
  }

  // 3. Luôn phản hồi HTTP 200 {"success": true}
  return res.status(200).json({ success: true });
});