626 lines
30 KiB
PHP
626 lines
30 KiB
PHP
<?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,
|
|
];
|
|
}
|
|
}
|