Files
zyt/server/app/common/service/esign/EsignClient.php
T
2026-11-20 10:30:04 +08:00

666 lines
32 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use Closure;
use RuntimeException;
use Throwable;
/** Safe public errors deliberately omit provider messages, bodies and transport diagnostics. */
class EsignProviderException extends RuntimeException
{
public const APPLICATION_ACCESS_DENIED = 'APPLICATION_ACCESS_DENIED';
public const IP_WHITELIST_MISMATCH = 'IP_WHITELIST_MISMATCH';
public const SIGNATURE_MISMATCH = 'SIGNATURE_MISMATCH';
public const IDENTITY_NAME_REJECTED = 'IDENTITY_NAME_REJECTED';
public const IDENTITY_METHOD_REJECTED = 'IDENTITY_METHOD_REJECTED';
public const IDENTITY_DOCUMENT_REJECTED = 'IDENTITY_DOCUMENT_REJECTED';
public const IDENTITY_QUOTA_REJECTED = 'IDENTITY_QUOTA_REJECTED';
/** Nullable allowlisted enum; never contains a provider message or identifier. */
public ?string $reason;
public function __construct(public string $operation, public string $providerCode, ?string $reason = null)
{
$hints = [
self::APPLICATION_ACCESS_DENIED => '该应用无权调用此接口,请管理员核查应用的接口授权',
self::IP_WHITELIST_MISMATCH => '请求 IP 未通过白名单校验,请管理员核查出口 IP 与应用白名单',
self::SIGNATURE_MISMATCH => '请求签名不匹配,请管理员核查签名配置',
self::IDENTITY_NAME_REJECTED => '开方医生姓名未通过核身校验,请管理员核对账号登记的证件实名',
self::IDENTITY_METHOD_REJECTED => '核身方式不可用,请管理员核对应用开通的认证方式',
self::IDENTITY_DOCUMENT_REJECTED => '证件信息未通过核身校验,请核对认证设置',
self::IDENTITY_QUOTA_REJECTED => '核身额度不足,请补充认证调试额度',
];
$validReason = match ($providerCode) {
'PROVIDER_403' => in_array($reason, [self::APPLICATION_ACCESS_DENIED, self::IP_WHITELIST_MISMATCH, self::SIGNATURE_MISMATCH], true),
'PROVIDER_30500121' => in_array($operation, ['startIdentity', 'startDoctorIdentity', 'startDoctorQuickAuthorization'], true) && in_array($reason, [self::IDENTITY_NAME_REJECTED,
self::IDENTITY_METHOD_REJECTED, self::IDENTITY_DOCUMENT_REJECTED, self::IDENTITY_QUOTA_REJECTED], true),
default => false,
};
$this->reason = $validReason ? $reason : null;
$message = 'e签宝 ' . $operation . ' 失败(' . $providerCode . ')';
if ($this->reason !== null) {
$message .= ':' . $hints[$this->reason];
} elseif ($operation === 'createPerson' && $providerCode === 'PROVIDER_403') {
$message .= ':创建签署账号被拒绝,请管理员核查该应用的接口权限及 IP 白名单';
} elseif ($operation === 'signPdf' && $providerCode === 'PROVIDER_10002') {
// The signing service and local initialization reuse this numeric code for different errors.
$message = 'e签宝签署次数不足(10002),请为当前应用补充电子签名 SDK 3.0 签署额度后重试';
}
parent::__construct($message);
}
}
/** Do not retry a signature after this exception without reconciling its outcome. */
class EsignOutcomeUnknownException extends EsignProviderException
{
public function __construct(string $code, public ?string $signServiceId = null)
{
parent::__construct('signPdf', $code);
}
}
/**
* SDK 3.x PaaS HTTP adapter. Identity uses the independent v2 identity service.
*
* Transport receives {method,url,headers,body,timeout} and returns
* {status:int,body:string,errno?:int}. HTTPS requests can include a local ca_file.
* It must not log request bodies or credentials.
* No method retries a request. initialize() is an explicit deployment operation:
* an initialized JVM must be restarted before changing app/environment.
*/
final class EsignClient
{
private const JSON_TYPE = 'application/json; charset=UTF-8';
private const MAINLAND_CERT_TYPE = 'INDIVIDUAL_CH_IDCARD';
private const WILLINGNESS_PATH = '/v2/identity/willingness/api/individual';
private const MAX_PDF_BYTES = 20971520;
private const ENVIRONMENTS = [
'sandbox' => [
'identity' => 'https://smlopenapi.esign.cn',
'init' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
'auth_hosts' => ['smlt.esign.cn', 'smlfront.esign.cn'],
],
'production' => [
'identity' => 'https://openapi.esign.cn',
'init' => 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2',
'auth_hosts' => ['t.esign.cn', 'idverify.esign.cn'],
],
];
private array $configuration;
private Closure $transport;
private Closure $clock;
public function __construct(?array $configuration = null, ?callable $transport = null, ?callable $clock = null)
{
$this->configuration = $configuration ?? (array) \think\facade\Config::get('esign', []);
$this->transport = $transport !== null ? Closure::fromCallable($transport) : Closure::fromCallable([self::class, 'curlTransport']);
$this->clock = $clock !== null ? Closure::fromCallable($clock) : static fn (): int => (int) floor(microtime(true) * 1000);
}
public function isEnabled(): bool
{
return filter_var($this->configuration['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN);
}
public function environment(): string
{
return strtolower(trim((string) ($this->configuration['environment'] ?? 'sandbox')));
}
public function assertConfigured(): void
{
if (!$this->isEnabled()) {
throw new EsignProviderException('configuration', 'DISABLED');
}
if (!isset(self::ENVIRONMENTS[$this->environment()])) {
throw new EsignProviderException('configuration', 'ENVIRONMENT_INVALID');
}
foreach (['app_id', 'app_secret'] as $key) {
if (!is_string($this->configuration[$key] ?? null)
|| trim($this->configuration[$key]) === ''
|| preg_match('/[\x00-\x1f\x7f]/', $this->configuration[$key])) {
throw new EsignProviderException('configuration', 'CREDENTIALS_MISSING');
}
}
$timeout = $this->configuration['timeout'] ?? 60;
if (filter_var($timeout, FILTER_VALIDATE_INT) === false || (int) $timeout < 1 || (int) $timeout > 300) {
throw new EsignProviderException('configuration', 'TIMEOUT_INVALID');
}
$caFile = $this->configuration['ca_file'] ?? '';
if (!is_string($caFile) || ($caFile !== '' && (!stream_is_local($caFile) || !is_file($caFile) || !is_readable($caFile)))) {
throw new EsignProviderException('configuration', 'CA_FILE_INVALID');
}
$url = (string) ($this->configuration['sdk_url'] ?? '');
$parts = parse_url($url);
if (!is_array($parts) || !isset($parts['host'])
|| !in_array($parts['scheme'] ?? '', ['http', 'https'], true)
|| isset($parts['user']) || isset($parts['pass'])
|| isset($parts['query']) || isset($parts['fragment'])
|| rtrim((string) ($parts['path'] ?? ''), '/') !== '/paas-sdk-service'
|| preg_match('/[\x00-\x20\x7f]/', $url)) {
throw new EsignProviderException('configuration', 'SDK_URL_INVALID');
}
// The SDK accepts credentials and patient documents: plain HTTP is local/private only.
if ($parts['scheme'] === 'http' && !self::isPrivateHost((string) $parts['host'])) {
throw new EsignProviderException('configuration', 'SDK_HTTP_REQUIRES_PRIVATE_HOST');
}
}
public function initialize(): void
{
$this->assertConfigured();
$this->sdkJson('initialize', '/timevale/init', [
'projectConfig' => [
'projectId' => $this->configuration['app_id'],
'projectSecret' => $this->configuration['app_secret'],
'itsmApiUrl' => self::ENVIRONMENTS[$this->environment()]['init'],
],
'httpConfig' => ['httpType' => 'HTTPS', 'retry' => 0],
'signConfig' => ['algorithm' => 'HMACSHA256'],
]);
}
/** @return array{flow_id:string,auth_url:string} */
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
{
return $this->hostedIdentity('startIdentity', ['name' => $name, 'certType' => self::MAINLAND_CERT_TYPE],
$contextId, 'PSN_TELECOM_AUTHCODE', $accountId);
}
/** @return array{flow_id:string,auth_url:string} */
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId = null): array
{
$this->requireMobile($mobile, 'startDoctorIdentity');
// The provider binds the authorized number only after successful face authentication.
return $this->hostedIdentity('startDoctorIdentity', [
'name' => $name, 'certType' => self::MAINLAND_CERT_TYPE, 'authMobileNo' => $mobile,
], $contextId, 'PSN_FACEAUTH_BYURL_ZHIMA', $accountId);
}
/** @return array{flow_id:string,auth_url:string} */
public function startDoctorQuickAuthorization(string $name, string $idNo, string $contextId, string $accountId): array
{
$this->requireText($idNo, 'startDoctorQuickAuthorization');
return $this->hostedIdentity('startDoctorQuickAuthorization', [
'name' => $name, 'certType' => self::MAINLAND_CERT_TYPE, 'certNo' => $idNo,
], $contextId, 'PSN_FACEAUTH_BYURL_ZHIMA', $accountId, 'PUREVERIFY');
}
/** @return array{flow_id:string,auth_url:string} */
private function hostedIdentity(
string $operation, array $person, string $contextId, string $authType, ?string $accountId, string $usageType = 'CERTAPPLY'
): array {
$this->requireText($person['name'], $operation);
$this->requireText($contextId, $operation);
if ($accountId !== null) {
$this->requireText($accountId, $operation);
$person['sdkAccountId'] = $accountId;
}
$uneditable = ['name', 'certType'];
if (isset($person['certNo'])) {
$uneditable[] = 'certNo';
}
$response = $this->identityJson($operation, 'POST', '/v2/identity/auth/web/indivAuthUrl', [
'indivInfo' => $person,
'usageType' => $usageType,
'authType' => $authType,
'availableAuthTypes' => [$authType],
'configParams' => ['indivUneditableInfo' => $uneditable],
'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true],
]);
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
$flowId = $this->requiredResponseText($data, 'flowId', $operation);
$url = !empty($data['shortLink']) ? $data['shortLink'] : ($data['url'] ?? '');
if (!is_string($url) || !$this->isTrustedAuthUrl($url)) {
throw new EsignProviderException($operation, 'AUTH_URL_INVALID');
}
return ['flow_id' => $flowId, 'auth_url' => $url];
}
public function identityDetail(string $flowId): array
{
$this->requireText($flowId, 'identityDetail');
$response = $this->identityJson('identityDetail', 'GET', '/v2/identity/auth/api/common/' . rawurlencode($flowId) . '/detail');
if (!is_array($response['data'] ?? null) || $response['data'] === []) {
throw new EsignProviderException('identityDetail', 'RESPONSE_INVALID');
}
return $response['data'];
}
public function checkWillingness(string $flowId): void
{
$this->willingnessExpiresAt($flowId);
}
/** Returns the provider's current expiration in Unix milliseconds. */
public function willingnessExpiresAt(string $flowId): int
{
$validity = $this->willingnessValidity($flowId);
if ($validity['state'] !== 'valid') {
throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID');
}
return $validity['expires_at'];
}
/** @return array{state:string,expires_at:int,remaining_times:int} Expiration is in Unix milliseconds. */
public function willingnessValidity(string $flowId): array
{
$this->requireText($flowId, 'checkWillingness');
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
$status = $data['status'] ?? null;
$expiresAt = $data['expireAt'] ?? null;
$remaining = $data['remainingTimes'] ?? null;
$state = match (true) {
!in_array($status, [0, 1], true), !is_int($expiresAt), $expiresAt <= 0 => 'invalid',
$expiresAt <= ($this->clock)() => 'expired',
$remaining === 0 => 'exhausted',
$status === 1 && is_int($remaining) && $remaining > 0 => 'valid',
default => 'invalid',
};
return [
'state' => $state,
'expires_at' => $state === 'valid' ? $expiresAt : 0,
'remaining_times' => $state === 'valid' ? $remaining : 0,
];
}
public function authorizedMobile(string $name, string $idNo): ?string
{
$this->requireText($name, 'authorizedMobile');
$this->requireText($idNo, 'authorizedMobile');
$response = $this->identityJson('authorizedMobile', 'POST', self::WILLINGNESS_PATH . '/get-individual-info', [
'name' => $name, 'idNo' => $idNo, 'certType' => self::MAINLAND_CERT_TYPE,
]);
$data = $response['data'] ?? null;
if ($data !== null && !is_array($data)) {
throw new EsignProviderException('authorizedMobile', 'RESPONSE_INVALID');
}
$mobile = $data['mobileNo'] ?? null;
if ($mobile === null || $mobile === '') {
return null;
}
if (!is_string($mobile) || !preg_match('/^1[3-9][0-9]{9}$/D', $mobile)) {
throw new EsignProviderException('authorizedMobile', 'RESPONSE_INVALID');
}
return $mobile;
}
public function sendWillingnessCode(string $name, string $idNo, string $mobile): string
{
$this->requireText($name, 'sendWillingnessCode');
$this->requireText($idNo, 'sendWillingnessCode');
$this->requireMobile($mobile, 'sendWillingnessCode');
$response = $this->identityJson('sendWillingnessCode', 'POST', self::WILLINGNESS_PATH . '/send-code', [
'mobileNo' => $mobile, 'name' => $name, 'idNo' => $idNo, 'certType' => self::MAINLAND_CERT_TYPE,
]);
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
return $this->requiredResponseText($data, 'flowId', 'sendWillingnessCode');
}
public function verifyWillingnessCode(string $flowId, string $code): void
{
$this->requireText($flowId, 'verifyWillingnessCode');
if (!preg_match('/^[0-9]{6}$/D', $code)) {
throw new EsignProviderException('verifyWillingnessCode', 'INPUT_INVALID');
}
$this->identityJson('verifyWillingnessCode', 'POST',
self::WILLINGNESS_PATH . '/' . rawurlencode($flowId) . '/verify-send-code', ['authCode' => $code]);
}
/** @return array{accountId:string,name:string,idNo:string,idNoType:string,accountType:string} */
public function signingAccount(string $accountId): array
{
$this->requireText($accountId, 'signingAccount');
$data = $this->sdkJson('signingAccount', '/timevale/account/queryByAccountId', ['accountId' => $accountId]);
$returnedId = $this->requiredResponseText($data, 'accountId', 'signingAccount');
if ($returnedId !== $accountId) {
throw new EsignProviderException('signingAccount', 'RESPONSE_INVALID');
}
return [
'accountId' => $returnedId,
'name' => $this->requiredResponseText($data, 'name', 'signingAccount'),
'idNo' => $this->requiredResponseText($data, 'idNo', 'signingAccount'),
'idNoType' => $this->requiredResponseText($data, 'idNoType', 'signingAccount'),
'accountType' => $this->requiredResponseText($data, 'accountType', 'signingAccount'),
];
}
/** @return array{startDate:string,endDate:string} */
public function certificateValidity(string $accountId): array
{
$data = $this->latestCertificate($accountId);
return [
'startDate' => $this->requiredResponseText($data, 'startDate', 'certificateValidity'),
'endDate' => $this->requiredResponseText($data, 'endDate', 'certificateValidity'),
];
}
private function latestCertificate(string $accountId): array
{
$this->requireText($accountId, 'certificateValidity');
return $this->sdkJson('certificateValidity', '/timevale/user/cert/queryLatestAvailableCert', ['accountId' => $accountId]);
}
public function certificateIdentity(string $accountId): array
{
$data = $this->latestCertificate($accountId);
return [
'issuerCN' => $this->requiredResponseText($data, 'issuerCN', 'certificateValidity'),
'sn' => $this->requiredResponseText($data, 'sn', 'certificateValidity'),
];
}
public function createPerson(string $name, string $idNo, string $flowId): string
{
foreach ([$name, $idNo, $flowId] as $value) {
$this->requireText($value, 'createPerson');
}
$data = $this->sdkJson('createPerson', '/timevale/account/addPerson', [
'name' => $name, 'idNo' => $idNo, 'idNoType' => 'MAINLAND', 'identityAuthId' => $flowId,
]);
return $this->requiredResponseText($data, 'accountId', 'createPerson');
}
public function createSeal(string $accountId): string
{
$this->requireText($accountId, 'createSeal');
$data = $this->sdkJson('createSeal', '/timevale/seal/createPersonSeal', [
'accountId' => $accountId, 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE',
]);
$seal = $this->requiredResponseText($data, 'sealData', 'createSeal');
if (base64_decode($seal, true) === false) {
throw new EsignProviderException('createSeal', 'RESPONSE_INVALID');
}
return $seal;
}
/** @return array{sign_service_id:string,pdf:string} */
public function signPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
{
return $this->signAt($accountId, $flowId, $sealData, $pdfBytes, $fileName, 520, 108);
}
public function signReviewPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
{
return $this->signAt($accountId, $flowId, $sealData, $pdfBytes, $fileName, 520, 63);
}
private function signAt(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName, int $x, int $y): array
{
foreach ([$accountId, $flowId, $sealData, $fileName] as $value) {
$this->requireText($value, 'signPdf');
}
$this->requirePdf($pdfBytes, 'signPdf');
if (base64_decode($sealData, true) === false) {
throw new EsignProviderException('signPdf', 'SEAL_INVALID');
}
$data = $this->sdkMultipart('signPdf', '/timevale/user/sign/personSign', 'personSignParam', [
'accountId' => $accountId, 'willingnessId' => $flowId, 'sealData' => $sealData,
'signType' => 'Single', 'fileBean' => ['fileName' => $fileName],
'posBeans' => [['posPage' => '1', 'posX' => $x, 'posY' => $y, 'width' => 48]],
], $pdfBytes, true);
$serviceId = is_string($data['signServiceId'] ?? null) && trim($data['signServiceId']) !== '' ? $data['signServiceId'] : null;
$pdf = is_string($data['stream'] ?? null) ? base64_decode($data['stream'], true) : false;
if ($serviceId === null || !is_string($pdf) || !str_starts_with($pdf, '%PDF-') || strlen($pdf) > self::MAX_PDF_BYTES) {
throw new EsignOutcomeUnknownException('SIGNED_FILE_UNAVAILABLE', $serviceId);
}
return ['sign_service_id' => $serviceId, 'pdf' => $pdf];
}
public function verifyPdf(string $pdfBytes): array
{
$this->requirePdf($pdfBytes, 'verifyPdf');
$data = $this->sdkMultipart('verifyPdf', '/timevale/verify/pdf', 'verifyPdfParam', ['fileName' => 'prescription.pdf'], $pdfBytes);
$signatures = $data['signatures'] ?? null;
if (!is_array($signatures) || $signatures === [] || array_keys($signatures) !== range(0, count($signatures) - 1)) {
throw new EsignProviderException('verifyPdf', 'NO_SIGNATURES');
}
foreach ($signatures as $signature) {
if (!is_array($signature) || ($signature['signature']['validate'] ?? null) !== true) {
throw new EsignProviderException('verifyPdf', 'SIGNATURE_INVALID');
}
}
return ['signatures' => $signatures];
}
private function sdkJson(string $operation, string $path, array $data): array
{
$this->assertConfigured();
return $this->request($operation, 'POST', rtrim($this->configuration['sdk_url'], '/') . $path,
['Content-Type' => self::JSON_TYPE, 'Accept' => 'application/json'], $this->json($data, $operation), 'errCode');
}
private function identityJson(string $operation, string $method, string $path, ?array $data = null): array
{
$this->assertConfigured();
$body = $data !== null ? $this->json($data, $operation) : '';
$md5 = $body === '' ? '' : base64_encode(md5($body, true));
// Official HMACSHA256 canonical form: method, accept, MD5, type, empty date, resource.
$canonical = $method . "\n*/*\n" . $md5 . "\n" . self::JSON_TYPE . "\n\n" . $path;
$headers = [
'Accept' => '*/*', 'Content-Type' => self::JSON_TYPE,
'X-Tsign-Open-App-Id' => $this->configuration['app_id'],
'X-Tsign-Open-Auth-Mode' => 'Signature',
'X-Tsign-Open-Ca-Timestamp' => (string) ($this->clock)(),
'X-Tsign-Open-Ca-Signature' => base64_encode(hash_hmac('sha256', $canonical, $this->configuration['app_secret'], true)),
];
if ($md5 !== '') {
$headers['Content-MD5'] = $md5;
}
return $this->request($operation, $method, self::ENVIRONMENTS[$this->environment()]['identity'] . $path, $headers, $body, 'code');
}
private function sdkMultipart(string $operation, string $path, string $parameter, array $data, string $pdf, bool $signing = false): array
{
$this->assertConfigured();
$boundary = 'esign-' . bin2hex(random_bytes(24));
// JSON part needs its own application/json media type; a PHP POSTFIELDS string is insufficient.
$body = '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"" . $parameter . "\"\r\nContent-Type: " . self::JSON_TYPE . "\r\n\r\n"
. $this->json($data, $operation)
. "\r\n--" . $boundary . "\r\nContent-Disposition: form-data; name=\"streamFile\"; filename=\"prescription.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n"
. $pdf . "\r\n--" . $boundary . "--\r\n";
return $this->request($operation, 'POST', rtrim($this->configuration['sdk_url'], '/') . $path,
['Content-Type' => 'multipart/form-data; boundary=' . $boundary, 'Accept' => 'application/json', 'Expect' => ''], $body, 'errCode', $signing);
}
private function request(string $operation, string $method, string $url, array $headers, string $body, string $codeKey, bool $signing = false): array
{
try {
$request = [
'method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body,
'timeout' => (int) ($this->configuration['timeout'] ?? 60),
];
$caFile = $this->configuration['ca_file'] ?? '';
if ($caFile !== '' && str_starts_with($url, 'https://')) {
$request['ca_file'] = $caFile;
}
$response = ($this->transport)($request);
} catch (Throwable $exception) {
// Never attach the original exception: its URL/body may contain identity or secret data.
$this->fail($operation, 'TRANSPORT_ERROR', $signing);
}
if (!is_array($response) || (int) ($response['errno'] ?? 0) !== 0) {
$this->fail($operation, is_array($response) && (int) ($response['errno'] ?? 0) === 28 ? 'TIMEOUT' : 'TRANSPORT_ERROR', $signing);
}
$status = (int) ($response['status'] ?? 0);
if ($status < 200 || $status > 299) {
$this->fail($operation, 'HTTP_' . $status, $signing);
}
$raw = $response['body'] ?? null;
if (!is_string($raw) || trim($raw) === '') {
$this->fail($operation, 'EMPTY_RESPONSE', $signing);
}
try {
$data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
} catch (Throwable $exception) {
$this->fail($operation, 'INVALID_JSON', $signing);
}
if (!is_array($data) || !array_key_exists($codeKey, $data) || !is_int($data[$codeKey])) {
$this->fail($operation, 'RESPONSE_INVALID', $signing);
}
if ($data[$codeKey] !== 0) {
$reason = match (true) {
$data[$codeKey] === 403 => $this->forbiddenReason($data),
in_array($operation, ['startIdentity', 'startDoctorIdentity', 'startDoctorQuickAuthorization'], true) && $data[$codeKey] === 30500121
=> $this->identityStartReason($data['message'] ?? $data['msg'] ?? null),
default => null,
};
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey],
$reason);
}
return $data;
}
private function forbiddenReason(array $data): ?string
{
$message = $data['msg'] ?? null;
if (!is_string($message)) {
return null;
}
// Translate recognized phrases to fixed codes; do not retain or echo vendor text.
if (str_contains($message, '该应用无权调用此接口')) {
return EsignProviderException::APPLICATION_ACCESS_DENIED;
}
foreach (['IP不在白名单', 'IP地址不在白名单', 'IP 不在白名单', 'IP 地址不在白名单',
'IP白名单不匹配', 'IP 白名单不匹配', 'IP白名单校验失败', 'IP 白名单校验失败'] as $phrase) {
if (str_contains($message, $phrase)) {
return EsignProviderException::IP_WHITELIST_MISMATCH;
}
}
if (preg_match('/(?<![A-Za-z0-9_])SignatureDoesNotMatch(?![A-Za-z0-9_])/', $message) === 1) {
return EsignProviderException::SIGNATURE_MISMATCH;
}
// FORBIDDEN alone does not distinguish application permissions from an IP rejection.
return null;
}
private function identityStartReason(mixed $message): ?string
{
if (!is_string($message)) {
return null;
}
// Translate provider detail into fixed hints. Do not return identity data from the supplier.
return match (true) {
str_contains($message, '姓名') => EsignProviderException::IDENTITY_NAME_REJECTED,
str_contains($message, '余额不足') || str_contains($message, '次数不足') => EsignProviderException::IDENTITY_QUOTA_REJECTED,
str_contains($message, '认证方式') => EsignProviderException::IDENTITY_METHOD_REJECTED,
str_contains($message, '证件') || str_contains($message, '身份证') => EsignProviderException::IDENTITY_DOCUMENT_REJECTED,
default => null,
};
}
private function fail(string $operation, string $code, bool $signing): void
{
if ($signing) {
throw new EsignOutcomeUnknownException($code);
}
throw new EsignProviderException($operation, $code);
}
private function json(array $data, string $operation): string
{
try {
return json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Throwable $exception) {
throw new EsignProviderException($operation, 'INPUT_INVALID');
}
}
private function requireText(string $text, string $operation): void
{
if (trim($text) === '' || strlen($text) > 1048576 || preg_match('/[\x00-\x1f\x7f]/', $text)) {
throw new EsignProviderException($operation, 'INPUT_INVALID');
}
}
private function requireMobile(string $mobile, string $operation): void
{
if (!preg_match('/^1[3-9][0-9]{9}$/D', $mobile)) {
throw new EsignProviderException($operation, 'INPUT_INVALID');
}
}
private function requirePdf(string $bytes, string $operation): void
{
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > self::MAX_PDF_BYTES) {
throw new EsignProviderException($operation, 'PDF_INVALID');
}
}
private function requiredResponseText(array $data, string $key, string $operation): string
{
if (!is_string($data[$key] ?? null) || trim($data[$key]) === '') {
throw new EsignProviderException($operation, 'RESPONSE_INVALID');
}
return $data[$key];
}
private function isTrustedAuthUrl(string $url): bool
{
$parts = parse_url($url);
return is_array($parts) && ($parts['scheme'] ?? '') === 'https'
&& !isset($parts['user']) && !isset($parts['pass'])
&& !preg_match('/[\x00-\x20\x7f\\\\]/', $url)
&& (!isset($parts['port']) || $parts['port'] === 443
|| (($parts['host'] ?? '') === 'smlfront.esign.cn' && $parts['port'] === 8890))
&& in_array(strtolower((string) ($parts['host'] ?? '')), self::ENVIRONMENTS[$this->environment()]['auth_hosts'], true);
}
private static function isPrivateHost(string $host): bool
{
$host = strtolower(trim($host, '[]'));
if (in_array($host, ['localhost', '::1'], true)) {
return true;
}
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$octets = array_map('intval', explode('.', $host));
return $octets[0] === 127 || $octets[0] === 10
|| ($octets[0] === 172 && $octets[1] >= 16 && $octets[1] <= 31)
|| ($octets[0] === 192 && $octets[1] === 168);
}
return false;
}
private static function curlTransport(array $request): array
{
if (!function_exists('curl_init')) {
throw new RuntimeException('CURL_UNAVAILABLE');
}
$handle = curl_init($request['url']);
$responseBody = '';
$headers = [];
foreach ($request['headers'] as $name => $value) {
$headers[] = $name . ': ' . $value;
}
curl_setopt_array($handle, [
CURLOPT_CUSTOMREQUEST => $request['method'], CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => false, CURLOPT_MAXREDIRS => 0,
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_CONNECTTIMEOUT => min(10, $request['timeout']), CURLOPT_TIMEOUT => $request['timeout'],
CURLOPT_NOSIGNAL => true,
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$responseBody): int {
if (strlen($responseBody) + strlen($chunk) > 67108864) {
return 0;
}
$responseBody .= $chunk;
return strlen($chunk);
},
]);
if (isset($request['ca_file'])) {
curl_setopt($handle, CURLOPT_CAINFO, $request['ca_file']);
}
if ($request['method'] !== 'GET') {
curl_setopt($handle, CURLOPT_POSTFIELDS, $request['body']);
}
curl_exec($handle);
$response = ['status' => (int) curl_getinfo($handle, CURLINFO_HTTP_CODE), 'body' => $responseBody, 'errno' => curl_errno($handle)];
curl_close($handle);
return $response;
}
}