Skip to content

PHP ​

Compatibility

PHP 7.4+. Only depends on the curl extension (enabled by default).

Client Implementation ​

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

// Thrown for every response whose `code` is not 0
class OpenAPIException extends RuntimeException {
    public int $httpStatus;
    public ?int $apiCode;      // business code: 40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
    public ?string $errorKey;  // stable machine key — branch on this, never on the message
    public ?int $retryAfter;   // Retry-After header in seconds (set on 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;
    }
}

// Returns `data` when code === 0, throws OpenAPIException otherwise
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)) {
        // Not our JSON envelope (e.g. a proxy error page)
        throw new OpenAPIException('invalid JSON response', $httpStatus, null, null, $retryAfter);
    }
    // Most business errors arrive with HTTP 200 — check `code`, not the HTTP status
    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);
}

Usage ​

php
<?php
require_once 'brand.php';

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

// 2. List card configs
$data = callOpenAPI('/api/v1/openapi/card_configs/list', ['header_id' => $headerId]);
$packageId = $data['list'][0]['package_id'];

// 3. Apply virtual card
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. Once the card is active (card.opened webhook / status 2), create a recharge.
//    `amount` is in the package's recharge asset (e.g. USDT).
$idempotencyKey = uuidv4(); // reuse the SAME key when retrying
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 → wait for webhook
} catch (OpenAPIException $e) {
    if ($e->apiCode === 40100) {
        // HTTP 401 openapi_invalid_credentials: check APP_ID / SECRET / clock — retrying won't help
        throw $e;
    } elseif ($e->apiCode === 42900) {
        // HTTP 429 too_many_requests: wait Retry-After seconds, then retry with the same key
        sleep($e->retryAfter ?: 60);
    } elseif ($e->errorKey === 'insufficient_balance') {
        echo "Top up your wallet first\n";
    } else {
        throw $e;
    }
}

Check code, not the HTTP status

Success is "code": 0. Most business errors (40000, 40001, 50000) come back with HTTP 200, so callOpenAPI() treats any non-zero code as an error and you branch on errorKey (plus apiCode for 40100 / 42900).

Webhook Receiver (Plain PHP) ​

php
<?php
// webhook.php — point your URL here
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 Receiver (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();
    }
}

Notes ​

  • JSON_UNESCAPED_UNICODE keeps non-ASCII characters as-is (not \uXXXX), matching the server's expectation
  • Use hash_equals for signature comparison, not === (timing-attack safe)
  • Laravel's default request body parsing reads php://input once — use $request->getContent() instead

Released under MIT-equivalent terms.