Files
zyt/server/app/common/service/esign/EsignClient.php
T
2026-11-17 17:06:05 +08:00

410 lines
19 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 function __construct(public string $operation, public string $providerCode)
{
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
}
}
/** 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}. 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 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');
}
$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
{
$this->requireText($name, 'startIdentity');
$this->requireText($contextId, 'startIdentity');
$person = ['name' => $name, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
if ($accountId !== null) {
$this->requireText($accountId, 'startIdentity');
$person['sdkAccountId'] = $accountId;
}
$response = $this->identityJson('startIdentity', 'POST', '/v2/identity/auth/web/indivAuthUrl', [
'indivInfo' => $person,
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true],
]);
$data = $response['data'] ?? null;
if (!is_array($data) || !is_string($data['flowId'] ?? null) || trim($data['flowId']) === '') {
throw new EsignProviderException('startIdentity', 'RESPONSE_INVALID');
}
$url = !empty($data['shortLink']) ? $data['shortLink'] : ($data['url'] ?? '');
if (!is_string($url) || !$this->isTrustedAuthUrl($url)) {
throw new EsignProviderException('startIdentity', 'AUTH_URL_INVALID');
}
return ['flow_id' => $data['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->requireText($flowId, 'checkWillingness');
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
if (($data['status'] ?? null) !== 1
|| !is_int($data['remainingTimes'] ?? null) || $data['remainingTimes'] < 1
|| !is_int($data['expireAt'] ?? null) || $data['expireAt'] <= ($this->clock)()) {
throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID');
}
}
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
{
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' => 420, 'posY' => 70, 'width' => 100]],
], $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 {
$response = ($this->transport)([
'method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body,
'timeout' => (int) ($this->configuration['timeout'] ?? 60),
]);
} 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) {
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey]);
}
return $data;
}
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 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 ($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;
}
}