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()