# 只计算签名(自检) */ /** 计算请求签名(纯函数,不读取时钟和随机数,方便和服务端对照) */ function yours_open_sign(string $signKey, string $method, string $path, string $timestamp, string $nonce, string $body): string { $stringToSign = strtoupper($method) . "\n" . $path . "\n" . $timestamp . "\n" . $nonce . "\n" . hash('sha256', $body); return hash_hmac('sha256', $stringToSign, $signKey); } final class YoursOpenClient { /** token 到期前多少秒就重新获取 */ private const TOKEN_REFRESH_MARGIN = 300; /** token 无效或过期 */ private const CODE_TOKEN_INVALID = 40102; /** @var string */ private $baseUrl; /** @var string */ private $appid; /** @var string */ private $secret; /** @var string */ private $signKey; /** @var int */ private $timeout; /** @var string */ private $token = ''; /** @var int */ private $tokenExpiresAt = 0; /** * @param string $baseUrl 只写协议和域名(可带端口),不要带 /v1,例如 https://open-api.yours.xyz */ public function __construct(string $baseUrl, string $appid, string $secret, string $signKey, int $timeout = 10) { $this->baseUrl = rtrim($baseUrl, '/'); $this->appid = $appid; $this->secret = $secret; $this->signKey = $signKey; $this->timeout = $timeout; } /** * 获取 access_token。有效期内复用;每天获取次数有限,生产环境请在多个进程之间共享缓存。 */ public function token(bool $forceRefresh = false): string { if (!$forceRefresh && $this->token !== '' && time() < $this->tokenExpiresAt) { return $this->token; } $body = $this->encodeJson(['appid' => $this->appid, 'secret' => $this->secret, 'grant_type' => 'client_credential']); $res = $this->send('POST', $this->baseUrl . '/oauth/token', $body, ['Content-Type: application/json']); if (($res['code'] ?? null) !== 0) { throw new RuntimeException(self::describeError('获取 token 失败', $res)); } $this->token = (string) $res['data']['access_token']; $this->tokenExpiresAt = time() + max(0, (int) $res['data']['expires_in'] - self::TOKEN_REFRESH_MARGIN); return $this->token; } /** * 调用开放接口,返回解析后的响应 {code, msg, data, request_id}(业务错误不抛异常,由调用方判断 code)。 * * @param string $path 以 / 开头、已经 URL 编码的路径,例如 /v1/tickets;查询参数放在 $query 里 * @param array $query 查询参数(不参与签名) * @param array|null $body 请求体,会编码成 JSON;null 表示不带请求体 * @param bool $sign 是否签名。写接口(*.write)必须签名;读接口签了也没有影响 * @return array */ public function request(string $method, string $path, array $query = [], ?array $body = null, bool $sign = true): array { if ($path === '' || $path[0] !== '/' || strpbrk($path, '?#') !== false) { throw new InvalidArgumentException('path 必须以 / 开头,且不能包含查询参数'); } $method = strtoupper($method); if ($body !== null && in_array($method, ['GET', 'HEAD'], true)) { throw new InvalidArgumentException('GET / HEAD 请求不能带请求体(签名包含请求体,但不会被发送)'); } $raw = $body === null ? '' : $this->encodeJson($body); $url = $this->baseUrl . $path . ($query === [] ? '' : '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986)); $res = $this->sendApi($method, $path, $url, $raw, $sign, false); if (($res['code'] ?? null) === self::CODE_TOKEN_INVALID) { // token 被吊销或过期:重新获取一次再试(每次请求都会生成新的 nonce) $res = $this->sendApi($method, $path, $url, $raw, $sign, true); } return $res; } /** @return array */ private function sendApi(string $method, string $path, string $url, string $raw, bool $sign, bool $refreshToken): array { $headers = ['Authorization: Bearer ' . $this->token($refreshToken)]; if ($raw !== '') { $headers[] = 'Content-Type: application/json'; } if ($sign) { $timestamp = (string) time(); $nonce = bin2hex(random_bytes(16)); $headers[] = 'X-Timestamp: ' . $timestamp; $headers[] = 'X-Nonce: ' . $nonce; // 签的必须是下面实际发送的 $raw,不能重新编码一次 $headers[] = 'X-Sign: ' . yours_open_sign($this->signKey, $method, $path, $timestamp, $nonce, $raw); } return $this->send($method, $url, $raw, $headers); } /** @return array */ private function send(string $method, string $url, string $body, array $headers): array { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_HTTPHEADER => $headers, ]); if ($method !== 'GET' && $method !== 'HEAD') { curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // 空字符串也设置,确保带上 Content-Length: 0 } $raw = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $error = curl_error($ch); curl_close($ch); if ($raw === false) { throw new RuntimeException("请求失败:{$error}"); } $json = json_decode((string) $raw, true); if (!is_array($json) || !array_key_exists('code', $json)) { throw new RuntimeException("响应不是开放平台格式(HTTP {$status})"); } return $json; } private function encodeJson(array $data): string { // 顶层空数组编码成 {}(请求体应为 JSON 对象)。嵌套的空对象请传 new \stdClass(),空数组 [] 会编码成 JSON 数组 return $data === [] ? '{}' : json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); } /** @param array $res */ public static function describeError(string $title, array $res): string { return sprintf('%s:code=%s msg=%s request_id=%s', $title, $res['code'] ?? '-', $res['msg'] ?? '-', $res['request_id'] ?? '-'); } } /** 演示:获取 token → 查询门店 → 现场取号。需要应用拥有 store.read 和 ticket.write 权限 */ function yours_open_demo(): int { $config = []; foreach (['OPEN_BASE_URL', 'OPEN_APPID', 'OPEN_SECRET', 'OPEN_SIGN_KEY'] as $name) { $config[$name] = (string) getenv($name); if ($config[$name] === '') { fwrite(STDERR, "请设置环境变量 {$name}\n"); return 2; } } $client = new YoursOpenClient($config['OPEN_BASE_URL'], $config['OPEN_APPID'], $config['OPEN_SECRET'], $config['OPEN_SIGN_KEY']); try { $client->token(); echo "获取 token 成功\n"; $stores = $client->request('GET', '/v1/stores'); if ($stores['code'] !== 0 || empty($stores['data']['items'])) { fwrite(STDERR, YoursOpenClient::describeError('查询门店失败', $stores) . "\n"); return 1; } $store = $stores['data']['items'][0]; echo "门店:store_id={$store['store_id']} name={$store['name']}\n"; // out_ticket_no 是你自己的单号(幂等键):超时重试时必须使用同一个单号 $outTicketNo = 'DEMO' . date('YmdHis') . bin2hex(random_bytes(3)); $ticket = $client->request('POST', '/v1/tickets', [], [ 'out_ticket_no' => $outTicketNo, 'store_id' => $store['store_id'], 'user' => ['open_user_id' => 'demo_user_1', 'mobile' => '13800000000', 'name' => '张三'], ]); if ($ticket['code'] !== 0) { fwrite(STDERR, YoursOpenClient::describeError('取号失败', $ticket) . "\n"); return 1; } $data = $ticket['data']; echo "取号成功:ticket_id={$data['ticket_id']} number={$data['number']} status={$data['status']} ahead_count={$data['ahead_count']}\n"; return 0; } catch (Throwable $e) { fwrite(STDERR, $e->getMessage() . "\n"); return 1; } } if (PHP_SAPI === 'cli' && isset($argv) && realpath($argv[0]) === __FILE__) { if (($argv[1] ?? '') === 'sign') { if (count($argv) !== 8) { fwrite(STDERR, "用法:php client.php sign \n"); exit(2); } [, , $key, $method, $path, $timestamp, $nonce, $bodyFile] = $argv; if ($key === '-') { // 从环境变量读取,避免 sign_key 出现在 shell 历史和进程列表里 $key = (string) getenv('OPEN_SIGN_KEY'); } $body = file_get_contents($bodyFile); if ($body === false) { fwrite(STDERR, "无法读取 {$bodyFile}\n"); exit(2); } echo yours_open_sign($key, $method, $path, $timestamp, $nonce, $body), "\n"; exit(0); } exit(yours_open_demo()); }