Files
zyt/server/tests/EsignClientTest.php
T
2026-11-20 10:30:04 +08:00

405 lines
28 KiB
PHP

<?php
declare(strict_types=1);
// Isolated adapter tests: no ThinkPHP bootstrap, credentials, database or network.
require_once dirname(__DIR__) . '/app/common/service/esign/EsignClient.php';
use app\common\service\esign\EsignClient;
use app\common\service\esign\EsignOutcomeUnknownException;
use app\common\service\esign\EsignProviderException;
$checks = 0;
function esignExpect(bool $condition, string $label): void
{
global $checks;
++$checks;
if (!$condition) {
throw new RuntimeException('FAIL: ' . $label);
}
}
function esignThrows(callable $call, string $class, string $code): EsignProviderException
{
try {
$call();
} catch (EsignProviderException $exception) {
esignExpect(get_class($exception) === $class, 'exception type ' . $code);
esignExpect($exception->providerCode === $code, 'exception code ' . $code);
esignExpect($exception->getPrevious() === null, 'no sensitive previous exception');
return $exception;
}
throw new RuntimeException('Expected exception: ' . $code);
}
function esignConfig(array $overrides = []): array
{
return array_replace([
'enabled' => true, 'environment' => 'sandbox', 'app_id' => 'test-app', 'app_secret' => 'test-secret',
'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service', 'timeout' => 45,
], $overrides);
}
function esignResponse(array $data, int $status = 200): array
{
return ['status' => $status, 'body' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
}
/** @return array<string,array{headers:string,body:string}> */
function esignMultipartParts(array $request): array
{
$contentType = $request['headers']['Content-Type'];
esignExpect(str_starts_with($contentType, 'multipart/form-data; boundary='), 'multipart envelope');
$boundary = substr($contentType, strlen('multipart/form-data; boundary='));
$parts = [];
foreach (explode('--' . $boundary, $request['body']) as $part) {
if (!str_contains($part, "\r\n\r\n")) {
continue;
}
[$headers, $body] = explode("\r\n\r\n", ltrim($part, "\r\n"), 2);
preg_match('/name="([^"]+)"/', $headers, $matches);
$parts[$matches[1]] = ['headers' => $headers, 'body' => substr($body, 0, -2)];
}
return $parts;
}
$requests = [];
$responses = [];
$transport = static function (array $request) use (&$requests, &$responses): array {
$requests[] = $request;
if ($responses === []) {
throw new RuntimeException('No fake response');
}
return array_shift($responses);
};
$clock = static fn (): int => 1800000000000;
$client = new EsignClient(esignConfig(), $transport, $clock);
esignExpect($client->isEnabled() && $client->environment() === 'sandbox', 'configured environment');
$client->assertConfigured();
foreach ([
[['enabled' => 'false'], 'DISABLED'],
[['environment' => 'prod'], 'ENVIRONMENT_INVALID'],
[['app_secret' => ''], 'CREDENTIALS_MISSING'],
[['app_id' => "app\r\nInjected:yes"], 'CREDENTIALS_MISSING'],
[['timeout' => 0], 'TIMEOUT_INVALID'],
[['timeout' => 301], 'TIMEOUT_INVALID'],
[['sdk_url' => 'http://example.com/paas-sdk-service'], 'SDK_HTTP_REQUIRES_PRIVATE_HOST'],
[['sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service?x=1'], 'SDK_URL_INVALID'],
[['sdk_url' => 'https://user:pass@example.com/paas-sdk-service'], 'SDK_URL_INVALID'],
[['sdk_url' => 'file:///tmp/paas-sdk-service'], 'SDK_URL_INVALID'],
] as [$config, $code]) {
esignThrows(fn () => (new EsignClient(esignConfig($config), $transport, $clock))->assertConfigured(), EsignProviderException::class, $code);
}
esignExpect($requests === [], 'configuration failures issue no request');
$responses[] = esignResponse(['errCode' => 0]);
$client->initialize();
$init = json_decode($requests[0]['body'], true);
esignExpect($requests[0]['url'] === 'http://127.0.0.1:8091/paas-sdk-service/timevale/init', 'SDK init endpoint');
esignExpect($init['projectConfig'] === [
'projectId' => 'test-app', 'projectSecret' => 'test-secret',
'itsmApiUrl' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
], 'sandbox initialization parameters');
esignExpect($init['httpConfig'] === ['httpType' => 'HTTPS', 'retry' => 0], 'SDK internal retry disabled');
esignExpect($init['signConfig']['algorithm'] === 'HMACSHA256', 'SDK algorithm');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'shortLink' => 'https://smlt.esign.cn/identity7']]);
$identity = $client->startIdentity('张医生', 'rx-7', 'sdk-account-1');
$request = $requests[count($requests) - 1];
$body = json_decode($request['body'], true);
esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.esign.cn/identity7'], 'identity result');
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl', 'independent v2 identity API');
esignExpect($body['indivInfo']['sdkAccountId'] === 'sdk-account-1' && !isset($body['sdkAccountId']), 'SDK account nested in indivInfo');
esignExpect($body['configParams']['indivUneditableInfo'] === ['name', 'certType'], 'doctor name locked');
esignExpect($body['usageType'] === 'CERTAPPLY', 'identity requests certificate agreement and issuance for signing');
esignExpect($body['authType'] === 'PSN_TELECOM_AUTHCODE'
&& $body['availableAuthTypes'] === ['PSN_TELECOM_AUTHCODE'], 'embedded identity uses mobile authentication without external face apps');
// Fixed vectors independently calculated with Python hashlib/hmac; UTF-8 bytes must match exactly.
esignExpect($request['headers']['Content-MD5'] === 'j/xD3VTZtMlQ9HftwFK6Cg==', 'POST content MD5 vector');
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'oMBDY2WjbOSJrIhQbxtsf9EgX/iYzf6NoP60AtqGEI4=', 'POST HMACSHA256 vector');
esignExpect($request['headers']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds');
esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'status' => 'SUCCESS']]);
esignExpect($client->identityDetail('flow-7')['status'] === 'SUCCESS', 'identity official data returned');
$request = $requests[count($requests) - 1];
esignExpect($request['method'] === 'GET' && $request['body'] === '' && !isset($request['headers']['Content-MD5']), 'GET no body MD5');
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'wPILAWFFD+SOKXrMxguRUqiG1Iwl+k/X9O9Fukf7hes=', 'GET HMACSHA256 vector');
$valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $clock() + 1000];
$responses[] = esignResponse($valid);
$client->checkWillingness('flow-7');
esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint');
$responses[] = esignResponse($valid);
esignExpect($client->willingnessExpiresAt('flow-7') === $valid['expireAt'], 'valid authorization returns its Unix millisecond expiry');
$responses[] = esignResponse(array_replace($valid, ['remainingTimes' => 2]));
esignExpect($client->willingnessValidity('flow-7') === [
'state' => 'valid', 'expires_at' => $valid['expireAt'], 'remaining_times' => 2,
], 'valid authorization exposes the provider count');
$responses[] = esignResponse(array_replace($valid, ['status' => 0, 'remainingTimes' => 0]));
esignExpect($client->willingnessValidity('flow-7')['state'] === 'exhausted',
'provider returns exhausted even when the expiration is still in the future');
foreach ([['status' => 0], ['remainingTimes' => 0], ['expireAt' => $clock()], ['status' => '1'], ['expireAt' => 'not-a-date']] as $invalid) {
$responses[] = esignResponse(array_replace($valid, $invalid));
esignThrows(fn () => $client->checkWillingness('flow-7'), EsignProviderException::class, 'WILLINGNESS_INVALID');
}
$responses[] = esignResponse(['errCode' => 0, 'accountId' => 'person-7']);
esignExpect($client->createPerson('张医生', 'TEST-IDENTITY', 'flow-7') === 'person-7', 'created SDK account');
$request = $requests[count($requests) - 1];
esignExpect(str_ends_with($request['url'], '/timevale/account/addPerson'), 'account SDK endpoint');
esignExpect(json_decode($request['body'], true) === ['name' => '张医生', 'idNo' => 'TEST-IDENTITY', 'idNoType' => 'MAINLAND', 'identityAuthId' => 'flow-7'], 'identity bound to SDK account');
$privateIdentity = '110101199001011237'; // Synthetic fixture, never sent over a network.
$responses[] = esignResponse(['errCode' => 9001, 'msg' => 'mismatch ' . $privateIdentity, 'idNo' => $privateIdentity]);
$before = count($requests);
$bindingError = esignThrows(fn () => $client->createPerson('张医生', $privateIdentity, 'flow-7'), EsignProviderException::class, 'PROVIDER_9001');
esignExpect(!str_contains($bindingError->getMessage(), $privateIdentity), 'SDK binding error cannot echo supplemental number');
esignExpect(count($requests) === $before + 1, 'SDK binding is never automatically retried');
$responses[] = esignResponse(['errCode' => 0, 'sealData' => base64_encode('seal-image')]);
esignExpect($client->createSeal('person-7') === base64_encode('seal-image'), 'seal result');
$sealBody = json_decode($requests[count($requests) - 1]['body'], true);
esignExpect($sealBody === ['accountId' => 'person-7', 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE'], 'seal from account identity');
$pdf = "%PDF-1.7\n\x00\x01binary-pdf\r\n%%EOF";
$signedPdf = "%PDF-1.7\nsigned\x00binary\n%%EOF";
$responses[] = esignResponse(['errCode' => 0, 'signServiceId' => 'service-7', 'stream' => base64_encode($signedPdf)]);
esignExpect($client->signPdf('person-7', 'flow-7', base64_encode('seal-image'), $pdf, 'rx-7.pdf') === ['sign_service_id' => 'service-7', 'pdf' => $signedPdf], 'decoded signed PDF bytes');
$request = $requests[count($requests) - 1];
esignExpect(str_ends_with($request['url'], '/timevale/user/sign/personSign'), 'SDK person sign endpoint');
$parts = esignMultipartParts($request);
esignExpect(array_keys($parts) === ['personSignParam', 'streamFile'], 'multipart field names');
esignExpect(str_contains($parts['personSignParam']['headers'], 'Content-Type: application/json; charset=UTF-8'), 'JSON part media type');
esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: application/octet-stream'), 'file part media type');
esignExpect($parts['streamFile']['body'] === $pdf, 'multipart preserves arbitrary binary bytes');
$parameters = json_decode($parts['personSignParam']['body'], true);
esignExpect($parameters['fileBean'] === ['fileName' => 'rx-7.pdf'] && !isset($parameters['fileBean']['dstPdfFile']), 'stream response requested');
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 520, 'posY' => 108, 'width' => 48]], 'compact first-page prescription signature');
esignExpect($parameters['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding');
$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]];
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $signatures]);
esignExpect($client->verifyPdf($signedPdf) === ['signatures' => $signatures], 'all signatures verified');
$parts = esignMultipartParts($requests[count($requests) - 1]);
esignExpect(isset($parts['verifyPdfParam']) && $parts['streamFile']['body'] === $signedPdf, 'verify multipart');
foreach ([[], [['signature' => ['validate' => true]], ['signature' => ['validate' => false]]], [['signature' => ['validate' => 1]]], [['cert' => []]]] as $invalid) {
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $invalid]);
esignThrows(fn () => $client->verifyPdf($signedPdf), EsignProviderException::class, $invalid === [] ? 'NO_SIGNATURES' : 'SIGNATURE_INVALID');
}
foreach ([
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
[['status' => 200, 'body' => '<html>secret identity data</html>'], 'INVALID_JSON'],
[esignResponse(['msg' => 'private identity']), 'RESPONSE_INVALID'],
[esignResponse(['errCode' => 42, 'msg' => 'private name/id/secret']), 'PROVIDER_42'],
[['status' => 302, 'body' => 'Location: https://attacker.invalid'], 'HTTP_302'],
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
] as [$response, $code]) {
$responses[] = $response;
$before = count($requests);
$exception = esignThrows(fn () => $client->createSeal('person-7'), EsignProviderException::class, $code);
esignExpect(count($requests) === $before + 1, 'no retry ' . $code);
esignExpect(!str_contains($exception->getMessage(), 'private') && !str_contains($exception->getMessage(), 'secret') && !str_contains($exception->getMessage(), 'attacker'), 'sanitized error ' . $code);
}
foreach ([
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
[['status' => 502, 'body' => 'private server exception'], 'HTTP_502'],
[esignResponse(['errCode' => 0, 'signServiceId' => 'already-signed']), 'SIGNED_FILE_UNAVAILABLE'],
] as [$response, $code]) {
$responses[] = $response;
$before = count($requests);
$exception = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, $code);
esignExpect(count($requests) === $before + 1, 'unknown signing outcome is never retried');
if ($code === 'SIGNED_FILE_UNAVAILABLE') {
esignExpect($exception->signServiceId === 'already-signed', 'known sign reference retained');
}
}
$responses[] = esignResponse(['errCode' => 55, 'msg' => 'secret rejected identity']);
esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_55');
$responses[] = esignResponse(['errCode' => 10002, 'msg' => '签署次数不足 private supplier text']);
$beforeQuotaRejection = count($requests);
$quotaRejection = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_10002');
esignExpect(str_contains($quotaRejection->getMessage(), '签署次数不足') && !str_contains($quotaRejection->getMessage(), 'private'), 'signing quota provides fixed guidance without raw supplier text');
esignExpect(count($requests) === $beforeQuotaRejection + 1, 'signing quota error sends only one request');
$responses[] = esignResponse(['errCode' => 10002, 'msg' => 'duplicate local initialization']);
$initializationRejection = esignThrows(fn () => $client->initialize(), EsignProviderException::class, 'PROVIDER_10002');
esignExpect(!str_contains($initializationRejection->getMessage(), '签署次数不足'), 'initialization 10002 is not interpreted as a signing error');
$throwing = new EsignClient(esignConfig(), static function (): array { throw new RuntimeException('https://secret:password/private'); }, $clock);
esignThrows(fn () => $throwing->createSeal('person-7'), EsignProviderException::class, 'TRANSPORT_ERROR');
esignThrows(fn () => $throwing->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, 'TRANSPORT_ERROR');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://attacker.invalid/identity']]);
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://t.esign.cn/identity']]);
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => 'https://smlfront.esign.cn:8890/identity/login']]);
esignExpect($client->startIdentity('医生', 'rx')['auth_url'] === 'https://smlfront.esign.cn:8890/identity/login', 'official sandbox long URL port');
foreach (['https://smlfront.esign.cn:444/x', 'https://smlt.esign.cn:8890/x', 'https://smlt.esign.cn/a\\b'] as $invalidUrl) {
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => $invalidUrl]]);
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
}
$production = new EsignClient(esignConfig(['environment' => 'production']), $transport, $clock);
$responses[] = esignResponse(['errCode' => 0]);
$production->initialize();
$init = json_decode($requests[count($requests) - 1]['body'], true);
esignExpect($init['projectConfig']['itsmApiUrl'] === 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2', 'production init endpoint');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => '', 'url' => 'https://idverify.esign.cn/identity']]);
$production->startIdentity('医生', 'rx');
esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint');
$responses[] = esignResponse(['errCode' => 403, 'msg' => 'private supplied identity 11010519491231002X']);
$before403 = count($requests);
$forbidden = esignThrows(fn () => $client->createPerson('测试医生', '11010519491231002X', 'flow-403'), EsignProviderException::class, 'PROVIDER_403');
esignExpect(str_contains($forbidden->getMessage(), '接口权限及 IP 白名单'), 'account 403 supplies fixed actionable configuration guidance');
esignExpect(!str_contains($forbidden->getMessage(), '11010519491231002X') && !str_contains($forbidden->getMessage(), 'private'), '403 guidance never echoes provider identity data');
esignExpect(count($requests) === $before403 + 1, 'account 403 is not automatically retried');
esignExpect($forbidden->operation === 'createPerson' && $forbidden->reason === null, 'unknown 403 retains operation without guessing a cause');
$privateSuffix = ' idNo=11010519491231002X appSecret=private-secret-token name=私密测试医生';
foreach ([
['该应用无权调用此接口' . $privateSuffix, EsignProviderException::APPLICATION_ACCESS_DENIED, '应用的接口授权'],
['FORBIDDEN: IP地址不在白名单' . $privateSuffix, EsignProviderException::IP_WHITELIST_MISMATCH, '出口 IP'],
['IP 白名单校验失败' . $privateSuffix, EsignProviderException::IP_WHITELIST_MISMATCH, '出口 IP'],
['SignatureDoesNotMatch' . $privateSuffix, EsignProviderException::SIGNATURE_MISMATCH, '签名配置'],
['FORBIDDEN' . $privateSuffix, null, '接口权限及 IP 白名单'],
['未知供应商错误' . $privateSuffix, null, '接口权限及 IP 白名单'],
['IP 白名单信息' . $privateSuffix, null, '接口权限及 IP 白名单'],
['NotSignatureDoesNotMatch' . $privateSuffix, null, '接口权限及 IP 白名单'],
[['msg' => '该应用无权调用此接口' . $privateSuffix], null, '接口权限及 IP 白名单'],
[null, null, '接口权限及 IP 白名单'],
] as [$vendorMessage, $reason, $hint]) {
$responses[] = esignResponse(['errCode' => 403, 'msg' => $vendorMessage, 'idNo' => $privateIdentity]);
$before = count($requests);
$exception = esignThrows(fn () => $client->createPerson('测试医生', 'TEST-IDENTITY', 'flow-403'), EsignProviderException::class, 'PROVIDER_403');
esignExpect($exception->operation === 'createPerson' && $exception->reason === $reason, '403 reason is a recognized enum or null');
esignExpect(str_contains($exception->getMessage(), $hint), '403 reason supplies only fixed guidance');
foreach (['11010519491231002X', $privateIdentity, 'private-secret-token', '私密测试医生', '未知供应商错误'] as $privateValue) {
esignExpect(!str_contains($exception->getMessage(), $privateValue), '403 diagnostic omits provider payload');
}
esignExpect(count($requests) === $before + 1, 'classified 403 never retries');
}
$responses[] = esignResponse(['errCode' => 9001, 'msg' => '该应用无权调用此接口' . $privateSuffix]);
$exception = esignThrows(fn () => $client->createPerson('测试医生', 'TEST-IDENTITY', 'flow-other'), EsignProviderException::class, 'PROVIDER_9001');
esignExpect($exception->reason === null, '403 classification does not alter other provider errors');
$invalidReason = new EsignProviderException('createPerson', 'PROVIDER_403', $privateSuffix);
esignExpect($invalidReason->reason === null && !str_contains($invalidReason->getMessage(), 'private-secret-token'), 'exception rejects unrecognized reason values');
$account = [
'accountId' => 'person-7', 'name' => '测试医生', 'idNo' => $privateIdentity,
'idNoType' => 'MAINLAND', 'accountType' => 'PERSON',
];
$responses[] = esignResponse(['errCode' => 0, 'cert' => 'cert-contents'] + $account);
esignExpect($client->signingAccount('person-7') === $account, 'signing account returns only requested fields');
$request = $requests[array_key_last($requests)];
esignExpect(str_ends_with($request['url'], '/timevale/account/queryByAccountId')
&& json_decode($request['body'], true) === ['accountId' => 'person-7'], 'signing account SDK request');
foreach ([['idNo' => null], ['accountId' => 'other-person']] as $invalidAccount) {
$responses[] = esignResponse(['errCode' => 0] + $invalidAccount + $account);
esignThrows(fn () => $client->signingAccount('person-7'), EsignProviderException::class, 'RESPONSE_INVALID');
}
$certDates = ['startDate' => '2026-09-11 10:20:30', 'endDate' => '2027-09-11 10:20:30'];
$responses[] = esignResponse(['errCode' => 0, 'sn' => 'cert-serial', 'owner' => '测试医生'] + $certDates);
esignExpect($client->certificateValidity('person-7') === $certDates, 'certificate validity retains provider dates only');
$request = $requests[array_key_last($requests)];
esignExpect(str_ends_with($request['url'], '/timevale/user/cert/queryLatestAvailableCert')
&& json_decode($request['body'], true) === ['accountId' => 'person-7'], 'certificate validity SDK request');
$responses[] = esignResponse(['errCode' => 0, 'startDate' => $certDates['startDate']]);
esignThrows(fn () => $client->certificateValidity('person-7'), EsignProviderException::class, 'RESPONSE_INVALID');
$doctorIdentity = ['flowId' => 'doctor-enrollment-1', 'shortLink' => 'https://smlt.esign.cn/enrollment'];
foreach ([null, 'person-7'] as $accountId) {
$responses[] = esignResponse(['code' => 0, 'data' => $doctorIdentity]);
esignExpect($client->startDoctorIdentity('测试医生', 'doctor-context', '13800138000', $accountId)
=== ['flow_id' => 'doctor-enrollment-1', 'auth_url' => $doctorIdentity['shortLink']], 'doctor enrollment returns hosted URL');
$request = $requests[array_key_last($requests)];
$body = json_decode($request['body'], true);
$person = ['name' => '测试医生', 'certType' => 'INDIVIDUAL_CH_IDCARD', 'authMobileNo' => '13800138000'];
if ($accountId !== null) {
$person['sdkAccountId'] = $accountId;
}
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl'
&& $body === [
'indivInfo' => $person,
'usageType' => 'CERTAPPLY',
'authType' => 'PSN_FACEAUTH_BYURL_ZHIMA',
'availableAuthTypes' => ['PSN_FACEAUTH_BYURL_ZHIMA'],
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
'contextInfo' => ['contextId' => 'doctor-context', 'showResultPage' => true],
], 'enrollment requests certificate and authorizes mobile through Alipay face authentication');
}
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'enrollment', 'shortLink' => 'https://attacker.invalid/enrollment']]);
esignThrows(fn () => $client->startDoctorIdentity('测试医生', 'ctx', '13800138000'), EsignProviderException::class, 'AUTH_URL_INVALID');
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'quick-auth', 'shortLink' => 'https://smlt.esign.cn/quick']]);
esignExpect($client->startDoctorQuickAuthorization('测试医生', $privateIdentity, 'doctor-quicksign-ctx', 'person-7')
=== ['flow_id' => 'quick-auth', 'auth_url' => 'https://smlt.esign.cn/quick'], 'quickface authorization result stays limited to a flow and hosted URL');
$request = $requests[array_key_last($requests)];
$body = json_decode($request['body'], true);
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl'
&& $body['indivInfo'] === ['name' => '测试医生', 'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => $privateIdentity, 'sdkAccountId' => 'person-7']
&& $body['usageType'] === 'PUREVERIFY'
&& $body['availableAuthTypes'] === ['PSN_FACEAUTH_BYURL_ZHIMA']
&& $body['configParams']['indivUneditableInfo'] === ['name', 'certType', 'certNo']
&& $body['contextInfo']['contextId'] === 'doctor-quicksign-ctx', 'quick-sign face flow locks the bound identity and asks for no SMS credentials');
$willingnessEndpoint = 'https://smlopenapi.esign.cn/v2/identity/willingness/api/individual';
$doctorInfo = ['name' => '测试医生', 'idNo' => $privateIdentity, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
$responses[] = esignResponse(['code' => 0, 'data' => ['mobileNo' => '13800138000']]);
esignExpect($client->authorizedMobile('测试医生', $privateIdentity) === '13800138000', 'authorized phone returned as text');
$request = $requests[array_key_last($requests)];
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/get-individual-info'
&& json_decode($request['body'], true) === $doctorInfo, 'authorized phone read-only request');
foreach ([null, ['mobileNo' => null], ['mobileNo' => '']] as $unbound) {
$responses[] = esignResponse(['code' => 0, 'data' => $unbound]);
esignExpect($client->authorizedMobile('测试医生', $privateIdentity) === null, 'provider returned no phone binding');
}
foreach (['unexpected', ['mobileNo' => '138****8000'], ['mobileNo' => 13800138000]] as $malformed) {
$responses[] = esignResponse(['code' => 0, 'data' => $malformed]);
esignThrows(fn () => $client->authorizedMobile('测试医生', $privateIdentity), EsignProviderException::class, 'RESPONSE_INVALID');
}
foreach (['sms-flow-1', 'sms-flow-2'] as $smsFlow) {
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => $smsFlow]]);
esignExpect($client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000') === $smsFlow, 'new willingness flow from provider');
$request = $requests[array_key_last($requests)];
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/send-code'
&& json_decode($request['body'], true) === ['mobileNo' => '13800138000'] + $doctorInfo,
'SMS request for the authorized user');
}
$responses[] = esignResponse(['code' => 0, 'data' => null]);
esignThrows(fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000'), EsignProviderException::class, 'RESPONSE_INVALID');
$responses[] = esignResponse(['code' => 0, 'data' => null]);
$client->verifyWillingnessCode('sms/flow', '000123');
$request = $requests[array_key_last($requests)];
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/sms%2Fflow/verify-send-code'
&& json_decode($request['body'], true) === ['authCode' => '000123'], 'verification preserves leading zeroes and encodes the flow path');
$before = count($requests);
esignThrows(fn () => $client->startDoctorIdentity('测试医生', 'ctx', '138****8000'), EsignProviderException::class, 'INPUT_INVALID');
esignThrows(fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '+8613800138000'), EsignProviderException::class, 'INPUT_INVALID');
esignThrows(fn () => $client->verifyWillingnessCode('sms-flow-1', '12345'), EsignProviderException::class, 'INPUT_INVALID');
esignExpect(count($requests) === $before, 'invalid phone and code are rejected before provider requests');
foreach ([
['authorizedMobile', fn () => $client->authorizedMobile('测试医生', $privateIdentity), 30500101],
['sendWillingnessCode', fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000'), 30500101],
['verifyWillingnessCode', fn () => $client->verifyWillingnessCode('sms-flow-1', '000123'), 30503002],
] as [$operation, $call, $code]) {
$responses[] = esignResponse(['code' => $code, 'message' => 'private ' . $privateIdentity . ' 13800138000 000123', 'data' => ['idNo' => $privateIdentity]]);
$before = count($requests);
$exception = esignThrows($call, EsignProviderException::class, 'PROVIDER_' . $code);
esignExpect($exception->operation === $operation && count($requests) === $before + 1, 'provider errors preserve operation without retries');
foreach ([$privateIdentity, '13800138000', '000123', 'private'] as $secret) {
esignExpect(!str_contains($exception->getMessage(), $secret), 'provider errors omit sensitive payloads');
}
}
esignExpect($responses === [], 'all expected transport responses consumed');
echo 'EsignClient: ' . $checks . " checks passed (offline)\n";