Skip to content

PHP ​

相容性

PHP 7.4+。僅依賴 curl 擴充套件(預設開啟)。

客戶端實現 ​

php
<?php
// brand.php
const BRAND_APP_ID = 'cp_a1b2c3d4...';
const BRAND_SECRET = 'f1e2d3c4...';
const BRAND_BASE   = 'https://api.coinepay.net';

// code 不為 0 的響應一律拋出該例外
class OpenAPIException extends RuntimeException {
    public int $httpStatus;
    public ?int $apiCode;      // 業務碼:40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
    public ?string $errorKey;  // 穩定的機器識別碼——據此分支,不要用 message
    public ?int $retryAfter;   // Retry-After 響應頭(秒),429 時設定

    public function __construct(string $message, int $httpStatus, ?int $apiCode, ?string $errorKey, ?int $retryAfter) {
        parent::__construct("HTTP $httpStatus code=$apiCode error_key=$errorKey: $message");
        $this->httpStatus = $httpStatus;
        $this->apiCode    = $apiCode;
        $this->errorKey   = $errorKey;
        $this->retryAfter = $retryAfter;
    }
}

// code === 0 時返回 data,否則拋出 OpenAPIException
function callOpenAPI(string $path, array $body = [], ?string $idempotencyKey = null): array {
    $bodyStr  = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $bodyHash = hash('sha256', $bodyStr);
    $ts       = (string) time();
    $nonce    = bin2hex(random_bytes(16));
    $signInput = "POST\n{$path}\n\n{$ts}\n{$nonce}\n{$bodyHash}";
    $sig = hash_hmac('sha256', $signInput, BRAND_SECRET);

    $headers = [
        "X-App-Id: " . BRAND_APP_ID,
        "X-Timestamp: $ts",
        "X-Nonce: $nonce",
        "X-Signature: $sig",
        "Content-Type: application/json",
    ];
    if ($idempotencyKey) $headers[] = "Idempotency-Key: $idempotencyKey";

    $retryAfter = null;
    $ch = curl_init(BRAND_BASE . $path);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $bodyStr,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
            if (stripos($line, 'Retry-After:') === 0) $retryAfter = (int) trim(substr($line, 12));
            return strlen($line);
        },
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $httpStatus = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    if ($resp === false) throw new RuntimeException("HTTP error: $err");

    $decoded = json_decode($resp, true);
    if (!is_array($decoded)) {
        // 不是我們的 JSON 包絡(如代理層錯誤頁)
        throw new OpenAPIException('invalid JSON response', $httpStatus, null, null, $retryAfter);
    }
    // 大部分業務錯誤的 HTTP 狀態碼是 200——判斷 code,不要看 HTTP 狀態碼
    if (($decoded['code'] ?? null) !== 0) {
        throw new OpenAPIException((string) ($decoded['message'] ?? ''), $httpStatus,
            $decoded['code'] ?? null, $decoded['error_key'] ?? null, $retryAfter);
    }
    return $decoded['data'] ?? [];
}

function verifyWebhook(string $sigHeader, string $tsHeader, string $rawBody, string $webhookSecret): bool {
    if (strpos($sigHeader, 'v1,') !== 0) return false;
    $sig = substr($sigHeader, 3);
    $expected = hash_hmac('sha256', $tsHeader . '.' . $rawBody, $webhookSecret);
    return hash_equals($sig, $expected);
}

使用示例 ​

php
<?php
require_once 'brand.php';

// 1. 列卡頭
$data = callOpenAPI('/api/v1/openapi/card_headers/list', ['page' => 1, 'page_size' => 20]);
$headerId = $data['list'][0]['header_id'];

// 2. 列卡配置
$data = callOpenAPI('/api/v1/openapi/card_configs/list', ['header_id' => $headerId]);
$packageId = $data['list'][0]['package_id'];

