Files
zyt/server/app/common/service/esign/PrescriptionEsignService.php
T
2026-11-26 15:46:20 +08:00

1216 lines
64 KiB
PHP

<?php
declare(strict_types=1);
namespace app\common\service\esign;
use app\adminapi\logic\tcm\PrescriptionLogic;
use app\common\model\auth\Admin;
use app\common\model\tcm\Prescription;
use DateTimeImmutable;
use DateTimeZone;
use DomainException;
use think\facade\Config;
use think\facade\Db;
/** The database is authoritative; browser redirects never complete a signature. */
final class PrescriptionEsignService
{
private const VERIFICATION_LEASE_SECONDS = 360; // Longer than the maximum provider timeout.
private const ISSUANCE_DISPATCH_DELAY_SECONDS = 2;
private const SMS_SEND_COOLDOWN_SECONDS = 60;
private const SMS_CODE_SECONDS = 900;
private const SMS_MAX_ATTEMPTS = 3;
private const REVIEW_SEAL_MAX_BYTES = 128 * 1024;
public static function enabled(): bool
{
return PrescriptionCaSigningSettings::override()
?? filter_var(Config::get('esign.enabled', false), FILTER_VALIDATE_BOOLEAN);
}
public static function capability(): array
{
$enabled = self::enabled();
return ['enabled' => $enabled, 'environment' => (string) Config::get('esign.environment', 'sandbox')]
+ (PrescriptionReviewEsignService::enabled() ? ['review_enabled' => true] : [])
+ ($enabled && self::usesDoctorQuick() ? ['verification_method' => 'quick'] : []);
}
public static function requiresSignature(array $row, bool $enabled): bool
{
return !empty($row['esign_required']) || ($enabled && ($row['esign_status'] ?? 'legacy') === 'legacy'
&& PrescriptionEsignPolicy::isPendingReview($row));
}
public static function status(int $id, int $actor, array $adminInfo): array
{
$model = Prescription::find($id);
if (!$model || !PrescriptionLogic::canViewPrescription($model, $actor, $adminInfo)) {
throw new DomainException('处方不存在或无权查看');
}
$row = $model->toArray();
return self::describe($row, $actor, true, (int) $row['creator_id'] === $actor
&& PrescriptionLogic::canSubmitForReview($actor, $adminInfo));
}
/** Read-only polling: never bind an account, change state or consume signing authorization. */
public static function identityStatus(int $id, int $actor, array $adminInfo): array
{
$read = static function () use ($id, $actor): array {
$row = self::lockSigner($id, $actor);
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
if ($e) {
self::assertEnvironment($e);
if ((int) $e['doctor_id'] !== $actor) {
throw new DomainException('处方签署人与冻结记录不一致');
}
}
return [$row, $e, self::describe($row, $actor)];
};
[$row, $e, $state] = Db::transaction($read);
$unavailable = ['identity_status' => 'UNAVAILABLE', 'can_complete' => false, 'identity_details_required' => false];
if (!$state['can_resume_identity']) {
return $state + $unavailable;
}
$client = new EsignClient();
$signerName = self::signerName($row, $e);
$sms = self::isSms($e);
$quick = self::isQuick($e);
$quickBlock = null;
$detailsMissing = false;
if ($quick) {
$accountId = self::account($actor)['account_id'] ?? '';
try {
$grant = DoctorEsignIdentityService::quickAuthorization($actor, $signerName, $accountId);
$identityState = $grant === $e['flow_id'] && $accountId === $e['account_id'] ? 'SUCCESS' : 'EXPIRED';
} catch (DoctorEsignIdentityRequired | DoctorEsignAuthorizationRequired $error) {
$identityState = 'EXPIRED';
$quickBlock = $error;
}
} elseif ($sms) {
$identityState = self::smsVerificationState($e);
} else {
$identity = $client->identityDetail($e['flow_id']);
self::assertIdentityFlow($identity, $e);
$identityState = $identity['status'] ?? '';
if (!in_array($identityState, ['INIT', 'ING', 'SUCCESS', 'FAIL'], true)) {
throw new DomainException('核身状态尚未确认,请重新查询');
}
$detailsMissing = $identityState === 'SUCCESS' && self::identityPerson($identity, $signerName) === null;
unset($identity); // Do not expose names, document numbers or supplier data to polling clients.
}
if ($identityState === 'SUCCESS' && !$quick) {
try {
$client->checkWillingness($e['flow_id']);
} catch (EsignProviderException $error) {
if ($error->providerCode !== 'WILLINGNESS_INVALID') {
throw new DomainException('暂时无法确认签署授权,请重新检查核身状态');
}
$identityState = 'EXPIRED';
}
}
// The prescription or flow may have changed while the network request was pending.
[$currentRow, $current, $currentState] = Db::transaction($read);
if (!$currentState['can_resume_identity']
|| !$current || $current['flow_id'] !== $e['flow_id']
|| $current['operation_token'] !== $e['operation_token']
|| !hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($currentRow))) {
return $currentState + $unavailable;
}
$account = self::account($actor);
if (!$quick || $identityState === 'SUCCESS') {
self::assertAccountBinding($signerName, $current, $account);
}
if (in_array($identityState, ['FAIL', 'EXPIRED'], true)) {
unset($currentState['auth_url']);
if ($quick) {
$currentState['message'] = '快捷签授权已更新,请重新准备签署';
$currentState = self::withQuickBlock($currentState, $quickBlock);
} else {
$currentState['message'] = $sms ? '本次短信验证已失效,请重新获取验证码'
: ($identityState === 'FAIL' ? '核身未通过,请重新核身' : '本次签署授权已失效,请重新核身');
}
}
$detailsRequired = $identityState === 'SUCCESS' && $detailsMissing && $account === null;
return $currentState + ['identity_status' => $identityState,
'can_complete' => $identityState === 'SUCCESS' && !$detailsRequired,
'identity_details_required' => $detailsRequired];
}
public static function describe(array $row, int $actor, bool $includeDetails = false, bool $maySubmitForReview = false): array
{
$enabled = self::enabled();
$enrolled = !empty($row['esign_required']);
$required = self::requiresSignature($row, $enabled);
$e = $enrolled ? Db::name('prescription_esign')->where('prescription_id', (int) $row['id'])->find() : null;
$state = $enrolled ? (string) ($row['esign_status'] ?? 'pending') : ($required ? 'pending' : 'legacy');
$voided = !empty($row['void_status']) || !empty($row['delete_time']);
if ($voided && $required) {
$state = 'voided';
}
$sameApp = !$e || self::matchesEnvironment($e);
$isCreator = $actor > 0 && (int) ($row['creator_id'] ?? 0) === $actor;
$awaitingUpload = PrescriptionEsignPolicy::isAwaitingUpload($row);
$canSign = $enabled && $required && !$voided && $sameApp && $isCreator && !empty($row['review_submitted_at'])
&& self::hasUploadContent($row, $required)
&& (!$e || (int) $e['doctor_id'] === $actor);
$rawState = $state;
$quick = self::usesDoctorQuick();
$sms = !$quick && (self::isSms($e ?: []) || ((empty($e['flow_id']) || self::isQuick($e ?: [])) && self::usesDoctorSms()));
$activeVerification = $rawState === 'verifying' && !self::archiveVerificationAvailable($rawState, $e ?: []);
$message = (string) ($e['error_message'] ?? '');
if ($state === 'signing' && time() - (int) ($e['started_at'] ?? time()) > 180) {
// Never release an expired signing lease to another sign request.
$state = 'uncertain';
$message = '签署结果待核实,请联系管理员核对签署流水,不要重复签署';
}
if ($rawState === 'verifying') {
$state = 'uncertain';
$message = $activeVerification ? '正在核验签署原件,请稍后刷新' : '签署原件待核验,请重试验签';
}
if (!$sameApp) {
$message = '此处方属于其他签署环境或应用,请恢复对应配置后处理';
}
if ($e && !$voided && !hash_equals((string) $e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
$state = 'uncertain';
$message = '处方与冻结原文不一致,请管理员核实';
$canSign = false;
}
if ($state === 'preparing') {
$lease = self::isSms($e ?: []) || self::isQuick($e ?: []) ? self::VERIFICATION_LEASE_SECONDS : 90;
$canSign = $canSign && time() - (int) ($e['started_at'] ?? time()) >= $lease;
$state = 'authenticating';
$message = $quick ? '正在检查快捷签授权,请稍后刷新'
: ($sms ? '正在发送签署验证码,请稍后刷新' : '正在准备认证链接,请稍后刷新');
}
if ($rawState === 'sms_verifying') {
$canSign = $canSign && time() - (int) ($e['started_at'] ?? time()) >= self::VERIFICATION_LEASE_SECONDS;
$state = 'authenticating';
$message = $canSign ? '验证码校验结果未能确认,请重新获取验证码' : '正在校验验证码,请稍后刷新';
}
$canResumeIdentity = $canSign && $quick === self::isQuick($e ?: []) && self::hasRetainedIdentity($rawState, $e ?: []);
$canRetryVerify = $canSign && $e && self::archiveVerificationAvailable($rawState, $e)
&& self::hasArchivedSignature($row, $e) && is_file(self::filePath($e['signed_path']));
if ($canRetryVerify && $rawState === 'signing') {
$message = '签署原件待核验,请重试验签';
}
if ($message === '' && $required && !$voided && $state !== 'signed') {
if (!$enabled) {
$message = '电子签署尚未启用,请联系管理员';
} elseif (!self::hasUploadContent($row, $required)) {
$message = '请开方医生先补全处方药品和临床诊断并保存';
} elseif ($awaitingUpload) {
$message = '请开方医生先上传处方,再进行电子签署';
} elseif (!$isCreator) {
$message = '请开方医生本人完成电子签署';
}
}
$labels = ['legacy' => '历史手写签名', 'pending' => '待电子签署', 'authenticating' => '待医生核身',
'signing' => '签署中', 'signed' => '已电子签署', 'failed' => '签署未完成', 'uncertain' => '签署结果待核实', 'voided' => '已作废'];
$out = [
'enabled' => $enabled, 'required' => $required, 'status' => $state,
'review_required' => !empty($e['review_required']) || ($required && !$voided
&& in_array($row['audit_status'] ?? null, [0, '0'], true) && PrescriptionReviewEsignService::enabled()),
'status_label' => $labels[$state] ?? '待电子签署',
'environment' => $e['environment'] ?? Config::get('esign.environment', 'sandbox'),
'can_sign' => $canSign && !self::hasSignatureEvidence($e ?: [])
&& in_array($state, ['pending', 'authenticating', 'failed'], true),
'can_resume_identity' => $canResumeIdentity, 'can_retry_verify' => $canRetryVerify,
'can_download' => !empty($e['signed_path']) && !empty($e['signed_at']),
'message' => $message, 'signed_at' => (int) ($e['signed_at'] ?? 0),
'signature_time' => (int) ($e['signature_time'] ?? 0),
'signature_time_source' => (string) ($e['signature_time_source'] ?? ''),
'issued_at' => (int) ($e['issued_at'] ?? 0),
'prescription_date' => (string) ($row['prescription_date'] ?? ''),
'review_submitted_at' => (int) ($row['review_submitted_at'] ?? 0),
'awaiting_upload' => $awaitingUpload,
'can_submit_for_review' => $maySubmitForReview && $isCreator && $awaitingUpload
&& self::hasUploadContent($row, $required),
'can_review_prescription' => PrescriptionEsignPolicy::isPendingReview($row) && self::canReview($row, $e ?: null),
];
if ($canResumeIdentity && !$quick && !empty($e['auth_url'])) {
$out['auth_url'] = $e['auth_url'];
}
if (($quick || $sms) && $out['can_sign']) {
$out['verification_method'] = $quick ? 'quick' : 'sms';
if ($sms) {
$out['sms_sent'] = $canResumeIdentity && self::isSms($e ?: []);
$out['doctor_identity_required'] = !empty($e['doctor_setup_required']) || self::account($actor) === null;
} else {
// A previous prescription failure must never shadow a later, account-level grant.
$out['doctor_identity_required'] = self::account($actor) === null;
$out['signing_authorization_required'] = false;
}
if ($state === 'authenticating') {
$out['status_label'] = $quick ? '待确认签名' : '待确认签署意愿';
}
}
if ($includeDetails && $out['can_download']) {
$out['doctor_signer_name'] = self::signerName($row, $e);
}
return $out + PrescriptionReviewEsignService::describe($e ?: null, $includeDetails ? $row : null);
}
public static function hasUploadContent(array $row, bool $required): bool
{
return PrescriptionEsignPolicy::hasPrescriptionContent($row)
&& (!$required || trim((string) ($row['clinical_diagnosis'] ?? '')) !== '');
}
public static function canReview(array $row, ?array $evidence = null): bool
{
try {
self::assertReviewReady($row, $evidence);
return true;
} catch (DomainException | \JsonException) {
return false;
}
}
public static function assertReviewReady(array $row, ?array $evidence = null): void
{
PrescriptionEsignPolicy::assertReviewReady($row);
if (!PrescriptionEsignPolicy::isPendingReview($row) || !self::requiresSignature($row, self::enabled())) {
return;
}
if ($evidence === null && !empty($row['esign_required']) && ($row['esign_status'] ?? '') === 'signed') {
$evidence = Db::name('prescription_esign')->where('prescription_id', (int) $row['id'])->find();
}
self::assertDoctorSignature($row, $evidence);
}
private static function assertDoctorSignature(array $row, ?array $evidence, bool $forDispensing = false): void
{
// Apply the active requirement without enrolling the prescription during review.
$row['esign_required'] = 1;
PrescriptionEsignPolicy::assertSigned($row, $evidence, $forDispensing);
self::readPdf((string) $evidence['signed_path'], (string) $evidence['signed_hash']);
}
// Audit and dispatch callers retain the prescription lock through their state write.
public static function assertSignedById(int $id, bool $forDispensing = false, ?int $reviewer = null, bool $orderApproval = false): void
{
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
if (!$row) {
throw new DomainException('处方不存在');
}
if ($forDispensing && (!empty($row['void_status']) || !empty($row['delete_time']))) {
throw new DomainException('处方已作废或删除,不能用于履约');
}
if ($reviewer !== null) {
PrescriptionEsignPolicy::assertReviewReady($row);
}
if (!self::requiresSignature($row, self::enabled())) {
return;
}
$e = empty($row['esign_required']) ? null : Db::name('prescription_esign')->where('prescription_id', $id)->find();
self::assertDoctorSignature($row, $e ?: null, $forDispensing);
if ($forDispensing || $reviewer !== null) {
PrescriptionReviewEsignService::assertVerified($row, $e, $reviewer, $orderApproval);
}
}
public static function isSandboxTest(int $id): bool
{
return Db::name('prescription_esign')->where('prescription_id', $id)->value('environment') === 'sandbox';
}
public static function start(int $id, int $actor, array $adminInfo, bool $restartIdentity = false): array
{
$client = new EsignClient();
$client->assertConfigured();
$token = bin2hex(random_bytes(16));
$work = Db::transaction(static function () use ($id, $actor, $token, $restartIdentity): ?array {
$row = self::lockSigner($id, $actor);
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
$state = empty($row['esign_required']) ? 'pending' : $row['esign_status'];
$quick = self::usesDoctorQuick();
$sms = !$quick && (self::isSms($e ?: []) || self::usesDoctorSms());
if (!in_array($state, ['pending', 'preparing', 'authenticating', 'failed', 'sms_verifying'], true)) {
return null;
}
if ($e) {
if ((int) $e['doctor_id'] !== $actor) {
throw new DomainException('处方签署人与冻结记录不一致');
}
self::assertEnvironment($e);
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
throw new DomainException('处方内容与签署原文不一致,请作废后重新开方');
}
if (self::hasSignatureEvidence($e)) {
return null;
}
if (!$restartIdentity && $quick === self::isQuick($e) && self::hasRetainedIdentity($state, $e)) {
return null;
}
$lease = self::isSms($e) || self::isQuick($e) ? self::VERIFICATION_LEASE_SECONDS : 90;
if (in_array($state, ['preparing', 'sms_verifying'], true) && time() - (int) $e['started_at'] < $lease) {
return null;
}
}
$signerName = self::configuredSignerName($row, $actor);
if ($sms) {
// Serialize per-doctor SMS cooldown reservations across prescriptions.
Db::name('admin')->where('id', $actor)->lock(true)->find();
$lastSend = Db::name('prescription_esign')->where('doctor_id', $actor)
->where('environment', Config::get('esign.environment', 'sandbox'))
->where('app_id', (string) Config::get('esign.app_id', ''))
->order('sms_sent_at', 'desc')->lock(true)->value('sms_sent_at');
if (time() - (int) $lastSend < self::SMS_SEND_COOLDOWN_SECONDS) {
throw new DomainException('验证码刚刚已请求,请稍候再试');
}
}
if (!$e) {
$name = trim((string) Admin::where('id', $actor)->value('name'));
if ($name === '' || $name !== trim((string) $row['doctor_name'])) {
throw new DomainException('医师姓名与当前账号不一致,请修正处方后签署');
}
$herbs = is_string($row['herbs']) ? json_decode($row['herbs'], true) : $row['herbs'];
if (empty($herbs) || trim((string) $row['clinical_diagnosis']) === '') {
throw new DomainException('请先补全处方药品和临床诊断');
}
$snapshotHash = PrescriptionEsignPolicy::hash($row);
$reviewRequired = PrescriptionReviewEsignService::enabled();
$pdf = PrescriptionPdf::render($row, (string) Config::get('esign.environment', 'sandbox'), 0, $reviewRequired);
$path = $id . '-' . $snapshotHash . '/source.pdf';
self::writePdf($path, $pdf);
$e = [
'prescription_id' => $id, 'doctor_id' => $actor,
'environment' => Config::get('esign.environment', 'sandbox'),
...($reviewRequired ? ['review_required' => 1] : []),
'app_id' => (string) Config::get('esign.app_id', ''),
'snapshot_hash' => $snapshotHash, 'source_hash' => hash('sha256', $pdf), 'source_path' => $path,
'create_time' => time(), 'update_time' => time(),
];
Db::name('prescription_esign')->insert($e);
}
$signerOverride = $signerName !== $row['doctor_name'] ? $signerName : '';
$updates = [
'operation_token' => $token, 'started_at' => time(), 'error_message' => '', 'update_time' => time(),
'flow_id' => '', 'auth_url' => '', 'account_id' => '',
];
if ($signerOverride !== '' || !empty($e['signer_name'])) {
$updates['signer_name'] = $signerOverride;
}
if ($quick || $sms || self::isQuick($e)) {
$updates += ['auth_method' => $quick ? 'quick' : ($sms ? 'sms' : ''),
'sms_sent_at' => $sms ? time() : (int) ($e['sms_sent_at'] ?? 0), 'sms_verified_at' => 0,
'sms_attempts' => 0, 'doctor_setup_required' => 0];
}
Db::name('prescription_esign')->where('prescription_id', $id)->update($updates);
Db::name('tcm_prescription')->where('id', $id)->update(['esign_required' => 1, 'esign_status' => 'preparing']);
return ['signer_name' => $signerName, 'sms' => $sms, 'quick' => $quick];
});
if ($work === null) {
return self::status($id, $actor, $adminInfo);
}
$quickBlock = null;
try {
$account = self::account($actor);
if ($account && $account['doctor_name'] !== $work['signer_name']) {
// 账号可能以药师审核身份绑定了另一实名,此时不能用该证书签署他人名下的处方
throw new DomainException('当前账号的签署实名为「' . $account['doctor_name'] . '」,与处方医师「'
. $work['signer_name'] . '」不一致,请使用医师本人账号开方并签署');
}
if ($work['quick']) {
$accountId = $account['account_id'] ?? '';
$proof = DoctorEsignIdentityService::quickAuthorization($actor, $work['signer_name'], $accountId);
self::finishOperation($id, $token, 'authenticating', ['flow_id' => $proof, 'account_id' => $accountId]);
return self::status($id, $actor, $adminInfo);
}
if ($work['sms']) {
$recipient = DoctorEsignIdentityService::willingnessRecipient($actor, $work['signer_name'], $account['account_id'] ?? '');
$flowId = $client->sendWillingnessCode($recipient['name'], $recipient['idNo'], $recipient['mobile']);
self::finishOperation($id, $token, 'authenticating', [
'flow_id' => $flowId, 'account_id' => $account['account_id'], 'sms_sent_at' => time(),
]);
return self::status($id, $actor, $adminInfo);
}
$auth = $client->startIdentity($work['signer_name'], 'prescription-' . $id, $account['account_id'] ?? null);
self::finishOperation($id, $token, 'authenticating', [
'flow_id' => $auth['flow_id'], 'auth_url' => $auth['auth_url'],
// Records whether this particular authentication was bound to an existing SDK account.
'account_id' => $account['account_id'] ?? '',
]);
} catch (\Throwable $e) {
$failure = ['error_message' => self::safeError($e)];
if ($work['quick'] && ($e instanceof DoctorEsignIdentityRequired || $e instanceof DoctorEsignAuthorizationRequired)) {
$quickBlock = $e;
} elseif ($e instanceof DoctorEsignIdentityRequired) {
$failure += ['doctor_setup_required' => 1, 'sms_sent_at' => 0];
}
self::finishOperation($id, $token, 'failed', $failure);
}
return self::withQuickBlock(self::status($id, $actor, $adminInfo), $quickBlock);
}
public static function verifyWillingness(int $id, int $actor, array $adminInfo, string $code): array
{
if (self::usesDoctorQuick()) {
throw new DomainException('请刷新处方,使用快捷签确认签名');
}
if (!preg_match('/^[0-9]{6}$/D', $code)) {
throw new DomainException('请输入收到的六位短信验证码');
}
$client = new EsignClient();
$client->assertConfigured();
$token = bin2hex(random_bytes(16));
$flow = Db::transaction(static function () use ($id, $actor, $token): ?string {
$row = self::lockSigner($id, $actor);
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
if (!$e || !self::isSms($e) || (int) $e['doctor_id'] !== $actor
|| !self::hasRetainedIdentity($row['esign_status'], $e)) {
throw new DomainException('请先获取本处方的签署验证码');
}
self::assertEnvironment($e);
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
throw new DomainException('处方内容已变化,请作废后重新开方');
}
self::assertAccountBinding(self::signerName($row, $e), $e, self::account($actor));
$state = self::smsVerificationState($e);
if ($state === 'SUCCESS') {
return null;
}
if ($state !== 'ING') {
throw new DomainException('本次短信验证已失效,请重新获取验证码');
}
self::writeOperation($row, 'sms_verifying', [
'operation_token' => $token, 'started_at' => time(),
'sms_attempts' => (int) $e['sms_attempts'] + 1,
], '');
return $e['flow_id'];
});
if ($flow !== null) {
try {
$client->verifyWillingnessCode($flow, $code);
} catch (\Throwable $error) {
$wrongCode = $error instanceof EsignProviderException && $error->providerCode === 'PROVIDER_30503002';
$message = $wrongCode ? '验证码不正确,请检查后重试' : '验证码校验未能完成,请重新获取验证码';
self::finishOperation($id, $token, 'authenticating', ['error_message' => $message]
+ ($wrongCode ? [] : ['sms_attempts' => self::SMS_MAX_ATTEMPTS]));
// Return the authoritative status so the client can immediately offer the appropriate retry.
return self::identityStatus($id, $actor, $adminInfo);
} finally {
unset($code);
}
self::finishOperation($id, $token, 'authenticating', ['sms_verified_at' => time(), 'error_message' => '']);
}
return self::identityStatus($id, $actor, $adminInfo);
}
public static function complete(int $id, int $actor, array $adminInfo, string $identityNumber = '', bool $verifyOnly = false): array
{
if ($verifyOnly) {
return self::retryVerification($id, $actor, $adminInfo);
}
$client = new EsignClient();
$client->assertConfigured();
$token = bin2hex(random_bytes(16));
$work = Db::transaction(static function () use ($id, $actor, $token): ?array {
$row = self::lockSigner($id, $actor);
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
if (!$e) {
throw new DomainException('请先发起电子签署');
}
if ((int) $e['doctor_id'] !== $actor) {
throw new DomainException('处方签署人与冻结记录不一致');
}
self::assertEnvironment($e);
if (in_array($row['esign_status'], ['signed', 'signing', 'uncertain', 'verifying', 'voided'], true)
|| self::hasSignatureEvidence($e)) {
return null;
}
if (!self::hasRetainedIdentity($row['esign_status'], $e)) {
throw new DomainException('请先完成医生核身认证');
}
if (self::usesDoctorQuick() !== self::isQuick($e)) {
throw new DomainException('签署方式已更新,请重新准备签署');
}
if (self::isSms($e) && self::smsVerificationState($e) !== 'SUCCESS') {
throw new DomainException('请先校验本处方的签署短信验证码');
}
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
throw new DomainException('处方内容已变化,请作废后重新开方');
}
Db::name('prescription_esign')->where('prescription_id', $id)->update([
'operation_token' => $token, 'started_at' => time(), 'error_message' => '', 'update_time' => time(),
]);
Db::name('tcm_prescription')->where('id', $id)->update(['esign_status' => 'signing']);
return ['row' => $row, 'evidence' => $e];
});
if ($work === null) {
return self::status($id, $actor, $adminInfo);
}
$attempted = false;
$signedReceived = false;
$archived = false;
$accountId = '';
$quickBlock = null;
try {
$row = $work['row'];
$e = $work['evidence'];
$signerName = self::signerName($row, $e);
if (self::isQuick($e)) {
self::assertQuickFlow($actor, $signerName, $e);
$accountId = $e['account_id'];
} elseif (self::isSms($e)) {
$account = self::account($actor);
self::assertAccountBinding($signerName, $e, $account);
$client->checkWillingness($e['flow_id']);
$accountId = $account['account_id'];
} else {
$identity = $client->identityDetail($e['flow_id']);
self::assertIdentityFlow($identity, $e);
if (($identity['status'] ?? '') !== 'SUCCESS') {
$failed = ($identity['status'] ?? '') === 'FAIL';
self::finishOperation($id, $token, $failed ? 'failed' : 'authenticating', [
'error_message' => $failed ? '核身未通过,请重新发起认证' : '尚未完成核身,请在认证页面完成后重试',
...($failed ? ['flow_id' => '', 'auth_url' => ''] : []),
]);
return self::status($id, $actor, $adminInfo);
}
$person = self::identityPerson($identity, $signerName);
$account = self::account($actor);
self::assertAccountBinding($signerName, $e, $account);
$client->checkWillingness($e['flow_id']);
if ($person === null && $account === null) {
$identityNumber = strtoupper(trim($identityNumber));
if (!self::validMainlandIdentityNumber($identityNumber)) {
// Missing/invalid local input consumes no SDK authorization and keeps the flow usable.
self::finishOperation($id, $token, 'authenticating', ['error_message' => $identityNumber === ''
? '核身已通过,请补充本次核身使用的身份证号码以绑定签署账号'
: '请输入本次核身使用的有效大陆身份证号码']);
$state = self::status($id, $actor, $adminInfo);
return $state + ['identity_status' => 'SUCCESS', 'can_complete' => false,
'identity_details_required' => $state['status'] === 'authenticating' && $state['can_sign']];
}
// addPerson verifies this transient input against identityAuthId; it is not identity proof itself.
$person = ['name' => $signerName, 'certNo' => $identityNumber];
}
if ($account) {
$accountId = $account['account_id'];
} else {
$accountId = $client->createPerson($person['name'], $person['certNo'], $e['flow_id']);
try {
Db::name('doctor_esign_account')->insert([
'doctor_id' => $actor, 'environment' => $e['environment'], 'app_id' => $e['app_id'],
'account_id' => $accountId, 'doctor_name' => $signerName, 'create_time' => time(),
]);
} catch (\Throwable $insertError) {
$existing = self::account($actor);
if (!$existing || $existing['account_id'] !== $accountId || $existing['doctor_name'] !== $signerName) {
throw new DomainException('签署账号绑定冲突,请联系管理员核实');
}
}
}
unset($person, $identity, $identityNumber); // Full identity document numbers are never persisted or logged.
}
self::finishOperation($id, $token, 'signing', ['account_id' => $accountId]);
$seal = $client->createSeal($accountId);
// Recheck after authentication: a prescription may have been voided meanwhile.
$lockSigningWork = static function () use ($id, $actor, $token, $accountId, $e, $signerName): array {
$currentRow = self::lockSigner($id, $actor);
$current = Db::name('prescription_esign')->where('prescription_id', $id)->find();
$boundAccount = self::account($actor);
if (!$current || !hash_equals($current['operation_token'], $token)
|| $currentRow['esign_status'] !== 'signing'
|| (int) $current['doctor_id'] !== $actor || self::signerName($currentRow, $current) !== $signerName
|| !self::matchesEnvironment($current) || $current['flow_id'] !== $e['flow_id']
|| !hash_equals($current['snapshot_hash'], PrescriptionEsignPolicy::hash($currentRow))
|| !$boundAccount || $boundAccount['account_id'] !== $accountId || $boundAccount['doctor_name'] !== $signerName) {
throw new DomainException('签署状态已变化,请刷新');
}
return [$currentRow, $current];
};
[$pdf, $issuedAt] = Db::transaction(static function () use ($id, $lockSigningWork): array {
[$currentRow, $current] = $lockSigningWork();
$pdf = self::readPdf($current['source_path'], $current['source_hash']);
$issuedAt = (int) ($current['issued_at'] ?? 0);
if ($issuedAt > 0) {
return [$pdf, $issuedAt];
}
// This is reached only after the doctor confirms signing and their willingness is verified.
$issuedAt = time();
$pdf = PrescriptionPdf::render($currentRow, $current['environment'], $issuedAt, !empty($current['review_required']));
$path = $id . '-' . $current['snapshot_hash'] . '/source-issued.pdf';
self::writePdf($path, $pdf);
Db::name('prescription_esign')->where('prescription_id', $id)->update([
'issued_at' => $issuedAt, 'source_hash' => hash('sha256', $pdf), 'source_path' => $path,
]);
return [$pdf, $issuedAt];
});
// Leave room for small TSA clock skew while keeping the exact issuance time in the PDF.
$delay = min(self::ISSUANCE_DISPATCH_DELAY_SECONDS, $issuedAt + self::ISSUANCE_DISPATCH_DELAY_SECONDS - microtime(true));
if ($delay > 0) {
$nanoseconds = (int) ceil($delay * 1_000_000_000);
$remaining = ['seconds' => intdiv($nanoseconds, 1_000_000_000), 'nanoseconds' => $nanoseconds % 1_000_000_000];
do {
$remaining = time_nanosleep($remaining['seconds'], $remaining['nanoseconds']);
} while (is_array($remaining));
if (!$remaining) {
throw new DomainException('签署暂未发送,请重新发起认证');
}
Db::transaction(static function () use ($lockSigningWork, $issuedAt, $pdf): void {
[, $current] = $lockSigningWork();
if ((int) ($current['issued_at'] ?? 0) !== $issuedAt
|| self::readPdf($current['source_path'], $current['source_hash']) !== $pdf) {
throw new DomainException('签署状态已变化,请刷新');
}
});
}
if (self::isQuick($e)) {
self::assertQuickFlow($actor, $signerName, $e);
Db::transaction($lockSigningWork);
}
$attempted = true;
$signed = $client->signPdf($accountId, $e['flow_id'], $seal, $pdf, 'prescription-' . $id . '.pdf');
$signedReceived = true;
// Save the supplier reference first: disk/archive failure must not lose a completed sign.
self::finishOperation($id, $token, 'signing', [
'sign_service_id' => $signed['sign_service_id'], 'account_id' => $accountId,
]);
$path = $id . '-' . $e['snapshot_hash'] . '/signed.pdf';
self::writePdf($path, $signed['pdf']);
// Persist the result before verification, so a verification outage cannot lose evidence.
$proof = ['signed_path' => $path, 'signed_hash' => hash('sha256', $signed['pdf']),
'sign_service_id' => $signed['sign_service_id'], 'account_id' => $accountId];
self::finishOperation($id, $token, 'signing', $proof);
$archived = true;
$verified = self::verifiedDoctorProof($client->verifyPdf($signed['pdf']), $signerName);
self::assertIssuedTime($issuedAt, $verified['timing']);
self::readPdf($path, $proof['signed_hash']);
self::finishOperation($id, $token, 'signed', $proof + $verified['timing'] + [
'signed_at' => time(), 'error_message' => '',
], $seal);
} catch (\Throwable $error) {
// A definite provider rejection before a result can retry with a fresh auth flow.
// Once bytes were signed, verification/storage failure must never re-enable signing.
$unknown = $attempted && ($signedReceived || !($error instanceof EsignProviderException)
|| $error instanceof EsignOutcomeUnknownException);
$expired = $error instanceof EsignProviderException && $error->providerCode === 'WILLINGNESS_INVALID';
$failure = ['error_message' => $unknown
? '签署结果待核实,请管理员核对签署流水;不要重复签署' : self::safeError($error)];
if ($archived) {
$failure['error_message'] = $error instanceof DomainException ? self::safeError($error)
: '签署原件暂未完成核验,请重试验签';
} elseif (!$unknown && $expired) {
$failure['error_message'] = self::isSms($work['evidence'])
? '本次签署授权已失效,请重新获取验证码' : '本次签署授权已失效,请重新核身';
}
if (!$unknown && self::isQuick($work['evidence'])
&& ($error instanceof DoctorEsignIdentityRequired || $error instanceof DoctorEsignAuthorizationRequired)) {
$quickBlock = $error;
}
if ($error instanceof EsignOutcomeUnknownException && $error->signServiceId !== null) {
$failure['sign_service_id'] = $error->signServiceId;
$failure['account_id'] = $accountId;
}
if (!$unknown && ($attempted || $error instanceof DomainException || $expired)) {
$failure += ['flow_id' => '', 'auth_url' => ''];
}
self::finishOperation($id, $token, $unknown ? 'uncertain' : 'failed', $failure);
}
return self::withQuickBlock(self::status($id, $actor, $adminInfo), $quickBlock);
}
public static function download(int $id, int $actor, array $adminInfo): array
{
$status = self::status($id, $actor, $adminInfo);
if (!$status['can_download']) {
throw new DomainException('已签原件尚不可下载');
}
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
if ($review = PrescriptionReviewEsignService::download($e)) {
return $review;
}
$pdf = self::readPdf($e['signed_path'], $e['signed_hash']);
return ['filename' => 'prescription-' . $id . '-signed.pdf', 'sha256' => $e['signed_hash'], 'content_base64' => base64_encode($pdf)];
}
/** Reverify an already archived result; never sends a second signature request. */
public static function retryVerification(int $id, int $actor, array $adminInfo): array
{
self::recoverArchived($id, $actor);
return self::status($id, $actor, $adminInfo);
}
/** CLI entry point for older archived signing attempts and confirmed originals. */
public static function recover(int $id): void
{
self::recoverArchived($id, null);
}
private static function recoverArchived(int $id, ?int $actor): void
{
$client = new EsignClient();
$client->assertConfigured();
$work = Db::transaction(static function () use ($id, $actor): ?array {
$row = $actor === null ? Db::name('tcm_prescription')->where('id', $id)->lock(true)->find() : self::lockSigner($id, $actor);
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
$recheckConfirmed = $actor === null && !empty($e['signed_at'])
&& in_array($row['esign_status'] ?? '', ['signed', 'voided'], true);
if (!$row || !$e || !self::hasArchivedSignature($row, $e, $recheckConfirmed) || !is_file(self::filePath($e['signed_path']))) {
throw new DomainException('本地没有可核验的签署原件,请联系管理员核对签署流水');
}
self::assertEnvironment($e);
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
throw new DomainException('处方与冻结原文不一致,不能恢复签署状态');
}
$state = $row['esign_status'];
if ($actor !== null && in_array($state, ['signed', 'verifying'], true)
&& !self::archiveVerificationAvailable($state, $e)) {
return null; // An already confirmed or actively verifying archive needs no additional request.
}
if (!self::archiveVerificationAvailable($state, $e) && !$recheckConfirmed) {
throw new DomainException('当前无法重试验签,请刷新签署状态');
}
if (!$recheckConfirmed) {
Db::name('prescription_esign')->where('prescription_id', $id)->update([
'operation_token' => bin2hex(random_bytes(16)), 'started_at' => time(), 'update_time' => time(),
]);
Db::name('tcm_prescription')->where('id', $id)->update(['esign_status' => 'verifying']);
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
$state = 'verifying';
}
return ['row' => $row, 'evidence' => $e, 'state' => $state, 'recheck_confirmed' => $recheckConfirmed];
});
if ($work === null) {
return;
}
$e = $work['evidence'];
$verified = ['seal' => '', 'timing' => []];
$failure = null;
try {
$pdf = self::readPdf($e['signed_path'], $e['signed_hash']);
$verified = self::verifiedDoctorProof($client->verifyPdf($pdf), self::signerName($work['row'], $e));
self::assertIssuedTime((int) ($e['issued_at'] ?? 0), $verified['timing']);
if (!empty($e['signature_time']) && (int) $e['signature_time'] !== $verified['timing']['signature_time']) {
throw new DomainException('本次验签时间与已存签署时间不一致,请联系管理员核实');
}
if (($e['signature_time_source'] ?? '') === 'tsa') {
$verified['timing']['signature_time_source'] = 'tsa';
}
} catch (\Throwable $error) {
$failure = $error;
}
$applied = Db::transaction(static function () use ($id, $actor, $work, $e, $verified, &$failure): bool {
$row = $actor === null ? Db::name('tcm_prescription')->where('id', $id)->lock(true)->find() : self::lockSigner($id, $actor);
$current = Db::name('prescription_esign')->where('prescription_id', $id)->find();
if (!$row || $current !== $e || $row['esign_status'] !== $work['state'] || !self::matchesEnvironment($e)
|| !self::hasArchivedSignature($row, $e, $work['recheck_confirmed'])
|| !hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
return false;
}
if ($failure === null) {
try {
self::readPdf($e['signed_path'], $e['signed_hash']);
} catch (DomainException $error) {
$failure = $error;
}
}
if ($work['recheck_confirmed']) {
if ($failure === null && $verified['timing'] !== [
'signature_time' => (int) ($e['signature_time'] ?? 0),
'signature_time_source' => (string) ($e['signature_time_source'] ?? ''),
]) {
Db::name('prescription_esign')->where('prescription_id', $id)->update($verified['timing']);
}
return true; // Existing signatures, including voided ones, keep their status and completion time.
}
$data = $failure === null
? $verified['timing'] + ['signed_at' => $e['signed_at'] ?: time(), 'error_message' => '']
: ['error_message' => $failure instanceof DomainException ? self::safeError($failure) : '暂时无法核验签署原件,请重试验签'];
self::writeOperation($row, $failure === null ? 'signed' : 'uncertain', $data, $verified['seal']);
return true;
});
if ($actor === null && $failure !== null) {
throw $failure;
}
if ($actor === null && !$applied) {
throw new DomainException('签署状态已变化,请刷新后重新核实');
}
}
private static function verifiedDoctorProof(array $verified, string $doctorName): array
{
$signerFound = false;
$seal = '';
$timing = [];
foreach ($verified['signatures'] ?? [] as $entry) {
$signature = $entry['signature'] ?? [];
if (($signature['validate'] ?? null) !== true) {
throw new DomainException('签署原件未通过验签');
}
if (($entry['cert']['cn'] ?? '') !== $doctorName) {
continue;
}
$signerFound = true;
if (is_string($entry['sealData'] ?? null) && $entry['sealData'] !== '' && base64_decode($entry['sealData'], true) !== false) {
$seal = $entry['sealData'];
}
$signingTime = self::verifiedSigningTime($signature);
if (!$signingTime) {
continue;
}
if ($timing && $timing['signature_time'] !== $signingTime['signature_time']) {
throw new DomainException('开方医生的签署时间存在冲突,请联系管理员核实');
}
if (!$timing || $signingTime['signature_time_source'] === 'tsa') {
$timing = $signingTime;
}
}
if (!$signerFound) {
throw new DomainException('签署原件的证书与开方医生不一致,请联系管理员核实');
}
if (!$timing) {
throw new DomainException('暂未取得可核验的医生签署时间,请重试验签');
}
return ['seal' => $seal, 'timing' => $timing];
}
public static function verifiedSigningTime(array $signature): array
{
$date = $signature['signDate'] ?? null;
$source = $signature['timeFrom'] ?? '';
if (!is_string($date) || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/D', $date)
|| !in_array($source, ['tsa', 'local'], true)) {
return [];
}
$format = 'Y-m-d H:i:s';
$timezone = new DateTimeZone((string) Config::get('esign.sdk_timezone', 'Asia/Shanghai'));
$parsed = DateTimeImmutable::createFromFormat('!' . $format, $date, $timezone);
if (!$parsed || $parsed->format($format) !== $date || $parsed->getTimestamp() <= 0) {
return [];
}
return ['signature_time' => $parsed->getTimestamp(), 'signature_time_source' => $source];
}
private static function assertIssuedTime(int $issuedAt, array $timing): void
{
if ($issuedAt === 0) {
return; // Earlier originals do not attest to an exact issuance time.
}
if ($timing['signature_time_source'] !== 'tsa') {
throw new DomainException('本次签名缺少可信时间戳,请重试验签');
}
if ($timing['signature_time'] < $issuedAt) {
throw new DomainException('签署时间早于开具确认时间,请联系管理员核对时钟和签署原件');
}
}
private static function hasSignatureEvidence(array $e): bool
{
return !empty($e['sign_service_id']) || !empty($e['signed_path']) || !empty($e['signed_hash']) || !empty($e['signed_at']);
}
private static function hasRetainedIdentity(string $state, array $e): bool
{
return in_array($state, ['authenticating', 'failed'], true) && !empty($e['flow_id']) && !self::hasSignatureEvidence($e);
}
private static function usesDoctorSms(): bool
{
return filter_var(Config::get('esign.doctor_sms_enabled', false), FILTER_VALIDATE_BOOLEAN);
}
private static function usesDoctorQuick(): bool
{
return DoctorEsignIdentityService::quickEnabled();
}
private static function isSms(array $e): bool
{
return ($e['auth_method'] ?? '') === 'sms';
}
private static function isQuick(array $e): bool
{
return ($e['auth_method'] ?? '') === 'quick';
}
private static function withQuickBlock(
array $state,
DoctorEsignIdentityRequired | DoctorEsignAuthorizationRequired | null $error
): array {
if ($error === null || ($state['verification_method'] ?? '') !== 'quick') {
return $state;
}
$state['doctor_identity_required'] = $error instanceof DoctorEsignIdentityRequired;
$state['signing_authorization_required'] = $error instanceof DoctorEsignAuthorizationRequired;
if ($error instanceof DoctorEsignAuthorizationRequired) {
$state['signing_authorization_reason'] = $error->reason;
}
$state['message'] = self::safeError($error);
return $state;
}
private static function assertQuickFlow(int $actor, string $signerName, array $evidence): void
{
if (DoctorEsignIdentityService::quickAuthorization($actor, $signerName, $evidence['account_id']) !== $evidence['flow_id']) {
throw new DomainException('快捷签授权已更新,请重新准备签署');
}
}
private static function smsVerificationState(array $e): string
{
if (!empty($e['sms_verified_at'])) {
return 'SUCCESS'; // Callers still check provider authorization before signing.
}
return time() - (int) $e['sms_sent_at'] < self::SMS_CODE_SECONDS
&& (int) $e['sms_attempts'] < self::SMS_MAX_ATTEMPTS ? 'ING' : 'EXPIRED';
}
private static function archiveVerificationAvailable(string $state, array $e): bool
{
return $state === 'uncertain' || (in_array($state, ['signing', 'verifying'], true)
&& time() - max((int) ($e['started_at'] ?? time()), (int) ($e['update_time'] ?? time())) >= self::VERIFICATION_LEASE_SECONDS);
}
private static function hasArchivedSignature(array $row, array $e, bool $includeInactive = false): bool
{
return !empty($row['esign_required']) && ($includeInactive || (empty($row['void_status']) && empty($row['delete_time'])))
&& (int) $e['doctor_id'] === (int) $row['creator_id'] && (int) $e['prescription_id'] === (int) $row['id']
&& !empty($e['sign_service_id']) && !empty($e['account_id'])
&& $e['signed_path'] === (int) $row['id'] . '-' . $e['snapshot_hash'] . '/signed.pdf'
&& preg_match('/^[a-f0-9]{64}$/D', (string) $e['signed_hash']) === 1;
}
private static function assertIdentityFlow(array $identity, array $evidence): void
{
if (($identity['flowId'] ?? '') !== $evidence['flow_id']
|| (isset($identity['appId']) && (string) $identity['appId'] !== (string) $evidence['app_id'])) {
throw new DomainException('核身流程与本次处方签署不一致,请重新认证');
}
}
private static function identityPerson(array $identity, string $signerName): ?array
{
if (($identity['objectType'] ?? '') !== 'INDIVIDUAL') {
throw new DomainException('核身对象类型与个人签署不一致');
}
// Only an explicit null has the documented SDK binding fallback. Missing/malformed data fails closed.
if (array_key_exists('indivInfo', $identity) && $identity['indivInfo'] === null) {
return null;
}
$person = $identity['indivInfo'] ?? [];
if (!is_array($person)
|| ($person['name'] ?? '') !== $signerName
|| ($person['certType'] ?? '') !== 'INDIVIDUAL_CH_IDCARD' || !is_string($person['certNo'] ?? null)
|| !preg_match('/^(?:\d{15}|\d{17}[\dXx])$/D', $person['certNo'])) {
throw new DomainException('核身信息与开方医生不一致或证件类型不支持');
}
return $person;
}
private static function assertAccountBinding(string $signerName, array $evidence, ?array $account): void
{
if ($account && ($account['doctor_name'] !== $signerName
|| empty($evidence['account_id']) || $account['account_id'] !== $evidence['account_id'])) {
// A concurrent first-time binding must not turn an unbound flow into a bound one.
throw new DomainException('签署账号绑定已变化,请重新发起核身认证');
}
if (!$account && !empty($evidence['account_id'])) {
throw new DomainException('签署账号绑定已变化,请联系管理员核实');
}
}
public static function validMainlandIdentityNumber(string $number): bool
{
if (!preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9X])$/D', $number)
|| !in_array(substr($number, 0, 2), ['11', '12', '13', '14', '15', '21', '22', '23',
'31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46',
'50', '51', '52', '53', '54', '61', '62', '63', '64', '65'], true)) {
return false;
}
$birth = strlen($number) === 15 ? '19' . substr($number, 6, 6) : substr($number, 6, 8);
if ((int) substr($birth, 0, 4) < 1800 || $birth > date('Ymd')
|| !checkdate((int) substr($birth, 4, 2), (int) substr($birth, 6, 2), (int) substr($birth, 0, 4))
|| substr($number, strlen($number) === 15 ? 12 : 14, 3) === '000') {
return false;
}
if (strlen($number) === 15) {
return true;
}
$sum = 0;
foreach ([7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] as $i => $weight) {
$sum += (int) $number[$i] * $weight;
}
return $number[17] === '10X98765432'[$sum % 11];
}
private static function lockSigner(int $id, int $actor): array
{
if (!self::enabled()) {
throw new DomainException('电子签署尚未启用,请联系管理员');
}
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
if (!$row || !self::requiresSignature($row, true)) {
throw new DomainException('此处方不属于电子签署流程');
}
PrescriptionEsignPolicy::assertSigner($row, $actor);
if (empty($row['review_submitted_at']) && ($row['esign_status'] ?? '') !== 'signed') {
throw new DomainException('请先上传处方,再进行电子签署');
}
if (trim((string) Admin::where('id', $actor)->value('name')) !== trim((string) $row['doctor_name'])) {
throw new DomainException('医师姓名已变更,请作废原处方后重新开方');
}
return $row;
}
public static function configuredSignerName(array $row, int $actor): string
{
$config = (string) Config::get('esign.sandbox_signer_names', '');
if (Config::get('esign.environment', 'sandbox') !== 'sandbox' || $config === '') {
return $row['doctor_name'];
}
$names = json_decode($config);
if (!$names instanceof \stdClass) {
throw new DomainException('沙箱签署实名配置无效,请联系管理员');
}
if (!property_exists($names, (string) $actor)) {
return $row['doctor_name'];
}
$name = $names->{(string) $actor};
if (!is_string($name) || trim($name) === '' || mb_strlen($name) > 100 || preg_match('/[\x00-\x1F\x7F]/', $name)) {
throw new DomainException('沙箱签署实名配置无效,请联系管理员');
}
return trim($name);
}
private static function signerName(array $row, array $evidence): string
{
return ($evidence['signer_name'] ?? '') !== '' ? $evidence['signer_name'] : $row['doctor_name'];
}
private static function assertEnvironment(array $e): void
{
if (!self::matchesEnvironment($e)) {
throw new DomainException('签署环境或应用与原处方不一致');
}
}
public static function matchesEnvironment(array $e): bool
{
return $e['environment'] === (string) Config::get('esign.environment', 'sandbox')
&& $e['app_id'] === (string) Config::get('esign.app_id', '');
}
public static function account(int $actor): ?array
{
return Db::name('doctor_esign_account')->where('doctor_id', $actor)
->where('environment', Config::get('esign.environment', 'sandbox'))
->where('app_id', (string) Config::get('esign.app_id', ''))->find() ?: null;
}
private static function finishOperation(int $id, string $token, string $state, array $data, string $seal = ''): void
{
Db::transaction(static function () use ($id, $token, $state, $data, $seal): void {
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
if (!$row || !$e || !hash_equals($e['operation_token'], $token)) {
return;
}
if ($state === 'authenticating' && self::isSms($e) && !empty($data['flow_id'])) {
Db::name('admin')->where('id', (int) $e['doctor_id'])->lock(true)->find();
$duplicate = Db::name('prescription_esign')->where('environment', $e['environment'])
->where('app_id', $e['app_id'])->where('flow_id', $data['flow_id'])
->where('prescription_id', '<>', $id)->lock(true)->find();
if ($duplicate) {
$state = 'failed';
$data = ['error_message' => '签署验证码流程与其他处方重复,请稍后重新获取'];
}
}
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
$state = 'uncertain';
$data['error_message'] = '处方与冻结原文不一致,请管理员核实';
unset($data['signed_at'], $data['signature_time'], $data['signature_time_source']);
}
self::writeOperation($row, $state, $data, $seal);
});
}
private static function writeOperation(array $row, string $state, array $data, string $seal): void
{
$id = (int) $row['id'];
Db::name('prescription_esign')->where('prescription_id', $id)->update($data + ['update_time' => time()]);
$updates = ['esign_status' => (!empty($row['void_status']) || !empty($row['delete_time'])) ? 'voided' : $state];
if ($state === 'signed' && $seal !== '') {
$updates['doctor_signature'] = 'data:image/png;base64,' . $seal;
}
Db::name('tcm_prescription')->where('id', $id)->update($updates);
}
private static function safeError(\Throwable $error): string
{
return $error instanceof DomainException || $error instanceof EsignProviderException
? mb_substr($error->getMessage(), 0, 240) : '电子签署服务暂不可用,请稍后重试或联系管理员';
}
private static function filePath(string $relative): string
{
if (!preg_match('#^\d+-[a-f0-9]{64}/(?:(?:source(?:-issued)?|signed|review-signed)\.pdf|review-seal-[a-f0-9]{64}\.png)$#D', $relative)) {
throw new DomainException('签署文件引用无效');
}
return rtrim((string) Config::get('esign.storage_path', root_path() . 'storage/esign'), '/\\') . DIRECTORY_SEPARATOR . $relative;
}
public static function writePdf(string $relative, string $bytes): void
{
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > 20 * 1024 * 1024) {
throw new DomainException('签署服务返回的 PDF 无效或超出大小限制');
}
self::writeArchiveFile($relative, $bytes);
}
public static function writeReviewSeal(string $relative, string $png): void
{
if (!self::isReviewSeal($png)) {
throw new DomainException('审核签章图片无效');
}
self::writeArchiveFile($relative, $png);
}
public static function readReviewSeal(string $relative): ?string
{
$path = self::filePath($relative);
$png = is_file($path) ? file_get_contents($path, false, null, 0, self::REVIEW_SEAL_MAX_BYTES + 1) : false;
return $png !== false && self::isReviewSeal($png) ? $png : null;
}
private static function isReviewSeal(string $png): bool
{
return strlen($png) <= self::REVIEW_SEAL_MAX_BYTES && str_starts_with($png, "\x89PNG\r\n\x1a\n")
&& (getimagesizefromstring($png)[2] ?? null) === IMAGETYPE_PNG;
}
private static function writeArchiveFile(string $relative, string $bytes): void
{
$path = self::filePath($relative);
$dir = dirname($path);
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
throw new DomainException('签署文件存储不可用');
}
$tmp = $path . '.' . bin2hex(random_bytes(8)) . '.tmp';
if (file_put_contents($tmp, $bytes, LOCK_EX) !== strlen($bytes)) {
@unlink($tmp);
throw new DomainException('签署文件保存失败');
}
@chmod($tmp, 0600);
if (!rename($tmp, $path)) {
@unlink($tmp);
throw new DomainException('签署文件归档失败');
}
}
public static function readPdf(string $relative, string $hash): string
{
$path = self::filePath($relative);
$bytes = is_file($path) && filesize($path) <= 20 * 1024 * 1024 ? file_get_contents($path) : false;
if ($bytes === false || !str_starts_with($bytes, '%PDF-') || !hash_equals($hash, hash('sha256', $bytes))) {
throw new DomainException('签署原件缺失或校验失败,请管理员恢复原件');
}
return $bytes;
}
}