Skip to content

PHP 示例

示例为:POST /payIn/orders/createAndPay,签名串为 timestamp|nonce|rawBody

php
<?php
function sign($timestamp, $nonce, $body, $secret) {
    $signData = $timestamp . "|" . $nonce . "|" . $body;
    $hash = hash_hmac("sha256", $signData, $secret, true);
    return base64_encode($hash);
}

$body = json_encode([
    "merchantOrderNo" => "M202412220001",
    "amount" => "100.00",
    "currency" => "USD",
    "methodCode" => "INTERNATIONAL_CARD",
    "methodData" => [
        "cardNumber" => "4111111111111111",
        "expiryMonth" => "12",
        "expiryYear" => "27",
        "securityCode" => "123"
    ]
], JSON_UNESCAPED_UNICODE);

$timestamp = (string) (int) (microtime(true) * 1000);
$nonce = "b2b2f3b6a6f24a4ba3dcd0e777c9a888";
$signature = sign($timestamp, $nonce, $body, "sk_test_9f3b8a2d7c1e4f6a8b0c2d4e6f8a1b3c");

// 使用 cURL 或 Guzzle 发送请求并设置 Headers:
// X-Merchant-Id, X-Timestamp, X-Nonce, X-Sign

验签示例(回调)

rawBody 为实际接收的原始 JSON 字符串

php
<?php
function sign($timestamp, $nonce, $body, $secret) {
    $signData = $timestamp . "|" . $nonce . "|" . $body;
    $hash = hash_hmac("sha256", $signData, $secret, true);
    return base64_encode($hash);
}

function verify($timestamp, $nonce, $rawBody, $secret, $signHeader) {
    $expected = sign($timestamp, $nonce, $rawBody, $secret);
    return hash_equals($expected, $signHeader);
}

$rawBody = '{"payNo":"P202312230001","tradeStatus":"SUCCESS"}';
$timestamp = "1734921005000";
$nonce = "b2b2f3b6a6f24a4ba3dcd0e777c9a888";
$signHeader = "base64_signature_from_header";

$ok = verify($timestamp, $nonce, $rawBody, "sk_test_9f3b8a2d7c1e4f6a8b0c2d4e6f8a1b3c", $signHeader);
var_dump($ok);