// 3. 申請虛擬卡(帶冪等鍵)
function uuidv4(): string {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

$data = callOpenAPI('/api/v1/openapi/card/apply', [
    'header_id'     => $headerId,
    'package_id'    => $packageId,
    'cardholder_id' => 'chd_1024',
], uuidv4());
$cardId = $data['card_id'];
echo "Created card: $cardId\n";

// 4. 卡啟用後(card.opened webhook / status 2)建立充值。
//    amount 的單位是套餐的充值資產(如 USDT)。
$idempotencyKey = uuidv4(); // 重試時必須複用同一個 key
try {
    $data = callOpenAPI('/api/v1/openapi/card/recharge', [
        'card_id' => $cardId,
        'amount'  => '100.00',
    ], $idempotencyKey);
    echo "Transaction: {$data['transaction_id']} ({$data['status_desc']})\n"; // processing → 等待 webhook
} catch (OpenAPIException $e) {
    if ($e->apiCode === 40100) {
        // HTTP 401 openapi_invalid_credentials:檢查 APP_ID / SECRET / 時鐘——重試無效
        throw $e;
    } elseif ($e->apiCode === 42900) {
        // HTTP 429 too_many_requests:等待 Retry-After 秒後用同一個 key 重試
        sleep($e->retryAfter ?: 60);
    } elseif ($e->errorKey === 'insufficient_balance') {
        echo "請先為錢包儲值\n";
    } else {
        throw $e;
    }
}

判斷 code,不要看 HTTP 狀態碼

成功是 "code": 0。大部分業務錯誤(40000、40001、50000)的 HTTP 狀態碼是 200,因此 callOpenAPI() 只要 code 非 0 就視為錯誤,再依 errorKey(40100 / 42900 看 apiCode)分支處理。

Webhook 接收(原生 PHP) ​

php
<?php
// webhook.php — 配置為某個 URL 的入口
require_once 'brand.php';

$rawBody = file_get_contents('php://input');
$sig = $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '';
$ts  = $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '';
$eventId = $_SERVER['HTTP_WEBHOOK_ID'] ?? '';
$eventType = $_SERVER['HTTP_WEBHOOK_TYPE'] ?? '';

$webhookSecret = getenv('BRAND_WEBHOOK_SECRET');

if (!verifyWebhook($sig, $ts, $rawBody, $webhookSecret)) {
    http_response_code(401);
    exit('invalid signature');
}

if (abs(time() - intval($ts)) > 300) {
    http_response_code(401);
    exit('timestamp expired');
}

if (alreadyProcessed($eventId)) {
    http_response_code(200);
    exit;
}

$payload = json_decode($rawBody, true);
enqueue($eventType, $payload);  // 重活丟佇列
markProcessed($eventId);

http_response_code(200);
echo 'ok';

Webhook 接收(Laravel) ​

php
<?php
// routes/web.php
Route::post('/webhook', [WebhookController::class, 'handle']);

// app/Http/Controllers/WebhookController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WebhookController extends Controller {
    public function handle(Request $request) {
        $rawBody = $request->getContent();
        $sig = $request->header('Webhook-Signature', '');
        $ts  = $request->header('Webhook-Timestamp', '');

        if (!verifyWebhook($sig, $ts, $rawBody, env('BRAND_WEBHOOK_SECRET'))) {
            abort(401, 'invalid signature');
        }
        if (abs(time() - intval($ts)) > 300) {
            abort(401, 'timestamp expired');
        }

        $eventId = $request->header('Webhook-Id');
        if (\Cache::has("webhook:$eventId")) return response()->noContent();

        ProcessWebhook::dispatch($request->header('Webhook-Type'), json_decode($rawBody, true));
        \Cache::put("webhook:$eventId", true, now()->addDays(7));

        return response()->noContent();
    }
}

注意事項 ​

  • JSON_UNESCAPED_UNICODE 讓中文不轉義成 \uXXXX,與伺服器期望一致
  • 用 hash_equals 而非 === 比較簽名(防 timing attack)
  • Laravel 預設會讀兩次 php://input 失敗 —— 用 $request->getContent()

採用 MIT 等價條款釋出