This commit is contained in:
Your Name
2026-11-20 10:30:04 +08:00
parent 378bf32069
commit 0dc41a1507
96 changed files with 13497 additions and 791 deletions
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
final class DoctorEsignAuthorizationRequired extends \DomainException
{
public function __construct(public readonly string $reason)
{
parent::__construct(match ($reason) {
'exhausted' => '医生实名和证书已保存。e签宝签署授权次数已用完,请在账号菜单查看快捷签授权',
'expired' => '医生实名和证书已保存。快捷签授权已到期,请在账号菜单续期',
'invalid' => '医生实名和证书已保存。e签宝签署授权已失效,请在账号菜单检查授权',
default => '医生实名和证书已保存。请在账号菜单的「医生电子签署身份」中授权快捷签',
});
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
final class DoctorEsignIdentityRequired extends \DomainException
{
}
@@ -0,0 +1,625 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use DateTimeImmutable;
use DateTimeZone;
use DomainException;
use think\facade\Config;
use think\facade\Db;
final class DoctorEsignIdentityService
{
private const DOCTOR_ROLE_ID = 1;
private const FLOW_LIFETIME = 30 * 86400;
private const ACCOUNT_BINDING_PROOF_LIFETIME = 30 * 60;
private const QUICK_LIFETIME = 86400;
private const IDENTITY_FLOW_TABLE = 'doctor_esign_identity';
private const QUICK_FLOW_TABLE = 'doctor_esign_quicksign';
private const STATE_CHANGED = '医师认证状态已变化,请重新查询';
public static function enabled(): bool
{
return PrescriptionEsignService::enabled()
&& (filter_var(Config::get('esign.doctor_sms_enabled', false), FILTER_VALIDATE_BOOLEAN) || self::quickEnabled());
}
public static function quickEnabled(): bool
{
return PrescriptionEsignService::enabled()
&& filter_var(Config::get('esign.doctor_quicksign_enabled', false), FILTER_VALIDATE_BOOLEAN);
}
public static function status(int $actor): array
{
if (!self::enabled()) {
return ['enabled' => false] + self::state('unbound', '医师电子签署认证尚未启用');
}
$scope = self::scope($actor);
$snapshot = self::snapshot($scope);
if (self::hasLease($snapshot['flow'])) {
return self::processing();
}
$client = new EsignClient();
if (self::hasCurrentFlow($snapshot)) {
[$status, $person] = self::identityResult($client, $snapshot);
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
}
}
$quick = self::quickEnabled() ? self::snapshot($scope, false, self::QUICK_FLOW_TABLE) : null;
if ($quick !== null && self::hasLease($quick['flow'])) {
return self::processing(true);
}
if ($quick !== null && self::hasPendingQuickFlow($quick)) {
[$quickStatus] = self::identityResult($client, $quick);
if ($pending = self::pendingState($quick, $quickStatus, false)) {
self::assertUnchanged($scope, $quick);
return $pending;
}
}
$state = self::readiness($client, $snapshot, true, $quick === null)['state'];
if (isset($status) && $state['status'] !== 'ready') {
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
}
if ($quick !== null && $state['status'] === 'ready') {
$state = self::withQuickValidity($state, self::quickValidity($client, $quick));
if (($quickStatus ?? '') === 'FAIL') {
$state['message'] = '快捷签认证未通过,请重新发起授权';
}
}
if ($quick !== null) {
self::assertUnchanged($scope, $quick);
}
self::assertUnchanged($scope, $snapshot);
return $state;
}
public static function start(int $actor, string $mobile): array
{
$scope = self::scope($actor);
$mobile = trim($mobile);
if (self::quickEnabled() && $mobile === '') {
return self::startQuick($scope);
}
if (!self::validMobile($mobile)) {
throw new DomainException('请输入有效的大陆手机号');
}
$mobileHash = self::mobileHash($scope, $mobile);
$snapshot = self::snapshot($scope);
if (self::hasLease($snapshot['flow'])) {
return self::processing();
}
$client = new EsignClient();
if (self::hasCurrentFlow($snapshot) && hash_equals($snapshot['flow']['mobile_hash'], $mobileHash)) {
[$status, $person] = self::identityResult($client, $snapshot);
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
}
}
$state = self::readiness($client, $snapshot, true, !self::quickEnabled())['state'];
if ($state['status'] === 'ready') {
self::assertUnchanged($scope, $snapshot);
return self::quickEnabled() ? self::status($actor) : $state;
}
$token = self::claim($scope, $snapshot);
try {
$accountId = $snapshot['account']['account_id'] ?? null;
$flow = $client->startDoctorIdentity($snapshot['name'], 'doctor-enrollment-' . $token, $mobile, $accountId);
self::finish($scope, $snapshot, $token, [
'doctor_name' => $snapshot['name'],
'account_id' => $accountId ?? '',
'flow_id' => $flow['flow_id'],
'auth_url' => $flow['auth_url'],
'mobile_hash' => $mobileHash,
'flow_started_at' => time(),
]);
return self::state('authenticating', '请完成医师实名认证') + ['auth_url' => $flow['auth_url']];
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
}
public static function complete(int $actor, string $identityNumber = ''): array
{
$scope = self::scope($actor);
$snapshot = self::snapshot($scope);
if (self::hasLease($snapshot['flow'])) {
return self::processing();
}
if (!self::hasCurrentFlow($snapshot)) {
if (self::quickEnabled()) {
return self::completeQuick($scope);
}
return self::status($actor);
}
$token = self::claim($scope, $snapshot);
try {
$client = new EsignClient();
[$status, $person] = self::identityResult($client, $snapshot);
if ($status === 'FAIL' || $status === 'EXPIRED') {
self::finish($scope, $snapshot, $token, null);
$state = self::status($actor);
if ($state['status'] !== 'ready') {
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
}
return $state;
}
if ($status !== 'SUCCESS') {
self::finish($scope, $snapshot, $token, []);
return self::pendingState($snapshot, $status, false);
}
if ($person && self::validMobile($person['mobile'])
&& !hash_equals($snapshot['flow']['mobile_hash'], self::mobileHash($scope, $person['mobile']))) {
self::finish($scope, $snapshot, $token, null);
throw new DomainException('认证手机号与本次发起的手机号不一致,请重新发起认证');
}
$newAccountId = null;
if ($snapshot['account']) {
$document = self::accountDocument($client, $snapshot);
if ($person && $person['idNo'] !== null && !hash_equals($document, $person['idNo'])) {
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
}
} else {
$document = $person['idNo'] ?? null;
if ($document === null) {
$document = strtoupper(trim($identityNumber));
if (!PrescriptionEsignService::validMainlandIdentityNumber($document)) {
self::finish($scope, $snapshot, $token, []);
$state = self::pendingState($snapshot, 'SUCCESS', true);
if ($document !== '') {
$state['message'] = '请输入本次认证使用的有效大陆身份证号码';
}
return $state;
}
}
// eSign matches the document and name against the authenticated identity before issuing the account.
$newAccountId = $client->createPerson($snapshot['name'], $document, $snapshot['flow']['flow_id']);
}
unset($identityNumber, $person, $document);
self::finish($scope, $snapshot, $token, null, $newAccountId);
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
return self::status($actor);
}
/** Returns the current doctor-scoped proof for the provider call only. */
public static function quickAuthorization(int $actor, string $signerName, string $accountId): string
{
if (!self::quickEnabled()) {
throw new DomainException('快捷签设置已变化,请重新查询处方');
}
$scope = self::scope($actor);
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
if (!$snapshot['account']) {
throw new DoctorEsignIdentityRequired('请先在医师电子签署设置中完成实名认证');
}
if ($snapshot['name'] !== $signerName || $snapshot['account']['doctor_name'] !== $signerName
|| $snapshot['account']['account_id'] !== $accountId) {
throw new DomainException('处方签署账号已变化,请重试');
}
$client = new EsignClient();
[$certStart, $certEnd] = self::certificatePeriod($client, $accountId);
if (!$certStart || $certStart > time() || $certEnd <= time()) {
throw new DoctorEsignIdentityRequired('医师签署证书需要续期,请在账号菜单中处理');
}
$validity = self::quickValidity($client, $snapshot);
self::assertUnchanged($scope, $snapshot);
if ($certEnd <= time()) {
throw new DoctorEsignIdentityRequired('医师签署证书需要续期,请在账号菜单中处理');
}
if ($validity['state'] !== 'valid') {
throw new DoctorEsignAuthorizationRequired($validity['state']);
}
if ($validity['expires_at'] <= time()) {
throw new DoctorEsignAuthorizationRequired('expired');
}
return $snapshot['flow']['flow_id'];
}
private static function startQuick(array $scope): array
{
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
if (self::hasLease($snapshot['flow'])) {
return self::processing(true);
}
$client = new EsignClient();
if (self::hasPendingQuickFlow($snapshot)) {
[$status] = self::identityResult($client, $snapshot);
if ($pending = self::pendingState($snapshot, $status, false)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
}
}
$ready = self::readiness($client, $snapshot, true, false);
$state = $ready['state'];
if ($state['status'] !== 'ready') {
self::assertUnchanged($scope, $snapshot);
return $state;
}
$state = self::withQuickValidity($state, self::quickValidity($client, $snapshot));
if ($state['quicksign_expires_at'] > time()) {
self::assertUnchanged($scope, $snapshot);
return $state;
}
$token = self::claim($scope, $snapshot);
try {
$accountId = $snapshot['account']['account_id'];
$flow = $client->startDoctorQuickAuthorization($snapshot['name'], $ready['idNo'], 'doctor-quicksign-' . $token, $accountId);
self::finish($scope, $snapshot, $token, [
'doctor_name' => $snapshot['name'], 'account_id' => $accountId, 'flow_id' => $flow['flow_id'],
'auth_url' => $flow['auth_url'], 'flow_started_at' => time(), 'expires_at' => 0,
]);
return self::state('authenticating', '请完成快捷签人脸认证', 0, true) + ['auth_url' => $flow['auth_url']];
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
}
private static function completeQuick(array $scope): array
{
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
if (self::hasLease($snapshot['flow'])) {
return self::processing(true);
}
if (!self::hasPendingQuickFlow($snapshot)) {
return self::status($scope['doctor_id']);
}
$token = self::claim($scope, $snapshot);
try {
$client = new EsignClient();
[$status, $person, $completedAt] = self::identityResult($client, $snapshot);
if ($status === 'INIT' || $status === 'ING') {
self::finish($scope, $snapshot, $token, []);
return self::pendingState($snapshot, $status, false);
}
$expires = 0;
if ($status === 'SUCCESS') {
$document = self::accountDocument($client, $snapshot);
if ($person && $person['idNo'] !== null && !hash_equals($document, $person['idNo'])) {
self::finish($scope, $snapshot, $token, null);
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
}
$providerExpiry = intdiv($client->willingnessValidity($snapshot['flow']['flow_id'])['expires_at'], 1000);
$expires = min($providerExpiry, min(time(), $completedAt) + self::QUICK_LIFETIME);
}
if ($expires <= time()) {
self::finish($scope, $snapshot, $token, null);
$state = self::status($scope['doctor_id']);
$state['message'] = $status === 'FAIL' ? '快捷签认证未通过,请重新发起授权' : '快捷签授权已失效,请重新发起授权';
return $state;
}
self::finish($scope, $snapshot, $token, ['auth_url' => null, 'expires_at' => $expires]);
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
return self::status($scope['doctor_id']);
}
/** @return array{state:string,expires_at:int,remaining_times:int} Expiration is in Unix seconds. */
private static function quickValidity(EsignClient $client, array $snapshot): array
{
$flow = $snapshot['flow'];
$localExpiry = (int) ($flow['expires_at'] ?? 0);
$missing = ['state' => 'missing', 'expires_at' => 0, 'remaining_times' => 0];
if (!$localExpiry || empty($flow['flow_id']) || self::hasLease($flow)) {
return $missing;
}
if (!$snapshot['account'] || $snapshot['account']['doctor_name'] !== $snapshot['name']
|| $flow['doctor_name'] !== $snapshot['name'] || $flow['account_id'] !== $snapshot['account']['account_id']) {
return ['state' => 'invalid'] + $missing;
}
if ($localExpiry <= time()) {
return ['state' => 'expired'] + $missing;
}
$validity = $client->willingnessValidity($flow['flow_id']);
if ($validity['state'] !== 'valid') {
return $validity;
}
$validity['expires_at'] = min($localExpiry, intdiv($validity['expires_at'], 1000));
return $validity['expires_at'] > time() ? $validity : ['state' => 'expired'] + $missing;
}
private static function withQuickValidity(array $state, array $validity): array
{
$state['quicksign_expires_at'] = $validity['expires_at'];
$state['quicksign_remaining_times'] = $validity['remaining_times'];
$state['quicksign_unavailable_reason'] = $validity['state'] === 'valid' ? '' : $validity['state'];
return $state;
}
/** @return array{name:string,idNo:string,mobile:string} For the provider call only. */
public static function willingnessRecipient(int $actor, string $signerName, string $accountId): array
{
$scope = self::scope($actor);
$snapshot = self::snapshot($scope);
if (!$snapshot['account']) {
throw new DoctorEsignIdentityRequired('请先在医师电子签署设置中完成实名认证');
}
if ($snapshot['name'] !== $signerName || $snapshot['account']['account_id'] !== $accountId) {
throw new DomainException('处方签署账号已变化,请重试');
}
$ready = self::readiness(new EsignClient(), $snapshot);
$current = self::snapshot($scope);
if ($current['name'] !== $snapshot['name'] || $current['account'] !== $snapshot['account']) {
throw new DomainException(self::STATE_CHANGED);
}
if ($ready['state']['status'] !== 'ready') {
throw new DoctorEsignIdentityRequired($ready['state']['message']);
}
if ($ready['state']['cert_expires_at'] <= time()) {
throw new DoctorEsignIdentityRequired('医师签署证书已过期,请重新认证');
}
return ['name' => $signerName, 'idNo' => $ready['idNo'], 'mobile' => $ready['mobile']];
}
private static function readiness(EsignClient $client, array $snapshot, bool $allowCertificateRecovery = false, bool $requireMobile = true): array
{
if (!$snapshot['account']) {
return ['state' => self::state('unbound', '请先完成医师实名认证')];
}
$idNo = self::accountDocument($client, $snapshot);
try {
[$start, $end] = self::certificatePeriod($client, $snapshot['account']['account_id']);
} catch (EsignProviderException $error) {
// The SDK does not define a distinct response code for no available certificate.
if (!$allowCertificateRecovery || !str_starts_with($error->providerCode, 'PROVIDER_')) {
throw $error;
}
return ['state' => self::state('renewal_required', '暂时无法确认签署证书有效期,可重新查询或发起续期')];
}
if ($start === 0 || $start > time() || $end <= time()) {
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
}
$mobile = $requireMobile ? $client->authorizedMobile($snapshot['name'], $idNo) : null;
if ($requireMobile && !self::validMobile($mobile)) {
return ['state' => self::state('needs_mobile', '请完成实名手机号认证', $end)];
}
if ($end <= time()) {
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
}
return ['state' => self::state('ready', '医师电子签署已就绪', $end), 'idNo' => $idNo, 'mobile' => $mobile];
}
private static function accountDocument(EsignClient $client, array $snapshot): string
{
$account = $snapshot['account'];
if ($account['doctor_name'] !== $snapshot['name']) {
throw new DomainException('签署账号实名信息已变化,请联系管理员核实');
}
$details = $client->signingAccount($account['account_id']);
$idNo = $details['idNo'] ?? '';
if (($details['accountId'] ?? '') !== $account['account_id'] || ($details['name'] ?? '') !== $snapshot['name']
|| ($details['accountType'] ?? '') !== 'PERSON' || ($details['idNoType'] ?? '') !== 'MAINLAND'
|| !is_string($idNo) || !preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9Xx])$/D', $idNo)) {
throw new DomainException('签署账号实名信息不一致,请联系管理员核实');
}
return strtoupper($idNo);
}
/** @return array{int,int} */
private static function certificatePeriod(EsignClient $client, string $accountId): array
{
$dates = $client->certificateValidity($accountId);
return [self::certificateTime($dates['startDate'] ?? ''), self::certificateTime($dates['endDate'] ?? '')];
}
/** SDK validity timestamps are local to the configured SDK timezone. */
private static function certificateTime(string $value): int
{
if ($value === '') {
return 0;
}
$zone = new DateTimeZone((string) Config::get('esign.sdk_timezone', 'Asia/Shanghai'));
$time = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value, $zone);
if (!$time || $time->format('Y-m-d H:i:s') !== $value) {
throw new DomainException('暂时无法确认医师签署证书有效期,请稍后重试');
}
return $time->getTimestamp();
}
private static function identityResult(EsignClient $client, array $snapshot): array
{
$flow = $snapshot['flow'];
$detail = $client->identityDetail($flow['flow_id']);
$status = $detail['status'] ?? '';
if (($detail['flowId'] ?? '') !== $flow['flow_id']
|| (isset($detail['appId']) && (string) $detail['appId'] !== $flow['app_id'])
|| !in_array($status, ['INIT', 'ING', 'SUCCESS', 'FAIL'], true)) {
throw new DomainException('暂时无法确认本次医师认证,请稍后重试');
}
if ($status !== 'SUCCESS') {
return [$status, null, 0];
}
if (($detail['objectType'] ?? '') !== 'INDIVIDUAL') {
throw new DomainException('认证对象与医师个人签署不一致');
}
$completedAt = isset($detail['endTime']) && is_int($detail['endTime']) && $detail['endTime'] > 0
? intdiv($detail['endTime'], 1000) : (int) $flow['flow_started_at'];
if (!$snapshot['account'] && $completedAt + self::ACCOUNT_BINDING_PROOF_LIFETIME <= time()) {
return ['EXPIRED', null, $completedAt];
}
if (array_key_exists('indivInfo', $detail) && $detail['indivInfo'] === null) {
return [$status, null, $completedAt];
}
$person = $detail['indivInfo'] ?? null;
if (!is_array($person) || ($person['name'] ?? '') !== $snapshot['name']
|| ($person['certType'] ?? '') !== 'INDIVIDUAL_CH_IDCARD' || !is_string($person['certNo'] ?? null)) {
throw new DomainException('认证实名信息与医师账号不一致或证件类型不支持');
}
$idNo = strtoupper($person['certNo']);
if (str_contains($idNo, '*') && preg_match('/^(?:[0-9*]{15}|[0-9*]{17}[0-9X*])$/D', $idNo)) {
$idNo = null; // addPerson validates any supplemental number against the provider flow.
} elseif (!preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9X])$/D', $idNo)) {
throw new DomainException('认证证件号码格式无效,请重新认证');
}
$mobile = is_string($person['authMobileNo'] ?? null) ? $person['authMobileNo'] : null;
return [$status, ['idNo' => $idNo, 'mobile' => $mobile], $completedAt];
}
private static function pendingState(array $snapshot, string $status, bool $documentMissing): ?array
{
$quick = $snapshot['flow_table'] === self::QUICK_FLOW_TABLE;
if ($status === 'INIT' || $status === 'ING') {
$message = $quick ? '请完成快捷签人脸认证' : '请完成医师实名认证';
return self::state('authenticating', $message, 0, $quick) + ['auth_url' => $snapshot['flow']['auth_url']];
}
if ($status === 'SUCCESS') {
$needed = !$snapshot['account'] && $documentMissing;
$message = match (true) {
$quick => '人脸认证已通过,请确认快捷签授权',
$needed => '认证已通过,请补充本次认证使用的身份证号码以绑定签署账号',
default => '认证已通过,请确认完成医师电子签署认证',
};
return self::state('binding_required', $message, 0, $quick) + ['identity_details_required' => $needed];
}
return null;
}
private static function scope(int $actor): array
{
if (!self::enabled()) {
throw new DomainException('医师电子签署认证尚未启用');
}
return ['doctor_id' => $actor, 'environment' => (string) Config::get('esign.environment', 'sandbox'),
'app_id' => (string) Config::get('esign.app_id', '')];
}
private static function snapshot(array $scope, bool $lock = false, string $flowTable = self::IDENTITY_FLOW_TABLE): array
{
$actor = $scope['doctor_id'];
$name = trim((string) Db::name('admin')->where('id', $actor)->where('disable', 0)
->whereNull('delete_time')->lock($lock)->value('name'));
$doctor = $actor > 0 && Db::name('admin_role')->where('admin_id', $actor)
->where('role_id', self::DOCTOR_ROLE_ID)->lock($lock)->value('admin_id');
if ($name === '' || (!$doctor && !(PrescriptionReviewEsignService::enabled()
&& PrescriptionReviewEsignService::canEnrollReviewer($actor)))) {
throw new DomainException('仅当前医师本人可使用医师电子签署认证');
}
return [
'name' => PrescriptionEsignService::configuredSignerName(['doctor_name' => $name], $actor),
'account' => Db::name('doctor_esign_account')->where($scope)->lock($lock)->find(),
'flow' => Db::name($flowTable)->where($scope)->lock($lock)->find(),
'flow_table' => $flowTable,
];
}
private static function hasCurrentFlow(array $snapshot): bool
{
$flow = $snapshot['flow'];
return !empty($flow['flow_id']) && $flow['doctor_name'] === $snapshot['name']
&& $flow['account_id'] === ($snapshot['account']['account_id'] ?? '')
&& (int) $flow['flow_started_at'] + self::FLOW_LIFETIME > time();
}
private static function hasLease(?array $flow): bool
{
return !empty($flow['operation_token']) && (int) $flow['operation_expires_at'] > time();
}
private static function hasPendingQuickFlow(array $snapshot): bool
{
return $snapshot['account'] && self::hasCurrentFlow($snapshot)
&& (int) $snapshot['flow']['expires_at'] === 0
&& (int) $snapshot['flow']['flow_started_at'] + self::QUICK_LIFETIME > time();
}
private static function assertUnchanged(array $scope, array $snapshot, bool $lock = false): void
{
if (self::snapshot($scope, $lock, $snapshot['flow_table']) !== $snapshot) {
throw new DomainException(self::STATE_CHANGED);
}
}
private static function claim(array $scope, array $snapshot): string
{
$token = bin2hex(random_bytes(16));
// Quick-sign completion may make three sequential provider requests before committing.
$timeout = max(1, min(300, (int) Config::get('esign.timeout', 60)));
$claim = ['operation_token' => $token, 'operation_expires_at' => time() + 3 * $timeout + 30];
Db::transaction(static function () use ($scope, $snapshot, $claim): void {
self::assertUnchanged($scope, $snapshot, true);
$query = Db::name($snapshot['flow_table']);
if ($snapshot['flow']) {
$query->where($scope)->update($claim);
} else {
$query->insert($scope + $claim);
}
});
return $token;
}
private static function finish(array $scope, array $snapshot, string $token, ?array $nextFlow, ?string $newAccountId = null): void
{
Db::transaction(static function () use ($scope, $snapshot, $token, $nextFlow, $newAccountId): void {
$current = self::snapshot($scope, true, $snapshot['flow_table']);
if ($current['name'] !== $snapshot['name'] || $current['account'] !== $snapshot['account']
|| !self::hasLease($current['flow']) || $current['flow']['operation_token'] !== $token) {
throw new DomainException(self::STATE_CHANGED);
}
if ($newAccountId !== null) {
$owner = Db::name('doctor_esign_account')->where('environment', $scope['environment'])
->where('app_id', $scope['app_id'])->where('account_id', $newAccountId)->lock(true)->value('doctor_id');
if ($owner !== null) {
throw new DomainException('签署账号绑定冲突,请联系管理员核实');
}
Db::name('doctor_esign_account')->insert($scope + [
'account_id' => $newAccountId, 'doctor_name' => $snapshot['name'], 'create_time' => time(),
]);
}
$query = Db::name($snapshot['flow_table'])->where($scope)->where('operation_token', $token);
if ($nextFlow === null) {
$query->delete();
} else {
$query->update($nextFlow + ['operation_token' => '', 'operation_expires_at' => 0]);
}
});
}
private static function release(array $scope, array $snapshot, string $token): void
{
Db::name($snapshot['flow_table'])->where($scope)->where('operation_token', $token)
->update(['operation_token' => '', 'operation_expires_at' => 0]);
}
private static function mobileHash(array $scope, string $mobile): string
{
$secret = (string) Config::get('esign.app_secret', '');
if ($secret === '') {
throw new DomainException('医师认证配置不完整,请联系管理员');
}
return hash_hmac('sha256', json_encode(['doctor-enrollment', $scope, $mobile], JSON_THROW_ON_ERROR), $secret);
}
private static function validMobile(?string $mobile): bool
{
return $mobile !== null && preg_match('/^1[3-9][0-9]{9}$/D', $mobile) === 1;
}
private static function processing(bool $quick = false): array
{
return self::state('authenticating', '医师认证请求处理中,请稍后查询', 0, $quick);
}
private static function state(string $status, string $message, int $certExpiresAt = 0, bool $quickAuthorizing = false): array
{
return [
'enabled' => true, 'status' => $status, 'cert_expires_at' => $certExpiresAt, 'message' => $message,
'quicksign_enabled' => self::quickEnabled(), 'quicksign_expires_at' => 0, 'quicksign_authorizing' => $quickAuthorizing,
];
}
}
+280 -24
View File
@@ -11,9 +11,45 @@ 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)
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)
{
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
$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);
}
}
@@ -30,13 +66,16 @@ class EsignOutcomeUnknownException extends EsignProviderException
* 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.
* {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' => [
@@ -91,6 +130,10 @@ final class EsignClient
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'])
@@ -124,27 +167,58 @@ final class EsignClient
/** @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'];
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, 'startIdentity');
$this->requireText($accountId, $operation);
$person['sdkAccountId'] = $accountId;
}
$response = $this->identityJson('startIdentity', 'POST', '/v2/identity/auth/web/indivAuthUrl', [
$uneditable = ['name', 'certType'];
if (isset($person['certNo'])) {
$uneditable[] = 'certNo';
}
$response = $this->identityJson($operation, 'POST', '/v2/identity/auth/web/indivAuthUrl', [
'indivInfo' => $person,
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
'usageType' => $usageType,
'authType' => $authType,
'availableAuthTypes' => [$authType],
'configParams' => ['indivUneditableInfo' => $uneditable],
'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');
}
$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('startIdentity', 'AUTH_URL_INVALID');
throw new EsignProviderException($operation, 'AUTH_URL_INVALID');
}
return ['flow_id' => $data['flowId'], 'auth_url' => $url];
return ['flow_id' => $flowId, 'auth_url' => $url];
}
public function identityDetail(string $flowId): array
@@ -159,13 +233,125 @@ final class EsignClient
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)()) {
$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
@@ -194,6 +380,16 @@ final class EsignClient
/** @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');
@@ -205,7 +401,7 @@ final class EsignClient
$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]],
'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;
@@ -274,10 +470,15 @@ final class EsignClient
private function request(string $operation, string $method, string $url, array $headers, string $body, string $codeKey, bool $signing = false): array
{
try {
$response = ($this->transport)([
$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);
@@ -302,11 +503,56 @@ final class EsignClient
$this->fail($operation, 'RESPONSE_INVALID', $signing);
}
if ($data[$codeKey] !== 0) {
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey]);
$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) {
@@ -331,6 +577,13 @@ final class EsignClient
}
}
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) {
@@ -398,6 +651,9 @@ final class EsignClient
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']);
}
@@ -99,5 +99,10 @@ final class PrescriptionEsignPolicy
if ($forDispensing && ($evidence['environment'] ?? '') !== 'production') {
throw new DomainException('沙箱签署处方仅供测试,不能用于正式发药');
}
$issuedAt = (int) ($evidence['issued_at'] ?? 0);
if ($issuedAt > 0 && (($evidence['signature_time_source'] ?? '') !== 'tsa'
|| (int) ($evidence['signature_time'] ?? 0) < $issuedAt)) {
throw new DomainException('处方开具和签署时间的验签证据不完整');
}
}
}
File diff suppressed because it is too large Load Diff
@@ -6,7 +6,7 @@ namespace app\common\service\esign;
/** Deterministic, text based A4 prescription; fixed first-page signature area. */
final class PrescriptionPdf
{
public static function render(array $row, string $environment): string
public static function render(array $row, string $environment, int $issuedAt = 0, bool $review = false): string
{
$row = PrescriptionEsignPolicy::snapshot($row);
$lines = [];
@@ -32,6 +32,10 @@ final class PrescriptionPdf
};
$add('处方编号', $row['sn']);
$add('日期', $row['prescription_date']);
if ($issuedAt > 0) {
$time = (new \DateTimeImmutable('@' . $issuedAt))->setTimezone(new \DateTimeZone('Asia/Shanghai'));
$add('开具确认时间(北京时间)', $time->format('Y-m-d H:i:s'));
}
$add('患者', $row['patient_name'] . ' 性别:' . ($row['gender'] === '1' ? '男' : '女') . ' 年龄:' . $row['age']);
$add('联系电话', $row['phone']);
$add('门诊号', $row['visit_no']);
@@ -93,7 +97,10 @@ final class PrescriptionPdf
$stream .= "0.7 w 45 133 m 550 133 l S\n";
$stream .= self::text('开方医师:' . $row['doctor_name'], 45, 110, 12);
if ($index === 0) {
$stream .= self::text('医师电子签章', 420, 117, 11);
$stream .= self::text('医师电子签章', 420, 104, 11);
if ($review) {
$stream .= self::text('审核电子签章', 420, 59, 11);
}
}
$stream .= self::text('处方快照 SHA-256', 45, 58, 8);
$stream .= self::text(PrescriptionEsignPolicy::hash($row), 45, 44, 7);
@@ -0,0 +1,342 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use app\adminapi\logic\auth\AuthLogic;
use app\adminapi\logic\tcm\PrescriptionLogic;
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\common\model\tcm\PrescriptionOrder;
use DomainException;
use think\facade\Config;
use think\facade\Db;
final class PrescriptionReviewEsignService
{
public const ORDER_PERMISSION = 'tcm.prescriptionOrder/auditPrescription';
private const TABLE = 'prescription_review_esign';
private const VERIFY_LEASE_SECONDS = 360;
public static function enabled(): bool
{
return filter_var(Config::get('esign.review_enabled', false), FILTER_VALIDATE_BOOLEAN);
}
/** Recheck the live personnel record and grants, including for an existing binding. */
public static function reviewerAccess(int $actor): array
{
$admin = Db::name('admin')->where('id', $actor)->where('disable', 0)->whereNull('delete_time')
->field('id,name,root')->find();
if (!$admin) {
return [];
}
$admin['admin_id'] = $actor;
$admin['role_id'] = Db::name('admin_role')->where('admin_id', $actor)->column('role_id');
$admin['permissions'] = (int) $admin['root'] === 1 ? ['*'] : AuthLogic::getAuthByAdminId($actor);
if (!PrescriptionLogic::canAuditPrescription($actor, $admin)) {
return [];
}
return $admin;
}
public static function canEnrollReviewer(int $actor): bool
{
$admin = self::reviewerAccess($actor);
return $admin && self::hasGrant($admin, array_merge(PrescriptionLogic::AUDIT_PERMISSIONS, [self::ORDER_PERMISSION]));
}
private static function hasGrant(array $admin, array $grants): bool
{
return (int) ($admin['root'] ?? 0) === 1 || array_intersect($admin['permissions'] ?? [], $grants) !== [];
}
private static function review(int $id): ?array
{
return Db::name(self::TABLE)->where('prescription_id', $id)->find() ?: null;
}
private static function path(array $doctor): string
{
return $doctor['prescription_id'] . '-' . $doctor['snapshot_hash'] . '/review-signed.pdf';
}
/** Called under the same prescription lock as approval or dispatch. */
public static function assertVerified(array $row, array $doctor, ?int $actor): void
{
// Previously approved single-signature records retain their archived evidence.
if (empty($doctor['review_required']) && !($actor !== null && self::enabled())) {
return;
}
$review = self::review((int) $row['id']);
if (!self::hasVerifiedReview($doctor, $review)) {
throw new DomainException('请由另一位有审核权限的人员完成处方审核电子签署');
}
if ($actor !== null && ($actor !== (int) $review['reviewer_id'] || !self::canEnrollReviewer($actor))) {
throw new DomainException('请由已签署此处方且仍有审核权限的审核人本人提交审核');
}
PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
}
private static function hasVerifiedReview(array $doctor, ?array $review): bool
{
return $review && $review['state'] === 'signed' && (int) $review['reviewer_id'] > 0
&& (int) $review['reviewer_id'] !== (int) $doctor['doctor_id']
&& $review['account_id'] !== '' && $review['account_id'] !== $doctor['account_id']
&& $review['environment'] === $doctor['environment'] && $review['app_id'] === $doctor['app_id']
&& hash_equals($doctor['signed_hash'], $review['doctor_pdf_hash'])
&& $review['sign_service_id'] !== '' && $review['signed_hash'] !== ''
&& (int) $review['signature_time'] > 0
&& (int) $review['signature_time'] >= (int) $doctor['signature_time'];
}
public static function describe(?array $doctor): array
{
if (empty($doctor['review_required']) || !($review = self::review((int) $doctor['prescription_id']))
|| !self::hasVerifiedReview($doctor, $review)) {
return [];
}
return ['review_signer_name' => $review['signer_name'], 'review_signature_time' => (int) $review['signature_time']];
}
public static function download(array $doctor): ?array
{
if (empty($doctor['review_required'])) {
return null;
}
$review = self::review((int) $doctor['prescription_id']);
if (!self::hasVerifiedReview($doctor, $review)) {
return null;
}
$pdf = PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
return ['filename' => 'prescription-' . $doctor['prescription_id'] . '-dual-signed.pdf',
'sha256' => $review['signed_hash'], 'content_base64' => base64_encode($pdf)];
}
public static function status(int $id, int $orderId, int $actor, array $adminInfo): array
{
$context = self::context($id, $orderId, $actor, $adminInfo);
return self::describeContext($context, $actor);
}
private static function context(int $id, int $orderId, int $actor, array $adminInfo, bool $lock = false): array
{
$order = $orderId > 0 ? PrescriptionOrder::where('id', $orderId)->whereNull('delete_time')->lock($lock)->find() : null;
if ($orderId > 0 && (!$order || (int) $order->prescription_id !== $id
|| !PrescriptionOrderLogic::canAccessOrder($order, $actor, $adminInfo))) {
throw new DomainException('业务订单不存在或无权查看');
}
$row = Db::name('tcm_prescription')->where('id', $id)->whereNull('delete_time')->lock($lock)->find();
if (!$row || (!$order && !PrescriptionLogic::canViewPrescription($row, $actor, $adminInfo))) {
throw new DomainException('处方不存在或无权查看');
}
$doctor = empty($row['esign_required']) ? null : Db::name('prescription_esign')->where('prescription_id', $id)->find();
$required = !empty($row['esign_required']) && (self::enabled() || !empty($doctor['review_required']));
$review = $required && !empty($doctor['review_required']) ? self::review($id) : null;
$pending = empty($row['void_status']) && ($order
? (int) $order->prescription_audit_status === 0 && !in_array((int) $order->fulfillment_status, [3, 4], true)
: (int) $row['audit_status'] === 0);
$reviewer = $required && $pending ? self::reviewerAccess($actor) : [];
$grants = $order ? [self::ORDER_PERMISSION] : PrescriptionLogic::AUDIT_PERMISSIONS;
return ['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required,
'can_audit' => $pending && $reviewer && self::hasGrant($reviewer, $grants),
'reviewer' => $reviewer];
}
private static function describeContext(array $context, int $actor): array
{
['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required, 'can_audit' => $canAudit,
'reviewer' => $reviewer] = $context;
$differentPerson = $actor !== (int) $row['creator_id'];
$signed = $doctor && self::hasVerifiedReview($doctor, $review);
$own = (int) ($review['reviewer_id'] ?? 0) === $actor;
$active = $doctor && PrescriptionEsignService::matchesEnvironment($doctor);
$state = (string) ($review['state'] ?? 'pending');
$canWork = $canAudit && $differentPerson && $active && self::enabled()
&& DoctorEsignIdentityService::quickEnabled() && ($row['esign_status'] ?? '') === 'signed';
$account = $canWork ? PrescriptionEsignService::account($actor) : null;
$stale = time() - (int) ($review['update_time'] ?? 0) >= self::VERIFY_LEASE_SECONDS;
$canRetry = $canAudit && $own && $active && PrescriptionEsignService::enabled() && !empty($review['signed_hash'])
&& ($state === 'uncertain' || (in_array($state, ['signing', 'verifying'], true) && $stale));
$message = match (true) {
!$required => '',
$signed => $own ? '审核签章已验签,可以提交通过。' : '请由已签署此处方的审核人本人提交审核。',
!$differentPerson => '请切换到另一位有权限的审核人账号。',
!$canAudit => '当前账号或处方状态不允许审核签署。',
($row['esign_status'] ?? '') !== 'signed' => '请开方医生先完成电子签署。',
$state === 'uncertain' => (string) $review['error_message'],
in_array($state, ['signing', 'verifying'], true) && !$stale => '正在处理审核签署,请稍后刷新。',
in_array($state, ['signing', 'verifying'], true) => '审核签署结果待核实,请查询状态或重试验签。',
!$canWork => '当前签署环境或快捷签配置不可用。',
!$account => '请先完成审核人本人的实名和快捷签授权。',
default => (string) (($review['error_message'] ?? '') ?: '核对处方后,请审核人本人确认追加签章。'),
};
return [
'required' => $required, 'state' => $signed ? 'signed' : $state,
'can_confirm' => $canWork && $account !== null && !$signed && in_array($state, ['pending', 'failed'], true),
'can_retry_verify' => $canRetry, 'can_approve' => !$required || ($signed && $own && $canAudit),
'can_setup' => $canWork,
'actor_id' => $actor, 'actor_name' => (string) ($account['doctor_name'] ?? $reviewer['name'] ?? ''),
'signer_name' => $signed ? $review['signer_name'] : '',
'signature_time' => $signed ? (int) $review['signature_time'] : 0,
'message' => $message,
];
}
public static function confirm(int $id, int $orderId, int $actor, array $adminInfo, bool $verifyOnly): array
{
$client = new EsignClient();
$context = self::context($id, $orderId, $actor, $adminInfo);
$status = self::describeContext($context, $actor);
$doctor = $context['doctor'];
if ($status['required'] && $status['can_approve']) {
return $status;
}
if (!($verifyOnly ? $status['can_retry_verify'] : $status['can_confirm'])) {
throw new DomainException($status['message'] ?: '当前处方无需审核签署');
}
PrescriptionEsignPolicy::assertSigned($context['row'], $doctor);
$source = PrescriptionEsignService::readPdf($doctor['signed_path'], $doctor['signed_hash']);
$token = bin2hex(random_bytes(16));
if ($verifyOnly) {
$newProof = [];
} else {
$account = PrescriptionEsignService::account($actor);
if (!$account || $account['account_id'] === $doctor['account_id']) {
throw new DomainException('审核人必须使用自己的签署账号,并与开方医生不同');
}
$name = (string) $account['doctor_name'];
$accountId = (string) $account['account_id'];
$doctorName = ($doctor['signer_name'] ?? '') ?: (string) $context['row']['doctor_name'];
$before = self::doctorSignature($client->verifyPdf($source), $doctorName, (int) $doctor['signature_time']);
$certificate = self::certificateKey($client->certificateIdentity($accountId));
if ($certificate === $before['certificate']) {
throw new DomainException('审核证书必须与开方医生的证书不同');
}
$seal = $client->createSeal($accountId);
// Verify consent and certificate validity immediately before taking the signing lease.
$flow = DoctorEsignIdentityService::quickAuthorization($actor, $name, $accountId);
$newProof = [
'reviewer_id' => $actor, 'signer_name' => $name, 'account_id' => $accountId,
'environment' => $doctor['environment'], 'app_id' => $doctor['app_id'],
'reviewer_certificate' => $certificate, 'doctor_signature' => $before['key'],
'doctor_pdf_hash' => $doctor['signed_hash'], 'confirmed_at' => time(),
'signed_hash' => '', 'signature_time' => 0, 'sign_service_id' => '',
];
}
$work = Db::transaction(static function () use ($id, $orderId, $actor, $adminInfo, $verifyOnly, $doctor, $newProof, $token): array {
$current = self::context($id, $orderId, $actor, $adminInfo, true);
$checked = self::describeContext($current, $actor);
if (!($verifyOnly ? $checked['can_retry_verify'] : $checked['can_confirm'])
|| $current['doctor']['signed_hash'] !== $doctor['signed_hash']) {
throw new DomainException('处方或审核签署状态已变化,请刷新');
}
PrescriptionEsignPolicy::assertSigned($current['row'], $current['doctor']);
if (!$verifyOnly && (PrescriptionEsignService::account($actor)['account_id'] ?? '') !== $newProof['account_id']) {
throw new DomainException('审核签署账号已变化,请重新确认');
}
$data = $newProof + ['state' => $verifyOnly ? 'verifying' : 'signing', 'operation_token' => $token,
'update_time' => time(), 'error_message' => ''];
if ($current['review']) {
Db::name(self::TABLE)->where('prescription_id', $id)->update($data);
} else {
Db::name(self::TABLE)->insert($data + ['prescription_id' => $id]);
}
if (empty($current['doctor']['review_required'])) {
Db::name('prescription_esign')->where('prescription_id', $id)->update(['review_required' => 1]);
}
return $data + ($current['review'] ?? []);
});
$received = $verifyOnly;
try {
if ($verifyOnly) {
$dual = PrescriptionEsignService::readPdf(self::path($doctor), $work['signed_hash']);
} else {
$signed = $client->signReviewPdf($accountId, $flow, $seal, $source, 'prescription-' . $id . '.pdf');
$received = true;
self::save($id, $token, ['sign_service_id' => $signed['sign_service_id']]);
$dual = $signed['pdf'];
PrescriptionEsignService::writePdf(self::path($doctor), $dual);
self::save($id, $token, ['signed_hash' => hash('sha256', $dual), 'state' => 'verifying']);
}
$time = self::verifyReview($source, $dual, $client->verifyPdf($dual), $doctor, $work);
self::save($id, $token, ['state' => 'signed', 'signature_time' => $time, 'error_message' => '']);
} catch (\Throwable $error) {
$definiteRejection = !$received && $error instanceof EsignProviderException && !($error instanceof EsignOutcomeUnknownException);
$details = $definiteRejection || $error instanceof DomainException ? $error->getMessage()
: '审核签署结果待核实,请刷新状态或重试验签';
$fields = ['state' => $definiteRejection ? 'failed' : 'uncertain', 'error_message' => mb_substr($details, 0, 240)];
if ($error instanceof EsignOutcomeUnknownException && $error->signServiceId !== null) {
$fields['sign_service_id'] = $error->signServiceId;
}
self::save($id, $token, $fields);
}
return self::status($id, $orderId, $actor, $adminInfo);
}
private static function save(int $id, string $token, array $fields): void
{
// One lease protects any provider request. Only verification can resume an archived result.
Db::name(self::TABLE)->where('prescription_id', $id)->where('operation_token', $token)
->update($fields + ['update_time' => time()]);
}
private static function certificateKey(array $cert): string
{
$issuer = trim((string) ($cert['issuerCN'] ?? ''));
$serial = ltrim(strtolower(trim((string) ($cert['sn'] ?? ''))), '0');
if ($issuer === '' || !preg_match('/^[a-f0-9]+$/D', $serial)) {
throw new DomainException('e签宝未返回可核对的签署证书信息');
}
return hash('sha256', $issuer . "\0" . $serial);
}
private static function signature(array $entry): array
{
$signature = $entry['signature'] ?? [];
$cert = $entry['cert'] ?? [];
$field = (string) ($signature['signatureName'] ?? '');
$timing = PrescriptionEsignService::verifiedSigningTime($signature);
if (($signature['validate'] ?? null) !== true || $field === '' || ($timing['signature_time_source'] ?? '') !== 'tsa') {
throw new DomainException('原件签章或可信时间戳未通过核验');
}
$name = (string) ($cert['cn'] ?? '');
$time = $timing['signature_time'];
$certificate = self::certificateKey($cert);
$key = hash('sha256', json_encode([$field, $certificate, $name, $time], JSON_THROW_ON_ERROR));
return compact('field', 'name', 'time', 'certificate', 'key');
}
private static function doctorSignature(array $verified, string $doctorName, int $recordedTime): array
{
$entries = $verified['signatures'] ?? [];
if (count($entries) !== 1 || $doctorName === '') {
throw new DomainException('开方原件须有且仅有一枚医生签章');
}
$signature = self::signature($entries[0]);
if ($signature['name'] !== $doctorName || ($recordedTime > 0 && $signature['time'] !== $recordedTime)) {
throw new DomainException('医生签章与归档签署记录不一致');
}
return $signature;
}
public static function verifyReview(string $source, string $dual, array $verified, array $doctor, array $proof): int
{
if (strlen($dual) <= strlen($source) || !str_starts_with($dual, $source)) {
throw new DomainException('双签原件未保留医生已签的原始文档,请联系管理员');
}
$entries = $verified['signatures'] ?? [];
if (count($entries) !== 2) {
throw new DomainException('双签原件须包含两枚有效签章');
}
[$first, $second] = array_map([self::class, 'signature'], $entries);
[$original, $review] = $first['key'] === $proof['doctor_signature'] ? [$first, $second] : [$second, $first];
if ($original['key'] !== $proof['doctor_signature'] || $original['field'] === $review['field']
|| $original['certificate'] === $review['certificate']
|| $review['certificate'] !== $proof['reviewer_certificate'] || $review['name'] !== $proof['signer_name']
|| $review['time'] < max((int) $doctor['issued_at'], $original['time'])) {
throw new DomainException('医生与审核人签章、证书或时间顺序未通过核验');
}
return $review['time'];
}
}
@@ -75,7 +75,7 @@ final class LockedPharmacySnapshotMutation
foreach ($orders as $order) {
$claim = Db::name('pharmacy_submission_claim')
->where('prescription_order_id', (int) $order['id'])
->where('source_revision', 1)
->order('source_revision', 'desc')
->lock(true)
->find();
PharmacyRemoteSnapshotPolicy::assertMutable($order, $claim ?: null);