scene('order-done'); // null = 该场景没配码 → 隐藏展示位 * $way = $qr->memberWay('member-center', 1479); // 会员一人一码(首次约 1-2s) * $st = $qr->memberStatus(1479); // ['bound'=>false] 或 ['bound'=>true, ...] */ final class SidianQrClient { /** 与服务端时差上限(秒),超出直接 40103,重试没用,必须校准时钟 */ private const TS_TOLERANCE = 300; private string $baseUrl; private string $appId; private string $secret; private int $timeout; private int $connectTimeout; /** @var callable|null fn(string $key): mixed */ private $cacheGet = null; /** @var callable|null fn(string $key, mixed $value, int $ttl): void */ private $cacheSet = null; public function __construct( string $baseUrl, string $appId, string $secret, int $timeout = 5, int $connectTimeout = 2 ) { $this->baseUrl = rtrim($baseUrl, '/'); $this->appId = $appId; $this->secret = $secret; $this->timeout = $timeout; $this->connectTimeout = $connectTimeout; } /** * 接入缓存(可选)。POS 侧一般用 Redis / ThinkPHP Cache: * $qr->withCache( * fn($k) => Cache::get($k), * fn($k, $v, $ttl) => Cache::set($k, $v, $ttl) * ); * 不给就不缓存,每次都打 SCRM(收银高峰期会被打穿,建议一定要给)。 */ public function withCache(callable $get, callable $set): self { $this->cacheGet = $get; $this->cacheSet = $set; return $this; } // ── 对外接口 ──────────────────────────────────────────────────── /** * 场景码:收银台/会员中心/下单完成等固定场景的加微活码。 * * GET /api/pos/contactways?scene_key=order-done * * @return array{way_id:int,title:string,qr_code:string,skip_verify:bool}|null * null = 该场景未配置码(**正常返回,不是错误**,前端隐藏展示位即可) */ public function scene(string $sceneKey): ?array { $cacheKey = 'sidian:qr:scene:' . $this->appId . ':' . $sceneKey; if ($hit = $this->cacheRead($cacheKey)) { return $hit === '__null__' ? null : $hit; } $data = $this->get('api/pos/contactways', ['scene_key' => $sceneKey]); $way = $this->normalizeWay($data['way'] ?? null); $this->cacheWrite($cacheKey, $way ?? '__null__', $way === null ? 60 : 600); return $way; } /** * 会员专属码(一人一码,扫码即归因到该会员)。 * * GET /api/pos/member-way?scene_key=member-center&pos_member_id=1479 * * 🔴 首次调用会在 SCRM 侧实时调企微建码,可能 1-2 秒;超时不要立刻报错, * 当次可先用 scene() 的共享码顶上,下一屏再换成专属码。 * 🔴 服务端有 5000 条/企业 的护栏,超了会静默回落共享码 —— 返回的 way_id * 与基础场景码相同就说明回落了,归因能力降级但展示不受影响。 * * @return array{way_id:int,title:string,qr_code:string,skip_verify:bool}|null */ public function memberWay(string $sceneKey, int $posMemberId, bool $allowSlow = true): ?array { if ($posMemberId <= 0) { return null; } $cacheKey = 'sidian:qr:member:' . $this->appId . ':' . $sceneKey . ':' . $posMemberId; if ($hit = $this->cacheRead($cacheKey)) { return $hit === '__null__' ? null : $hit; } $data = $this->get( 'api/pos/member-way', ['scene_key' => $sceneKey, 'pos_member_id' => $posMemberId], $allowSlow ? max($this->timeout, 8) : $this->timeout ); $way = $this->normalizeWay($data['way'] ?? null); $this->cacheWrite($cacheKey, $way ?? '__null__', $way === null ? 60 : 1800); return $way; } /** * 会员加微状态:已加上就不要再推码。 * * GET /api/pos/member-status?pos_member_id=1479 * * @return array{bound:bool,bound_at?:string,guide_key?:string,owner_name?:string} */ public function memberStatus(int $posMemberId): array { if ($posMemberId <= 0) { return ['bound' => false]; } $data = $this->get('api/pos/member-status', ['pos_member_id' => $posMemberId]); return [ 'bound' => (bool) ($data['bound'] ?? false), 'bound_at' => (string) ($data['bound_at_text'] ?? ''), 'guide_key' => (string) ($data['guide_key'] ?? ''), 'owner_name' => (string) ($data['owner_name'] ?? ''), ]; } /** * 分佣归因增量(选配):pos_member_id → guide_key。 * * GET /api/pos/member-bindings?updated_since={ts} * * @return array{bindings:array,next_since:int,has_more:bool} */ public function bindings(int $updatedSince = 0): array { $data = $this->get('api/pos/member-bindings', ['updated_since' => $updatedSince]); return [ 'bindings' => (array) ($data['bindings'] ?? []), 'next_since' => (int) ($data['next_since'] ?? 0), 'has_more' => (bool) ($data['has_more'] ?? false), ]; } // ── 底层:签名与请求 ──────────────────────────────────────────── /** * @param array $query * @return array */ private function get(string $pathinfo, array $query = [], ?int $timeout = null): array { $pathinfo = trim($pathinfo, '/'); // 🔴 无前后斜杠 $queryString = http_build_query($query); $url = $this->baseUrl . '/' . $pathinfo . ($queryString !== '' ? '?' . $queryString : ''); $ts = (string) time(); $nonce = bin2hex(random_bytes(16)); // 24h 内不可重复 // 🔴 签名串用的 pathinfo 不含 query;GET 的 body 段是空串 $signString = implode("\n", ['GET', $pathinfo, $ts, $nonce, '']); $signature = hash_hmac('sha256', $signString, $this->secret); $headers = [ 'X-POS-App-Id: ' . $this->appId, 'X-POS-Timestamp: ' . $ts, 'X-POS-Nonce: ' . $nonce, 'X-POS-Signature: ' . $signature, 'Accept: application/json', ]; $raw = $this->curl($url, $headers, $timeout ?? $this->timeout); $json = json_decode($raw, true); if (!is_array($json)) { throw new SidianQrException('SCRM 返回非 JSON(检查域名/nginx 是否返回了 HTML 错误页)', -1, 0, $raw); } $error = (int) ($json['error'] ?? 0); if ($error !== 0) { $msg = (string) ($json['error_msg'] ?? $json['message'] ?? '未知错误'); throw new SidianQrException($msg, $error, 0, $raw); } return $json; } private function curl(string $url, array $headers, int $timeout): string { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPGET => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_CONNECTTIMEOUT => $this->connectTimeout, CURLOPT_TIMEOUT => $timeout, // SCRM 生产在 nginx 后,跟随一次跳转(尾斜杠会 301,body/query 会丢) CURLOPT_FOLLOWLOCATION => false, ]); $body = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $err = curl_error($ch); curl_close($ch); if ($status === 301 || $status === 302) { throw new SidianQrException('被 301/302 重定向(路径带尾斜杠或域名跳转),请去掉尾部斜杠', -2, $status, ''); } if ($body === false || $status === 0) { throw new SidianQrException('网络失败:' . $err, -3, 0, ''); } if ($status !== 200) { // 401 的 body 是 {error:401xx,message:...},交给上层解析错误码 $decoded = json_decode((string) $body, true); if (is_array($decoded) && isset($decoded['error'])) { throw new SidianQrException((string) ($decoded['message'] ?? '鉴权失败'), (int) $decoded['error'], $status, (string) $body); } throw new SidianQrException('HTTP ' . $status, -4, $status, (string) $body); } return (string) $body; } /** * 归一化 way:只保留 POS 需要展示的四个字段。 * 🔴 way:null 是正常返回值(未配置场景码),别当异常抛。 */ private function normalizeWay(mixed $way): ?array { if (!is_array($way) || empty($way['qr_code'])) { return null; } return [ 'way_id' => (int) ($way['way_id'] ?? 0), 'title' => (string) ($way['title'] ?? ''), 'qr_code' => (string) $way['qr_code'], 'skip_verify' => (bool) ($way['skip_verify'] ?? false), // 展示用(已是北京时间,直接显示,不要再转一次) 'updated_at_text' => (string) ($way['updated_at_text'] ?? ''), ]; } private function cacheRead(string $key): mixed { if ($this->cacheGet === null) { return null; } try { return ($this->cacheGet)($key); } catch (\Throwable) { return null; // 缓存挂了不影响主流程 } } private function cacheWrite(string $key, mixed $value, int $ttl): void { if ($this->cacheSet === null) { return; } try { ($this->cacheSet)($key, $value, $ttl); } catch (\Throwable) { // 同上 } } } /** * SDK 异常。errorCode 与 SCRM 文档错误码一致(401xx / 4001 ...)。 */ final class SidianQrException extends \RuntimeException { public int $errorCode; public int $httpStatus; public string $rawBody; public function __construct(string $message, int $errorCode = 0, int $httpStatus = 0, string $rawBody = '') { parent::__construct($message); $this->errorCode = $errorCode; $this->httpStatus = $httpStatus; $this->rawBody = $rawBody; } /** 网络/签名类错误可以重试吗:只有 5xx 与网络失败值得重试,签名错重试只会烧 nonce */ public function retryable(): bool { return $this->errorCode === -3 || $this->httpStatus >= 500; } }