refactor: flatten src/AKSRT → src (drop theme-identifier dir)

Move all domain folders from src/AKSRT/{Domain} to src/{Domain}; remap
Composer PSR-4 "AKSRT\\": "src/"; update audit script + README + ADR
paths; remove dead tools/build-psr4-map.php (scanned deleted inc/classes).
This commit is contained in:
2026-08-02 22:06:06 +08:00
parent 56f1a8175f
commit 8c5b1555c9
285 changed files with 26 additions and 3600 deletions
+171
View File
@@ -0,0 +1,171 @@
<?php
/**
* Identity verification application persistence.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class ApplicationRepository {
public const ACTIVE_STATUSES = [
'created', 'provider_pending', 'provider_processing', 'manual_pending',
];
private string $table;
public function __construct() {
$this->table = \AKSRT\Core\DBMigrator::table('identity_application');
}
/** @param array<string,mixed> $data */
public function create(array $data) {
global $wpdb;
if ($this->table === '') {
return new \WP_Error('aksrt_identity_table', __('身份认证数据表不可用', 'aksrt'));
}
$now = current_time('mysql', true);
$row = wp_parse_args($data, [
'application_uuid' => wp_generate_uuid4(),
'client_request_id' => wp_generate_uuid4(),
'user_id' => 0,
'type' => 'personal',
'channel' => 'cloud',
'provider' => '',
'status' => 'created',
'public_name' => '',
'public_desc' => '',
'fee_amount' => 0,
'fee_status' => 'not_required',
'created_at' => $now,
'updated_at' => $now,
]);
$inserted = $wpdb->insert($this->table, $row);
if ($inserted !== 1) {
return new \WP_Error('aksrt_identity_create', __('认证申请创建失败', 'aksrt'));
}
return $this->find_by_id((int) $wpdb->insert_id);
}
/** @return array<string,mixed>|null */
public function find_by_id(int $id): ?array {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table} WHERE id = %d", $id), ARRAY_A);
return is_array($row) ? $this->normalize($row) : null;
}
/** @return array<string,mixed>|null */
public function find_by_uuid(string $uuid): ?array {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table} WHERE application_uuid = %s", $uuid), ARRAY_A);
return is_array($row) ? $this->normalize($row) : null;
}
/** @return array<string,mixed>|null */
public function find_by_client_request(int $user_id, string $request_id): ?array {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$this->table} WHERE user_id = %d AND client_request_id = %s LIMIT 1",
$user_id,
$request_id
), ARRAY_A);
return is_array($row) ? $this->normalize($row) : null;
}
/** @return array<string,mixed>|null */
public function latest_for_user(int $user_id): ?array {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$this->table} WHERE user_id = %d ORDER BY id DESC LIMIT 1",
$user_id
), ARRAY_A);
return is_array($row) ? $this->normalize($row) : null;
}
/** @return array<string,mixed>|null */
public function active_for_user(int $user_id): ?array {
global $wpdb;
$placeholders = implode(',', array_fill(0, count(self::ACTIVE_STATUSES), '%s'));
$params = array_merge([$user_id], self::ACTIVE_STATUSES);
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$this->table} WHERE user_id = %d AND status IN ({$placeholders}) ORDER BY id DESC LIMIT 1",
$params
), ARRAY_A);
return is_array($row) ? $this->normalize($row) : null;
}
/** @return array<string,mixed>|null */
public function verified_for_user(int $user_id): ?array {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$this->table} WHERE user_id = %d AND status = 'verified' ORDER BY completed_at DESC, id DESC LIMIT 1",
$user_id
), ARRAY_A);
return is_array($row) ? $this->normalize($row) : null;
}
/** @param array<string,mixed> $fields */
public function transition(int $id, string $expected, string $next, array $fields = []): bool {
global $wpdb;
$fields['status'] = $next;
$fields['updated_at'] = current_time('mysql', true);
$formats = array_fill(0, count($fields), '%s');
foreach (['reviewer_id', 'retry_count', 'attempt_ordinal'] as $int_key) {
$index = array_search($int_key, array_keys($fields), true);
if ($index !== false) {
$formats[$index] = '%d';
}
}
foreach (['fee_amount'] as $float_key) {
$index = array_search($float_key, array_keys($fields), true);
if ($index !== false) {
$formats[$index] = '%f';
}
}
return $wpdb->update($this->table, $fields, ['id' => $id, 'status' => $expected], $formats, ['%d', '%s']) === 1;
}
/** @param array<string,mixed> $fields */
public function update(int $id, array $fields): bool {
global $wpdb;
if ($fields === []) {
return true;
}
$fields['updated_at'] = current_time('mysql', true);
$updated = $wpdb->update($this->table, $fields, ['id' => $id]);
return $updated !== false;
}
public function count_user_type(int $user_id, string $type): int {
global $wpdb;
return (int) $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM {$this->table} WHERE user_id = %d AND type = %s AND fee_status IN ('charged','not_required')",
$user_id,
$type
));
}
public function delete(int $id): bool {
global $wpdb;
return $wpdb->delete($this->table, ['id' => $id], ['%d']) === 1;
}
/** @return array<string,mixed> */
private function normalize(array $row): array {
foreach (['id', 'user_id', 'reviewer_id', 'attempt_ordinal', 'retry_count'] as $key) {
$row[$key] = (int) ($row[$key] ?? 0);
}
foreach (['provider_started_at', 'completed_at', 'expires_at'] as $nullable_key) {
if (($row[$nullable_key] ?? null) === null) {
$row[$nullable_key] = '';
}
}
$row['fee_amount'] = round((float) ($row['fee_amount'] ?? 0), 2);
$evidence = json_decode((string) ($row['evidence_ids'] ?? ''), true);
$row['evidence_ids'] = is_array($evidence) ? array_values(array_map('intval', $evidence)) : [];
return $row;
}
}
+317
View File
@@ -0,0 +1,317 @@
<?php
/**
* Identity verification application orchestration.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
use AKSRT\Identity\Provider\ProviderFactory;
use AKSRT\Identity\Provider\ProviderResult;
defined('ABSPATH') || exit;
final class ApplicationService {
public function __construct(
private ?ApplicationRepository $applications = null,
private ?TransitionService $transitions = null,
private ?EvidenceService $evidence = null
) {
$this->applications ??= new ApplicationRepository();
$this->transitions ??= new TransitionService($this->applications);
$this->evidence ??= new EvidenceService();
}
/** @param array<string,mixed> $input */
public function create(int $user_id, array $input) {
$settings = SettingsRuntime::get();
if (empty($settings['enabled']) || empty($settings['allow_apply'])) {
return new \WP_Error('aksrt_identity_disabled', __('暂不能申请身份认证', 'aksrt'));
}
if (!is_ssl()) {
return new \WP_Error('aksrt_identity_https', __('身份认证必须通过 HTTPS 发起', 'aksrt'));
}
if ($this->applications->verified_for_user($user_id)) {
return new \WP_Error('aksrt_identity_verified', __('您已是认证用户', 'aksrt'));
}
if ($this->applications->active_for_user($user_id)) {
return new \WP_Error('aksrt_identity_active', __('您已有进行中的认证申请', 'aksrt'));
}
$type = sanitize_key((string) ($input['type'] ?? ''));
if (!in_array($type, ['personal', 'enterprise'], true)) {
return new \WP_Error('aksrt_identity_type', __('请选择有效的认证类型', 'aksrt'));
}
$request_id = sanitize_text_field((string) ($input['client_request_id'] ?? ''));
if (!wp_is_uuid($request_id)) {
return new \WP_Error('aksrt_identity_request_id', __('请求标识无效', 'aksrt'));
}
$existing = $this->applications->find_by_client_request($user_id, $request_id);
if ($existing) {
return $this->view($existing);
}
$person_name = sanitize_text_field((string) ($input['person_name'] ?? ''));
$id_number = strtoupper(preg_replace('/\s+/', '', sanitize_text_field((string) ($input['id_number'] ?? ''))) ?: '');
$company_name = $type === 'enterprise' ? sanitize_text_field((string) ($input['company_name'] ?? '')) : '';
$company_code = $type === 'enterprise' ? (preg_replace('/\s+/', '', sanitize_text_field((string) ($input['company_code'] ?? ''))) ?: '') : '';
if ($person_name === '' || $this->length($person_name) > 50 || !$this->is_china_id_number($id_number)) {
return new \WP_Error('aksrt_identity_person_fields', __('请填写有效的姓名和身份证号码', 'aksrt'));
}
if ($type === 'enterprise' && ($company_name === '' || $this->length($company_name) > 191 || $company_code === '' || $this->length($company_code) > 32)) {
return new \WP_Error('aksrt_identity_enterprise_fields', __('请填写有效的企业全称和统一社会信用代码', 'aksrt'));
}
if (empty($input['consent'])) {
return new \WP_Error('aksrt_identity_consent', __('请先同意身份信息处理说明', 'aksrt'));
}
$public_name = $type === 'enterprise' ? $this->truncate($company_name, 64) : __('个人认证', 'aksrt');
$public_desc = '';
$type_settings = \AKSRT\User\AuthApply::type_settings($type);
$attempt = $this->applications->count_user_type($user_id, $type);
$free = max(0, (int) ($type_settings['free_applications'] ?? 0));
$fee = $attempt < $free ? 0.0 : max(0, (float) ($type_settings['fee'] ?? 0));
$application = $this->applications->create([
'application_uuid' => wp_generate_uuid4(),
'client_request_id' => $request_id,
'user_id' => $user_id,
'type' => $type,
'provider' => $settings['provider'],
'provider_flow' => (string) $settings['personal_flow'],
'public_name' => $public_name,
'public_desc' => $public_desc,
'person_name_masked' => SettingsRuntime::mask_name($person_name),
'id_number_masked' => SettingsRuntime::mask_id_number($id_number),
'id_number_hash' => SettingsRuntime::hmac($id_number),
'company_name' => $company_name,
'company_code_masked' => $type === 'enterprise' ? SettingsRuntime::mask_id_number($company_code) : '',
'company_code_hash' => $type === 'enterprise' ? SettingsRuntime::hmac($company_code) : '',
'fee_amount' => $fee,
'fee_status' => $fee > 0 ? 'pending' : 'not_required',
'attempt_ordinal' => $attempt + 1,
]);
if (is_wp_error($application)) {
return $application;
}
$provider = ProviderFactory::make((string) $settings['provider']);
$valid = $provider->validate_config();
if (is_wp_error($valid)) {
$next = !empty($settings['allow_manual_fallback']) ? 'provider_unsupported' : 'cancelled';
$failed = $this->transitions->transition($application, $next, [
'provider_result_code' => $valid->get_error_code(),
'provider_result_summary' => $valid->get_error_message(),
], ['source' => 'system', 'event_type' => 'provider_preflight_failed']);
return is_wp_error($failed) ? $failed : $this->view($failed);
}
$provider_request = $input;
$provider_request['person_name'] = $person_name;
$provider_request['id_number'] = $id_number;
$provider_request['company_name'] = $company_name;
$provider_request['company_code'] = $company_code;
$provider_request['application_uuid'] = $application['application_uuid'];
$provider_request['user_id'] = $user_id;
$result = $type === 'personal'
? $provider->start_personal($provider_request)
: $provider->start_enterprise($provider_request);
return $this->apply_provider_result($application, $result, true);
}
public function refresh(array $application) {
if (!in_array((string) $application['status'], ['provider_pending', 'provider_processing'], true)) {
return $this->view($application);
}
if (!empty($application['expires_at']) && strtotime((string) $application['expires_at'] . ' UTC') <= time()) {
$settings = SettingsRuntime::get();
$next = !empty($settings['allow_manual_fallback']) ? 'provider_expired' : 'cancelled';
$expired = $this->transitions->transition($application, $next, [
'provider_result_code' => 'session_expired',
'provider_result_summary' => __('云认证会话已过期', 'aksrt'),
], ['source' => 'system', 'event_type' => 'session_expired']);
return is_wp_error($expired) ? $expired : $this->view($expired);
}
$provider = ProviderFactory::make((string) $application['provider']);
return $this->apply_provider_result($application, $provider->query($application), false);
}
public function move_to_manual(array $application, $files) {
if (!in_array((string) $application['status'], ['created', 'provider_failed', 'provider_unsupported', 'provider_expired'], true)) {
return new \WP_Error('aksrt_identity_manual_state', __('该申请当前不能转人工审核', 'aksrt'));
}
if (empty(SettingsRuntime::get()['allow_manual_fallback'])) {
return new \WP_Error('aksrt_identity_manual_disabled', __('站点未开放人工审核回退', 'aksrt'));
}
$ids = $this->evidence->upload((int) $application['user_id'], (string) $application['application_uuid'], $files);
if (is_wp_error($ids)) {
return $ids;
}
$charge = $this->charge($application);
if (is_wp_error($charge)) {
$this->evidence->delete($ids);
return $charge;
}
$updated = $this->transitions->transition($application, 'manual_pending', [
'channel' => 'manual',
'manual_reason' => __('云认证未完成,用户转入人工审核', 'aksrt'),
'evidence_ids' => wp_json_encode($ids),
'fee_status' => $charge,
], ['source' => 'user', 'event_type' => 'manual_fallback', 'actor_user_id' => (int) $application['user_id']]);
if (is_wp_error($updated)) {
$this->evidence->delete($ids);
$this->refund($application);
return $updated;
}
return $this->view($updated);
}
/** @return array<string,mixed> */
public function view(array $application): array {
$stage = (string) $application['status'];
$next = 'wait';
if (in_array($stage, ['provider_pending', 'provider_processing'], true)) {
$next = 'poll';
} elseif (in_array($stage, ['provider_failed', 'provider_unsupported', 'provider_expired'], true)) {
$next = 'manual_or_retry';
} elseif ($stage === 'verified') {
$next = 'complete';
}
return [
'uuid' => (string) $application['application_uuid'],
'type' => (string) $application['type'],
'status' => TransitionService::public_status($stage),
'stage' => $stage,
'next_action' => $next,
'public_name' => (string) $application['public_name'],
'public_desc' => (string) $application['public_desc'],
'result_code' => (string) $application['provider_result_code'],
'message' => (string) $application['provider_result_summary'],
'redirect_url' => esc_url_raw((string) ($application['redirect_url'] ?? '')),
'qr_payload' => sanitize_text_field((string) ($application['qr_payload'] ?? '')),
'expires_at' => (string) ($application['expires_at'] ?? ''),
'created_at' => (string) $application['created_at'],
'poll_interval' => (int) SettingsRuntime::get()['poll_interval_seconds'],
];
}
private function apply_provider_result(array $application, ProviderResult $result, bool $starting) {
$data = $result->data;
if ($result->decision === ProviderResult::PENDING) {
$fee_status = (string) $application['fee_status'];
if ($starting) {
$charged = $this->charge($application);
if (is_wp_error($charged)) {
return $charged;
}
$fee_status = $charged;
}
$next = $starting ? 'provider_pending' : 'provider_processing';
$fields = [
'provider_session_id' => sanitize_text_field((string) ($data['provider_session_id'] ?? ($application['provider_session_id'] ?? ''))),
'provider_request_id' => sanitize_text_field((string) ($data['request_id'] ?? ($application['provider_request_id'] ?? ''))),
'redirect_url' => esc_url_raw((string) ($data['redirect_url'] ?? ($application['redirect_url'] ?? ''))),
'qr_payload' => sanitize_text_field((string) ($data['qr_payload'] ?? ($application['qr_payload'] ?? ''))),
'provider_started_at' => $starting ? current_time('mysql', true) : ($application['provider_started_at'] ?? ''),
'expires_at' => (string) ($data['expires_at'] ?? ($application['expires_at'] ?? '')),
'provider_result_code' => sanitize_text_field((string) ($data['result_code'] ?? 'pending')),
'provider_result_summary' => sanitize_text_field((string) ($data['message'] ?? '')),
'fee_status' => $fee_status,
];
$updated = $this->transitions->transition($application, $next, $fields, [
'source' => (string) $application['provider'],
'event_type' => $starting ? 'session_started' : 'query_pending',
'external_event_id' => (string) ($data['external_event_id'] ?? ''),
]);
if (is_wp_error($updated)) {
if ($starting) {
$this->refund(array_merge($application, ['fee_status' => $fee_status]));
}
return $updated;
}
$updated['redirect_url'] = (string) ($updated['redirect_url'] ?? '');
$updated['qr_payload'] = (string) ($updated['qr_payload'] ?? '');
return $this->view($updated);
}
$map = [
ProviderResult::PASSED => 'verified',
ProviderResult::FAILED => 'provider_failed',
ProviderResult::UNSUPPORTED => 'provider_unsupported',
ProviderResult::EXPIRED => 'provider_expired',
];
$next = $map[$result->decision] ?? 'provider_failed';
$settings = SettingsRuntime::get();
if (in_array($next, ['provider_failed', 'provider_unsupported', 'provider_expired'], true) && empty($settings['allow_manual_fallback'])) {
$next = 'cancelled';
}
$updated = $this->transitions->transition($application, $next, [
'provider_result_code' => sanitize_text_field((string) ($data['result_code'] ?? $result->decision)),
'provider_result_summary' => sanitize_text_field((string) ($data['message'] ?? '')),
], [
'source' => (string) $application['provider'],
'event_type' => 'provider_result',
'external_event_id' => (string) ($data['external_event_id'] ?? ''),
'result_code' => (string) ($data['result_code'] ?? $result->decision),
]);
return is_wp_error($updated) ? $updated : $this->view($updated);
}
/** @return string|\WP_Error */
private function charge(array $application) {
if (in_array((string) $application['fee_status'], ['charged', 'not_required'], true)) {
return (string) $application['fee_status'];
}
$fee = (float) $application['fee_amount'];
if ($fee <= 0) {
return 'not_required';
}
$result = \AKSRT\Credits\Balance::deduct(
(int) $application['user_id'],
$fee,
'verify_application',
['type' => 'identity', 'id' => (int) $application['id']],
sprintf(__('提交%s认证申请', 'aksrt'), (string) $application['type'])
);
return is_wp_error($result) ? $result : 'charged';
}
private function refund(array $application): void {
if ((float) $application['fee_amount'] <= 0 || !in_array((string) $application['fee_status'], ['charged', 'pending'], true)) {
return;
}
\AKSRT\Credits\Balance::add(
(int) $application['user_id'],
(float) $application['fee_amount'],
'verify_application_refund',
['type' => 'identity', 'id' => (int) $application['id']],
__('认证会话创建失败退款', 'aksrt')
);
$this->applications->update((int) $application['id'], ['fee_status' => 'refunded']);
}
private function length(string $value): int {
return function_exists('mb_strlen') ? mb_strlen($value) : strlen($value);
}
private function truncate(string $value, int $length): string {
return function_exists('mb_substr') ? mb_substr($value, 0, $length) : substr($value, 0, $length);
}
private function is_china_id_number(string $value): bool {
if (!preg_match('/^(\d{17}[0-9X]|\d{15})$/', $value)) {
return false;
}
if (strlen($value) === 15) {
return true;
}
$weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
$codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
$sum = 0;
for ($i = 0; $i < 17; $i++) {
$sum += (int) $value[$i] * $weights[$i];
}
return $codes[$sum % 11] === $value[17];
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
/**
* Identity provider callback endpoints.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
use AKSRT\Identity\Provider\ProviderFactory;
defined('ABSPATH') || exit;
final class CallbackController {
private const NS = 'aksrt/v1';
public function register_routes(): void {
foreach (['aliyun', 'tencent'] as $provider) {
register_rest_route(self::NS, '/identity/callback/' . $provider, [
'methods' => $provider === 'aliyun' ? ['GET', 'POST'] : 'POST',
'callback' => function (\WP_REST_Request $request) use ($provider): \WP_REST_Response {
return $this->handle($provider, $request);
},
'permission_callback' => '__return_true',
]);
}
}
private function handle(string $provider_key, \WP_REST_Request $request): \WP_REST_Response {
$body = $request->get_body();
if (strlen($body) > 1024 * 1024) {
return new \WP_REST_Response(['success' => false], 413);
}
$provider = ProviderFactory::make($provider_key);
if (!$provider->verify_callback($request)) {
return new \WP_REST_Response(['success' => false], 403);
}
$result = $provider->parse_callback($request);
$session = sanitize_text_field((string) ($result->data['provider_session_id'] ?? ''));
$outer_order = sanitize_text_field((string) ($result->data['outer_order_no'] ?? ''));
if ($session === '' && $outer_order === '') {
return new \WP_REST_Response(['success' => false], 422);
}
global $wpdb;
$table = \AKSRT\Core\DBMigrator::table('identity_application');
if ($session !== '') {
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$table} WHERE provider = %s AND provider_session_id = %s ORDER BY id DESC LIMIT 1",
$provider_key,
$session
), ARRAY_A);
} else {
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$table} WHERE provider = %s AND application_uuid = %s ORDER BY id DESC LIMIT 1",
$provider_key,
$outer_order
), ARRAY_A);
}
if (!is_array($row)) {
return new \WP_REST_Response(['success' => false], 404);
}
// The callback only wakes server-side reconciliation. A provider query
// remains the source of truth for a successful identity decision.
$service = new ApplicationService();
$response = $service->refresh($row);
if (is_wp_error($response)) {
return new \WP_REST_Response(['success' => false], 409);
}
return new \WP_REST_Response(['success' => true]);
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
/**
* Identity verification event persistence.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class EventRepository {
private string $table;
public function __construct() {
$this->table = \AKSRT\Core\DBMigrator::table('identity_event');
}
/** @param array<string,mixed> $event */
public function record(array $event): bool {
global $wpdb;
$summary = is_array($event['summary'] ?? null) ? $event['summary'] : [];
$row = [
'application_id' => (int) ($event['application_id'] ?? 0),
'event_uuid' => wp_generate_uuid4(),
'source' => sanitize_key((string) ($event['source'] ?? 'system')),
'event_type' => sanitize_key((string) ($event['event_type'] ?? 'status_changed')),
'external_event_id' => sanitize_text_field((string) ($event['external_event_id'] ?? '')),
'dedupe_key' => (string) ($event['dedupe_key'] ?? hash('sha256', wp_generate_uuid4())),
'from_status' => sanitize_key((string) ($event['from_status'] ?? '')),
'to_status' => sanitize_key((string) ($event['to_status'] ?? '')),
'result_code' => sanitize_text_field((string) ($event['result_code'] ?? '')),
'summary_json' => $summary !== [] ? wp_json_encode($summary) : null,
'actor_user_id' => !empty($event['actor_user_id']) ? (int) $event['actor_user_id'] : null,
'created_at' => current_time('mysql', true),
];
$inserted = $wpdb->insert($this->table, $row);
if ($inserted === 1) {
return true;
}
return str_contains(strtolower((string) $wpdb->last_error), 'duplicate');
}
/** @return array<int,array<string,mixed>> */
public function for_application(int $application_id): array {
global $wpdb;
$rows = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM {$this->table} WHERE application_id = %d ORDER BY id DESC",
$application_id
), ARRAY_A);
return is_array($rows) ? $rows : [];
}
public function delete_for_application(int $application_id): bool {
global $wpdb;
return $wpdb->delete($this->table, ['application_id' => $application_id], ['%d']) !== false;
}
}
+150
View File
@@ -0,0 +1,150 @@
<?php
/**
* Private identity evidence handling.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class EvidenceService {
public const OWNER_META = '_aksrt_verify_evidence_owner';
public const APPLICATION_META = '_aksrt_identity_application_uuid';
public function init(): void {
add_action('admin_post_aksrt_verify_evidence', [$this, 'serve']);
}
/** @return array<int,int>|\WP_Error */
public function upload(int $user_id, string $application_uuid, $input) {
$files = $this->normalize($input);
if (is_wp_error($files) || $files === []) {
return $files;
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$ids = [];
foreach ($files as $file) {
$tmp = (string) ($file['tmp_name'] ?? '');
$size = (int) ($file['size'] ?? 0);
if ((int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || $size <= 0 || $size > 2 * MB_IN_BYTES || !is_uploaded_file($tmp)) {
$this->delete($ids);
return new \WP_Error('aksrt_identity_upload', __('证明材料上传失败,单张图片不能超过 2MB', 'aksrt'));
}
$checked = wp_check_filetype_and_ext($tmp, sanitize_file_name((string) ($file['name'] ?? 'evidence.jpg')));
$mime = (string) ($checked['type'] ?? '');
$ext = (string) ($checked['ext'] ?? '');
if (!in_array($mime, ['image/jpeg', 'image/png', 'image/webp'], true) || $ext === '') {
$this->delete($ids);
return new \WP_Error('aksrt_identity_upload_type', __('证明材料仅支持 JPG、PNG 或 WebP 图片', 'aksrt'));
}
$id = media_handle_sideload([
'name' => wp_generate_password(24, false, false) . '.' . $ext,
'tmp_name' => $tmp,
'type' => $mime,
'error' => UPLOAD_ERR_OK,
'size' => $size,
], 0, __('身份认证证明材料', 'aksrt'));
if (is_wp_error($id)) {
$this->delete($ids);
return new \WP_Error('aksrt_identity_upload_write', __('证明材料写入失败', 'aksrt'));
}
$id = (int) $id;
wp_update_post(['ID' => $id, 'post_author' => $user_id, 'post_status' => 'private']);
update_post_meta($id, self::OWNER_META, $user_id);
update_post_meta($id, self::APPLICATION_META, $application_uuid);
$ids[] = $id;
}
return $ids;
}
/** @return array<int,array{id:int,url:string,thumbnail_url:string}> */
public function items(array $application, bool $admin = false): array {
$owner_id = (int) ($application['user_id'] ?? 0);
if ($owner_id <= 0 || ($admin ? !current_user_can('aksrt_review_identity') : get_current_user_id() !== $owner_id)) {
return [];
}
$items = [];
foreach ((array) ($application['evidence_ids'] ?? []) as $id) {
$id = (int) $id;
if ((int) get_post_meta($id, self::OWNER_META, true) !== $owner_id || (string) get_post_meta($id, self::APPLICATION_META, true) !== (string) $application['application_uuid']) {
continue;
}
$url = add_query_arg([
'action' => 'aksrt_verify_evidence',
'attachment' => $id,
'_wpnonce' => wp_create_nonce('aksrt_verify_evidence_' . $id),
], admin_url('admin-post.php'));
$items[] = ['id' => $id, 'url' => $url, 'thumbnail_url' => $url];
}
return $items;
}
public function serve(): void {
if (!is_user_logged_in()) {
wp_die(esc_html__('请先登录', 'aksrt'), '', ['response' => 401]);
}
$id = isset($_GET['attachment']) ? (int) $_GET['attachment'] : 0;
if ($id <= 0 || !check_admin_referer('aksrt_verify_evidence_' . $id)) {
wp_die(esc_html__('安全校验失败', 'aksrt'), '', ['response' => 403]);
}
$owner = (int) get_post_meta($id, self::OWNER_META, true);
if ($owner <= 0 || (get_current_user_id() !== $owner && !current_user_can('aksrt_review_identity'))) {
wp_die(esc_html__('您没有权限查看该证明材料', 'aksrt'), '', ['response' => 403]);
}
$path = get_attached_file($id);
$mime = (string) get_post_mime_type($id);
if (!is_string($path) || !is_file($path) || !is_readable($path)) {
wp_die(esc_html__('证明材料不存在', 'aksrt'), '', ['response' => 404]);
}
if (!in_array($mime, ['image/jpeg', 'image/png', 'image/webp'], true)) {
wp_die(esc_html__('证明材料类型无效', 'aksrt'), '', ['response' => 415]);
}
nocache_headers();
header('Cache-Control: private, no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
header('Content-Type: ' . $mime);
header('Content-Disposition: inline; filename="evidence-' . $id . '"');
header('Content-Length: ' . (string) filesize($path));
readfile($path);
exit;
}
/** @return array<int,array<string,mixed>>|\WP_Error */
private function normalize($input) {
if (!is_array($input) || empty($input['name'])) {
return [];
}
$names = is_array($input['name']) ? $input['name'] : [$input['name']];
if (count($names) > 3) {
return new \WP_Error('aksrt_identity_upload_limit', __('证明材料最多上传 3 张', 'aksrt'));
}
$files = [];
foreach ($names as $index => $name) {
if ((string) $name === '') {
continue;
}
$files[] = [
'name' => $name,
'tmp_name' => is_array($input['tmp_name'] ?? null) ? ($input['tmp_name'][$index] ?? '') : ($input['tmp_name'] ?? ''),
'error' => is_array($input['error'] ?? null) ? ($input['error'][$index] ?? UPLOAD_ERR_NO_FILE) : ($input['error'] ?? UPLOAD_ERR_NO_FILE),
'size' => is_array($input['size'] ?? null) ? ($input['size'][$index] ?? 0) : ($input['size'] ?? 0),
];
}
return $files;
}
/** @param array<int,int> $ids */
public function delete(array $ids): void {
foreach ($ids as $id) {
if ((int) $id > 0 && get_post_type((int) $id) === 'attachment') {
wp_delete_attachment((int) $id, true);
}
}
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
/**
* Identity verification lifecycle.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class Identity {
private static ?self $instance = null;
public static function get_instance(): self {
return self::$instance ??= new self();
}
public function init(): void {
add_action('rest_api_init', [new RestController(), 'register_routes']);
add_action('rest_api_init', [new CallbackController(), 'register_routes']);
(new EvidenceService())->init();
add_action('init', [$this, 'ensure_reviewer_capability']);
add_action('delete_user', [$this, 'delete_user_data']);
}
public function ensure_reviewer_capability(): void {
$role = get_role('administrator');
if ($role && !$role->has_cap('aksrt_review_identity')) {
$role->add_cap('aksrt_review_identity');
}
}
public function delete_user_data(int $user_id): void {
global $wpdb;
$applications = \AKSRT\Core\DBMigrator::table('identity_application');
$events = \AKSRT\Core\DBMigrator::table('identity_event');
if ($applications === '' || $events === '') {
return;
}
$ids = $wpdb->get_col($wpdb->prepare("SELECT id FROM {$applications} WHERE user_id = %d", $user_id));
foreach ((array) $ids as $id) {
$wpdb->delete($events, ['application_id' => (int) $id], ['%d']);
}
$wpdb->delete($applications, ['user_id' => $user_id], ['%d']);
}
}
+351
View File
@@ -0,0 +1,351 @@
<?php
/**
* Alibaba Cloud Cloudauth provider.
*
* @package AKSRT
*/
namespace AKSRT\Identity\Provider;
use AKSRT\Identity\SettingsRuntime;
defined('ABSPATH') || exit;
final class AliyunProvider implements ProviderInterface {
public function key(): string { return 'aliyun'; }
public function capabilities(): array { return ['personal' => true, 'enterprise' => true]; }
public function validate_config() {
$cfg = SettingsRuntime::get();
foreach (['access_key_id', 'access_key_secret'] as $key) {
if (empty($cfg['credentials'][$key])) {
return new \WP_Error('aksrt_identity_aliyun_credentials', __('阿里云实人认证凭证不完整', 'aksrt'));
}
}
if (empty($cfg['personal_flow'])) {
return new \WP_Error('aksrt_identity_aliyun_scene', __('请配置阿里云实人认证 SceneId', 'aksrt'));
}
if (!empty($cfg['enterprise_flow']) && preg_match('/[^A-Za-z0-9_-]/', (string) $cfg['enterprise_flow'])) {
return new \WP_Error('aksrt_identity_aliyun_enterprise_scene', __('阿里云企业认证 SceneCode 格式无效', 'aksrt'));
}
return true;
}
public function start_personal(array $request): ProviderResult {
return $this->init_face_verify($request);
}
public function start_enterprise(array $request): ProviderResult {
$cfg = SettingsRuntime::get();
// Ref: https://help.aliyun.com/zh/id-verification/enterprise-factor-validation-v2
foreach (['company_name', 'company_code', 'person_name', 'id_number'] as $key) {
if (empty($request[$key])) {
return ProviderResult::failed('aliyun_enterprise_fields', __('企业认证资料不完整', 'aksrt'));
}
}
$response = $this->rpc('cloudauth.aliyuncs.com', '2022-11-25', 'EntElementVerifyV2', [
'SceneCode' => (string) ($cfg['enterprise_flow'] ?: $cfg['personal_flow']),
'MerchantBizId' => preg_replace('/[^A-Za-z0-9]/', '', (string) $request['application_uuid']),
'MerchantUserId' => preg_replace('/[^A-Za-z0-9]/', '', 'U' . (string) ($request['user_id'] ?? '0')),
'UserAuthorization' => '1',
'InfoVerifyType' => 'ENT_4META',
'LicenseNo' => preg_replace('/\s+/', '', (string) $request['company_code']),
'EntName' => (string) $request['company_name'],
'LegalPersonName' => (string) $request['person_name'],
'LegalPersonCertNo' => preg_replace('/\s+/', '', (string) $request['id_number']),
]);
if (is_wp_error($response)) {
return ProviderResult::failed($response->get_error_code(), $response->get_error_message());
}
if (!$this->enterprise_passed($response)) {
return ProviderResult::failed(
sanitize_text_field((string) ($response['Code'] ?? $response['ResultCode'] ?? 'enterprise_failed')),
sanitize_text_field((string) ($response['Message'] ?? __('企业要素或法人关系核验未通过', 'aksrt')))
);
}
return $this->init_face_verify($request);
}
public function query(array $application): ProviderResult {
// Ref: https://api.aliyun.com/document/Cloudauth/2019-03-07/DescribeFaceVerify
$response = $this->rpc('cloudauth.aliyuncs.com', '2019-03-07', 'DescribeFaceVerify', [
'SceneId' => (string) ($application['provider_flow'] ?? ''),
'CertifyId' => (string) ($application['provider_session_id'] ?? ''),
]);
if (is_wp_error($response)) {
return ProviderResult::pending(['result_code' => $response->get_error_code(), 'message' => __('认证结果暂未取回,请稍后重试', 'aksrt')]);
}
$code = sanitize_text_field((string) ($response['Code'] ?? ''));
if ($code === '424') {
return ProviderResult::pending([
'request_id' => sanitize_text_field((string) ($response['RequestId'] ?? '')),
'result_code' => $code,
'message' => __('用户尚未在阿里云核身页面提交认证,请完成后再刷新结果', 'aksrt'),
]);
}
if ($code !== '' && $code !== '200') {
return ProviderResult::failed($code, sanitize_text_field((string) ($response['Message'] ?? '')));
}
$object = $this->normalize_result_object($response['ResultObject'] ?? []);
$passed = $object['Passed'] ?? $object['passed'] ?? $response['Passed'] ?? null;
$success = $object['Success'] ?? $object['success'] ?? $response['Success'] ?? null;
if ((string) ($response['Code'] ?? '') === '200' && ($success === true || $success === 'True' || $success === 'true') && $passed === 'T') {
return ProviderResult::passed(['request_id' => (string) ($response['RequestId'] ?? ''), 'result_code' => 'passed']);
}
$status = strtoupper((string) ($object['SubCode'] ?? $object['Status'] ?? $object['subCode'] ?? $object['status'] ?? ''));
if ((string) ($response['Code'] ?? '') === '200' && $status === '200') {
return ProviderResult::passed(['request_id' => (string) ($response['RequestId'] ?? ''), 'result_code' => 'passed']);
}
$message = $object['MaterialInfo'] ?? $object['Message'] ?? $object['message'] ?? __('阿里云仍在处理认证结果', 'aksrt');
if ($passed === 'F') {
$debug = $this->response_debug_summary($response, $object, ['passed' => 'F']);
$this->log_debug('DescribeFaceVerify not passed', $debug);
return ProviderResult::failed($status ?: 'not_passed', sanitize_text_field((string) $message));
}
if ($object === []) {
$debug = $this->response_debug_summary($response, $object);
$this->log_debug('DescribeFaceVerify empty ResultObject', $debug);
return ProviderResult::pending([
'request_id' => sanitize_text_field((string) ($response['RequestId'] ?? '')),
'result_code' => 'processing',
'message' => sprintf(__('阿里云已返回成功状态,认证明细仍在生成中:%s', 'aksrt'), $debug),
]);
}
if ($status === '' || in_array($status, ['PROCESSING', 'INIT', 'PENDING'], true)) {
return ProviderResult::pending(['result_code' => $status ?: 'processing', 'message' => sanitize_text_field((string) $message)]);
}
return ProviderResult::failed($status, sanitize_text_field((string) $message));
}
private function is_public_https_url(string $url): bool {
if ($url === '') {
return false;
}
$parts = wp_parse_url($url);
if (!is_array($parts) || strtolower((string) ($parts['scheme'] ?? '')) !== 'https') {
return false;
}
$host = strtolower((string) ($parts['host'] ?? ''));
return $host !== '' && !in_array($host, ['localhost', '127.0.0.1', '::1'], true) && !str_ends_with($host, '.local');
}
public function verify_callback(\WP_REST_Request $request): bool {
$token = sanitize_text_field((string) ($request->get_param('CallbackToken') ?: $request->get_param('callbackToken')));
$session = sanitize_text_field((string) ($request->get_param('certifyId') ?: $request->get_param('CertifyId')));
if ($token === '' || $session === '') {
return false;
}
global $wpdb;
$table = \AKSRT\Core\DBMigrator::table('identity_application');
$uuid = (string) $wpdb->get_var($wpdb->prepare(
"SELECT application_uuid FROM {$table} WHERE provider = 'aliyun' AND provider_session_id = %s LIMIT 1",
$session
));
return $uuid !== '' && hash_equals(hash_hmac('sha256', $uuid, wp_salt('nonce')), $token);
}
public function parse_callback(\WP_REST_Request $request): ProviderResult {
$session = sanitize_text_field((string) ($request->get_param('certifyId') ?: $request->get_param('CertifyId')));
$outer_order = sanitize_text_field((string) ($request->get_param('outerOrderNo') ?: $request->get_param('OuterOrderNo')));
return ProviderResult::pending(['provider_session_id' => $session, 'outer_order_no' => $outer_order, 'result_code' => 'callback_received']);
}
private function init_face_verify(array $request): ProviderResult {
// Ref: https://api.aliyun.com/document/Cloudauth/2019-03-07/InitFaceVerify
$cfg = SettingsRuntime::get();
$callback_token = hash_hmac('sha256', (string) ($request['application_uuid'] ?? ''), wp_salt('nonce'));
$params = [
'SceneId' => (string) $cfg['personal_flow'],
'OuterOrderNo' => (string) ($request['application_uuid'] ?? wp_generate_uuid4()),
'ProductCode' => (string) $cfg['product_code'],
'CertType' => 'IDENTITY_CARD',
'CertName' => (string) ($request['person_name'] ?? ''),
'CertNo' => preg_replace('/\s+/', '', (string) ($request['id_number'] ?? '')),
];
$meta_info = trim((string) ($request['meta_info'] ?? ''));
if ($meta_info !== '') {
$params['MetaInfo'] = $meta_info;
}
$return_url = esc_url_raw((string) ($request['return_url'] ?? ''));
if ($this->is_public_https_url($return_url)) {
$params['ReturnUrl'] = $return_url;
}
$callback_url = esc_url_raw(rest_url('aksrt/v1/identity/callback/aliyun'));
if ($this->is_public_https_url($callback_url)) {
$params['CallbackUrl'] = $callback_url;
$params['CallbackToken'] = $callback_token;
}
$response = $this->rpc('cloudauth.aliyuncs.com', '2019-03-07', 'InitFaceVerify', $params);
if (is_wp_error($response)) {
return ProviderResult::failed($response->get_error_code(), $response->get_error_message());
}
$code = sanitize_text_field((string) ($response['Code'] ?? ''));
if ($code !== '' && $code !== '200') {
return ProviderResult::failed($code, sanitize_text_field((string) ($response['Message'] ?? '')));
}
$object = $this->normalize_result_object($response['ResultObject'] ?? []);
$certify_id = sanitize_text_field((string) $this->first_response_value($response, [
['ResultObject', 'CertifyId'],
['ResultObject', 'certifyId'],
['CertifyId'],
['certifyId'],
['Data', 'CertifyId'],
['Data', 'certifyId'],
]));
$url = esc_url_raw((string) $this->first_response_value(array_merge($response, ['ResultObject' => $object]), [
['ResultObject', 'CertifyUrl'],
['ResultObject', 'certifyUrl'],
['ResultObject', 'Url'],
['ResultObject', 'url'],
['CertifyUrl'],
['certifyUrl'],
['Url'],
['url'],
['Data', 'CertifyUrl'],
['Data', 'certifyUrl'],
['Data', 'Url'],
['Data', 'url'],
]));
if ($certify_id === '') {
$debug = $this->response_debug_summary($response, $object, [
'has_certify_id' => false,
'has_certify_url' => $url !== '',
]);
$this->log_debug('InitFaceVerify missing CertifyId', $debug);
return ProviderResult::failed('aliyun_invalid_response', sprintf(
__('阿里云未返回有效认证会话:%s', 'aksrt'),
$debug
));
}
if ($url === '') {
$debug = $this->response_debug_summary($response, $object, [
'has_certify_id' => true,
'has_certify_url' => false,
]);
$this->log_debug('InitFaceVerify returned CertifyId without URL', $debug);
return ProviderResult::failed('aliyun_missing_certify_url', sprintf(
__('阿里云只返回了 CertifyId,未返回可打开的核身链接。请确认 SceneId/ProductCode 对应的是支持 H5 链接的实人认证方案;调试信息:%s', 'aksrt'),
$debug
));
}
return ProviderResult::pending([
'provider_session_id' => $certify_id,
'request_id' => sanitize_text_field((string) ($response['RequestId'] ?? '')),
'redirect_url' => $url,
'result_code' => 'session_created',
'expires_at' => gmdate('Y-m-d H:i:s', time() + ((int) $cfg['session_ttl_minutes'] * MINUTE_IN_SECONDS)),
]);
}
/** @return array<string,mixed>|\WP_Error */
private function rpc(string $host, string $version, string $action, array $business) {
$cfg = SettingsRuntime::get();
$endpoint = 'https://' . $host . '/';
// The official PHP SDK uses ACS3-HMAC-SHA256 by default. This zero-dependency
// fallback deliberately uses the documented RPC v2 signature until the SDK
// packages can be installed and locked in this deployment.
$params = array_merge([
'Format' => 'JSON',
'Version' => $version,
'AccessKeyId' => (string) $cfg['credentials']['access_key_id'],
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce' => wp_generate_uuid4(),
'SignatureVersion' => '1.0',
'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
'Action' => $action,
], $business);
ksort($params);
$canonical = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$string_to_sign = 'POST&%2F&' . rawurlencode($canonical);
$params['Signature'] = base64_encode(hash_hmac('sha1', $string_to_sign, (string) $cfg['credentials']['access_key_secret'] . '&', true));
$response = wp_remote_post($endpoint, [
'timeout' => 20,
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'body' => $params,
]);
if (is_wp_error($response)) {
return new \WP_Error('aliyun_network_error', __('阿里云接口请求失败', 'aksrt'));
}
$status_code = (int) wp_remote_retrieve_response_code($response);
$body = (string) wp_remote_retrieve_body($response);
$decoded = json_decode($body, true);
if (!is_array($decoded)) {
$this->log_debug('Aliyun invalid JSON response', [
'http_status' => $status_code,
'body_preview' => $this->truncate_debug($body, 800),
]);
return new \WP_Error('aliyun_invalid_json', __('阿里云返回格式无效', 'aksrt'));
}
if (defined('WP_DEBUG') && WP_DEBUG) {
$this->log_debug('Aliyun RPC response', [
'action' => $action,
'http_status' => $status_code,
'summary' => $this->response_debug_summary($decoded),
]);
}
return $decoded;
}
private function enterprise_passed(array $response): bool {
$result = is_array($response['Result'] ?? null) ? $response['Result'] : [];
return (string) ($response['Code'] ?? '') === 'Success'
&& (string) ($result['BizCode'] ?? '') === '1'
&& (string) ($result['Status'] ?? '') === '1';
}
/** @param mixed $value @return array<string,mixed> */
private function normalize_result_object($value): array {
if (is_array($value)) {
return $value;
}
if (is_string($value) && $value !== '') {
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : [];
}
return [];
}
/** @param array<string,mixed> $response @param array<int,array<int,string>> $paths */
private function first_response_value(array $response, array $paths): string {
foreach ($paths as $path) {
$value = $response;
foreach ($path as $segment) {
if (!is_array($value) || !array_key_exists($segment, $value)) {
$value = null;
break;
}
$value = $value[$segment];
}
if (is_scalar($value) && (string) $value !== '') {
return (string) $value;
}
}
return '';
}
/** @param array<string,mixed> $response @param array<string,mixed> $object @param array<string,mixed> $extra */
private function response_debug_summary(array $response, array $object = [], array $extra = []): string {
$summary = array_merge([
'code' => (string) ($response['Code'] ?? ''),
'message' => (string) ($response['Message'] ?? ''),
'request_id' => (string) ($response['RequestId'] ?? ''),
'top_keys' => implode(',', array_slice(array_keys($response), 0, 20)),
'result_keys' => $object !== [] ? implode(',', array_slice(array_keys($object), 0, 20)) : '',
], $extra);
return wp_json_encode($summary, JSON_UNESCAPED_UNICODE) ?: '';
}
/** @param mixed $data */
private function log_debug(string $message, $data): void {
if (!defined('WP_DEBUG') || !WP_DEBUG) {
return;
}
error_log('[AKSRT Identity Aliyun] ' . $message . ': ' . (is_string($data) ? $data : (wp_json_encode($data, JSON_UNESCAPED_UNICODE) ?: '')));
}
private function truncate_debug(string $value, int $length): string {
return function_exists('mb_substr') ? mb_substr($value, 0, $length) : substr($value, 0, $length);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
/**
* Identity provider factory.
*
* @package AKSRT
*/
namespace AKSRT\Identity\Provider;
defined('ABSPATH') || exit;
final class ProviderFactory {
public static function make(string $provider): ProviderInterface {
$provider = sanitize_key($provider);
if ($provider === 'tencent') {
return new TencentProvider();
}
return new AliyunProvider();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Identity provider contract.
*
* @package AKSRT
*/
namespace AKSRT\Identity\Provider;
defined('ABSPATH') || exit;
interface ProviderInterface {
public function key(): string;
/** @return array{personal:bool,enterprise:bool} */
public function capabilities(): array;
/** @return true|\WP_Error */
public function validate_config();
/** @param array<string,mixed> $request */
public function start_personal(array $request): ProviderResult;
/** @param array<string,mixed> $request */
public function start_enterprise(array $request): ProviderResult;
/** @param array<string,mixed> $application */
public function query(array $application): ProviderResult;
public function verify_callback(\WP_REST_Request $request): bool;
public function parse_callback(\WP_REST_Request $request): ProviderResult;
}
+41
View File
@@ -0,0 +1,41 @@
<?php
/**
* Normalized identity provider result.
*
* @package AKSRT
*/
namespace AKSRT\Identity\Provider;
defined('ABSPATH') || exit;
final class ProviderResult {
public const PENDING = 'pending';
public const PASSED = 'passed';
public const FAILED = 'failed';
public const UNSUPPORTED = 'unsupported';
public const EXPIRED = 'expired';
/** @param array<string,mixed> $data */
public function __construct(
public readonly string $decision,
public readonly array $data = []
) {}
public static function pending(array $data = []): self {
return new self(self::PENDING, $data);
}
public static function passed(array $data = []): self {
return new self(self::PASSED, $data);
}
public static function failed(string $code, string $message = ''): self {
return new self(self::FAILED, ['result_code' => $code, 'message' => $message]);
}
public static function unsupported(string $message): self {
return new self(self::UNSUPPORTED, ['result_code' => 'unsupported', 'message' => $message]);
}
}
+202
View File
@@ -0,0 +1,202 @@
<?php
/**
* Tencent Cloud FaceId provider.
*
* @package AKSRT
*/
namespace AKSRT\Identity\Provider;
use AKSRT\Identity\SettingsRuntime;
defined('ABSPATH') || exit;
final class TencentProvider implements ProviderInterface {
private const VERSION = '2018-03-01';
private const SERVICE = 'faceid';
private const ENDPOINT = 'faceid.tencentcloudapi.com';
public function key(): string { return 'tencent'; }
public function capabilities(): array { return ['personal' => true, 'enterprise' => true]; }
public function validate_config() {
$cfg = SettingsRuntime::get();
foreach (['secret_id', 'secret_key'] as $key) {
if (empty($cfg['credentials'][$key])) {
return new \WP_Error('aksrt_identity_tencent_credentials', __('腾讯云人脸核身凭证不完整', 'aksrt'));
}
}
if (empty($cfg['personal_flow'])) {
return new \WP_Error('aksrt_identity_tencent_rule', __('请配置腾讯云人脸核身 RuleId', 'aksrt'));
}
return true;
}
public function start_personal(array $request): ProviderResult {
// Ref: https://cloud.tencent.com/document/product/1007/31816
$cfg = SettingsRuntime::get();
$payload = [
'RuleId' => (string) $cfg['personal_flow'],
'TerminalType' => $this->terminal_type(),
'RedirectUrl' => esc_url_raw((string) ($request['return_url'] ?? '')),
'Extra' => (string) ($request['application_uuid'] ?? ''),
];
if (!empty($request['person_name'])) {
$payload['Name'] = (string) $request['person_name'];
}
if (!empty($request['id_number'])) {
$payload['IdCard'] = preg_replace('/\s+/', '', (string) $request['id_number']);
}
$response = $this->request('DetectAuth', $payload);
if (is_wp_error($response)) {
return ProviderResult::failed($response->get_error_code(), $response->get_error_message());
}
$data = is_array($response['Response'] ?? null) ? $response['Response'] : [];
if (!empty($data['Error'])) {
return ProviderResult::failed((string) ($data['Error']['Code'] ?? 'tencent_error'), (string) ($data['Error']['Message'] ?? ''));
}
$biz_token = sanitize_text_field((string) ($data['BizToken'] ?? ''));
$url = esc_url_raw((string) ($data['Url'] ?? ''));
if ($biz_token === '' || $url === '') {
return ProviderResult::failed('tencent_invalid_response', __('腾讯云未返回有效认证会话', 'aksrt'));
}
return ProviderResult::pending([
'provider_session_id' => $biz_token,
'request_id' => sanitize_text_field((string) ($data['RequestId'] ?? '')),
'redirect_url' => $url,
'result_code' => 'session_created',
'expires_at' => gmdate('Y-m-d H:i:s', time() + ((int) $cfg['session_ttl_minutes'] * MINUTE_IN_SECONDS)),
]);
}
public function start_enterprise(array $request): ProviderResult {
// Ref: https://cloud.tencent.com/document/product/866/129072
foreach (['company_name', 'company_code', 'person_name', 'id_number'] as $key) {
if (empty($request[$key])) {
return ProviderResult::failed('tencent_enterprise_fields', __('企业认证资料不完整', 'aksrt'));
}
}
$response = $this->request_service('ocr', 'ocr.tencentcloudapi.com', '2018-11-19', 'VerifyBizLicenseEnterprise4', [
'CreditCode' => preg_replace('/\s+/', '', (string) $request['company_code']),
'EntName' => (string) $request['company_name'],
'LrName' => (string) $request['person_name'],
'IdNum' => preg_replace('/\s+/', '', (string) $request['id_number']),
]);
if (is_wp_error($response)) {
return ProviderResult::failed($response->get_error_code(), $response->get_error_message());
}
$data = is_array($response['Response'] ?? null) ? $response['Response'] : [];
if (!empty($data['Error'])) {
return ProviderResult::failed((string) ($data['Error']['Code'] ?? 'tencent_ocr_error'), (string) ($data['Error']['Message'] ?? ''));
}
if (!$this->enterprise_passed($data)) {
return ProviderResult::failed('tencent_enterprise_mismatch', __('企业工商四要素或法人关系核验未通过', 'aksrt'));
}
return $this->start_personal($request);
}
public function query(array $application): ProviderResult {
// Ref: https://cloud.tencent.com/document/product/1007/41957
$response = $this->request('GetDetectInfoEnhanced', [
'BizToken' => (string) ($application['provider_session_id'] ?? ''),
'RuleId' => (string) ($application['provider_flow'] ?? ''),
'InfoType' => '0',
]);
if (is_wp_error($response)) {
return ProviderResult::pending(['result_code' => $response->get_error_code(), 'message' => __('认证结果暂未取回,请稍后重试', 'aksrt')]);
}
$data = is_array($response['Response'] ?? null) ? $response['Response'] : [];
if (!empty($data['Error'])) {
return ProviderResult::failed((string) ($data['Error']['Code'] ?? 'tencent_error'), (string) ($data['Error']['Message'] ?? ''));
}
$text = $data['Text'] ?? ($data['DetectInfo']['Text'] ?? []);
if (is_string($text)) {
$decoded_text = json_decode($text, true);
$text = is_array($decoded_text) ? $decoded_text : [];
} elseif (!is_array($text)) {
$text = [];
}
$result = (string) ($text['ErrCode'] ?? '');
$live_status = (string) ($text['LiveStatus'] ?? '');
$compare_status = (string) ($text['Comparestatus'] ?? '');
if ($result === '0' && ($live_status === '' || $live_status === '0') && ($compare_status === '' || $compare_status === '0')) {
return ProviderResult::passed(['request_id' => (string) ($data['RequestId'] ?? ''), 'result_code' => '0']);
}
$message = sanitize_text_field((string) ($text['ErrMsg'] ?? $text['LiveMsg'] ?? $text['Comparemsg'] ?? ''));
if ($result === '') {
return ProviderResult::pending(['result_code' => 'processing', 'message' => __('腾讯云仍在处理认证结果', 'aksrt')]);
}
return ProviderResult::failed($result, $message);
}
public function verify_callback(\WP_REST_Request $request): bool { unset($request); return false; }
public function parse_callback(\WP_REST_Request $request): ProviderResult { unset($request); return ProviderResult::unsupported(__('腾讯云人脸核身使用服务端主动查询,不接收结果回调', 'aksrt')); }
/** @return array<string,mixed>|\WP_Error */
private function request(string $action, array $payload) {
return $this->request_service(self::SERVICE, self::ENDPOINT, self::VERSION, $action, $payload);
}
/** @return array<string,mixed>|\WP_Error */
private function request_service(string $service, string $host, string $version, string $action, array $payload) {
$cfg = SettingsRuntime::get();
$endpoint = 'https://' . $host;
$timestamp = time();
$date = gmdate('Y-m-d', $timestamp);
$body = (string) wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$canonical_headers = "content-type:application/json; charset=utf-8\nhost:{$host}\nx-tc-action:" . strtolower($action) . "\n";
$signed_headers = 'content-type;host;x-tc-action';
$canonical_request = "POST\n/\n\n{$canonical_headers}\n{$signed_headers}\n" . hash('sha256', $body);
$scope = $date . '/' . $service . '/tc3_request';
$string_to_sign = "TC3-HMAC-SHA256\n{$timestamp}\n{$scope}\n" . hash('sha256', $canonical_request);
$secret_key = (string) $cfg['credentials']['secret_key'];
$secret_date = hash_hmac('sha256', $date, 'TC3' . $secret_key, true);
$secret_service = hash_hmac('sha256', $service, $secret_date, true);
$secret_signing = hash_hmac('sha256', 'tc3_request', $secret_service, true);
$signature = hash_hmac('sha256', $string_to_sign, $secret_signing);
$authorization = 'TC3-HMAC-SHA256 Credential=' . $cfg['credentials']['secret_id'] . '/' . $scope . ', SignedHeaders=' . $signed_headers . ', Signature=' . $signature;
$headers = [
'Authorization' => $authorization,
'Content-Type' => 'application/json; charset=utf-8',
'Host' => $host,
'X-TC-Action' => $action,
'X-TC-Timestamp' => (string) $timestamp,
'X-TC-Version' => $version,
];
if ($service !== self::SERVICE && !empty($cfg['region'])) {
$headers['X-TC-Region'] = (string) $cfg['region'];
}
$response = wp_remote_post($endpoint, [
'timeout' => 20,
'headers' => $headers,
'body' => $body,
]);
if (is_wp_error($response)) {
return new \WP_Error('tencent_network_error', __('腾讯云接口请求失败', 'aksrt'));
}
$decoded = json_decode((string) wp_remote_retrieve_body($response), true);
return is_array($decoded) ? $decoded : new \WP_Error('tencent_invalid_json', __('腾讯云返回格式无效', 'aksrt'));
}
private function enterprise_passed(array $data): bool {
if ((string) ($data['StatusCode'] ?? '') !== '0' || (string) ($data['VerifyResult'] ?? '') !== '1') {
return false;
}
foreach (['IsCreditCodeConsistent', 'IsEntNameConsistent', 'IsLrNameConsistent', 'IsIdNumConsistent'] as $field) {
$value = $data[$field] ?? null;
if (!in_array($value, [true, 1, '1', 'true'], true)) {
return false;
}
}
$status = strtoupper((string) ($data['OperatingStatus'] ?? $data['RegStatus'] ?? ''));
return !in_array($status, ['吊销', '注销', 'REVOKED', 'CANCELLED'], true);
}
private function terminal_type(): string {
$ua = strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
return str_contains($ua, 'mobile') ? '1' : '2';
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
/**
* Public identity verification REST API.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class RestController {
private const NS = 'aksrt/v1';
public function __construct(
private ?ApplicationRepository $applications = null,
private ?ApplicationService $service = null
) {
$this->applications ??= new ApplicationRepository();
$this->service ??= new ApplicationService($this->applications);
}
public function register_routes(): void {
register_rest_route(self::NS, '/identity/applications', [
'methods' => 'POST',
'callback' => [$this, 'create'],
'permission_callback' => [$this, 'logged_in'],
]);
register_rest_route(self::NS, '/identity/applications/current', [
'methods' => 'GET',
'callback' => [$this, 'current'],
'permission_callback' => [$this, 'logged_in'],
]);
register_rest_route(self::NS, '/identity/applications/(?P<uuid>[a-f0-9-]{36})', [
'methods' => 'GET',
'callback' => [$this, 'get'],
'permission_callback' => [$this, 'owns_application'],
]);
register_rest_route(self::NS, '/identity/applications/(?P<uuid>[a-f0-9-]{36})/refresh', [
'methods' => 'POST',
'callback' => [$this, 'refresh'],
'permission_callback' => [$this, 'owns_application'],
]);
register_rest_route(self::NS, '/identity/applications/(?P<uuid>[a-f0-9-]{36})/manual', [
'methods' => 'POST',
'callback' => [$this, 'manual'],
'permission_callback' => [$this, 'owns_application'],
]);
}
public function logged_in(): bool {
return is_user_logged_in();
}
public function owns_application(\WP_REST_Request $request): bool {
if (!is_user_logged_in()) {
return false;
}
$application = $this->applications->find_by_uuid((string) $request['uuid']);
return is_array($application) && (int) $application['user_id'] === get_current_user_id();
}
public function create(\WP_REST_Request $request): \WP_REST_Response {
$params = $request->get_json_params();
$params = is_array($params) ? $params : [];
$result = $this->service->create(get_current_user_id(), $params);
return $this->respond($result, 201);
}
public function current(): \WP_REST_Response {
$application = $this->applications->latest_for_user(get_current_user_id());
return new \WP_REST_Response(['success' => true, 'data' => $application ? $this->service->view($application) : null]);
}
public function get(\WP_REST_Request $request): \WP_REST_Response {
$application = $this->applications->find_by_uuid((string) $request['uuid']);
return new \WP_REST_Response(['success' => true, 'data' => $this->service->view($application)]);
}
public function refresh(\WP_REST_Request $request): \WP_REST_Response {
$application = $this->applications->find_by_uuid((string) $request['uuid']);
return $this->respond($this->service->refresh($application));
}
public function manual(\WP_REST_Request $request): \WP_REST_Response {
$application = $this->applications->find_by_uuid((string) $request['uuid']);
return $this->respond($this->service->move_to_manual($application, $_FILES['evidence'] ?? null));
}
private function respond($result, int $success_status = 200): \WP_REST_Response {
if (is_wp_error($result)) {
$status = in_array($result->get_error_code(), ['aksrt_identity_active', 'aksrt_identity_verified', 'aksrt_identity_conflict'], true) ? 409 : 422;
return new \WP_REST_Response([
'success' => false,
'code' => $result->get_error_code(),
'message' => $result->get_error_message(),
], $status);
}
return new \WP_REST_Response(['success' => true, 'data' => $result], $success_status);
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
/**
* Encrypted identity provider credential storage.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class SecretStore {
public const OPTION_KEY = 'aksrt_identity_secrets';
private const CONTEXT = 'aksrt-identity-secrets-v1';
/** @return array<string,string> */
public static function get(string $provider): array {
$stored = get_option(self::OPTION_KEY, []);
$record = is_array($stored) ? ($stored[sanitize_key($provider)] ?? null) : null;
if (!is_array($record)) {
return [];
}
$plain = self::decrypt($record);
if ($plain === '') {
return [];
}
$data = json_decode($plain, true);
if (!is_array($data)) {
return [];
}
$clean = [];
foreach ($data as $key => $value) {
if (is_string($key) && is_string($value)) {
$clean[sanitize_key($key)] = $value;
}
}
return $clean;
}
/** @param array<string,string|null> $changes */
public static function update(string $provider, array $changes): bool {
$provider = sanitize_key($provider);
if (!in_array($provider, ['aliyun', 'tencent'], true)) {
return false;
}
$current = self::get($provider);
foreach ($changes as $key => $value) {
$key = sanitize_key((string) $key);
if ($key === '') {
continue;
}
if ($value === null) {
unset($current[$key]);
} elseif (is_string($value) && $value !== '') {
$current[$key] = $value;
}
}
$stored = get_option(self::OPTION_KEY, []);
$stored = is_array($stored) ? $stored : [];
if ($current === []) {
unset($stored[$provider]);
} else {
$record = self::encrypt((string) wp_json_encode($current));
if (is_wp_error($record)) {
return false;
}
$stored[$provider] = $record;
}
return update_option(self::OPTION_KEY, $stored, false) || get_option(self::OPTION_KEY, []) === $stored;
}
/** @return array<string,array{configured:bool,fingerprint:string}> */
public static function status(string $provider): array {
$status = [];
foreach (self::get($provider) as $key => $value) {
$status[$key] = [
'configured' => $value !== '',
'fingerprint' => $value !== '' ? substr(hash('sha256', $value), -4) : '',
];
}
return $status;
}
/** @return array<string,string>|\WP_Error */
private static function encrypt(string $plain) {
$key = self::key();
if (function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES);
$cipher = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($plain, self::CONTEXT, $nonce, $key);
return ['driver' => 'sodium', 'nonce' => base64_encode($nonce), 'cipher' => base64_encode($cipher)];
}
if (function_exists('openssl_encrypt')) {
$nonce = random_bytes(12);
$tag = '';
$cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, self::CONTEXT);
if (!is_string($cipher)) {
return new \WP_Error('aksrt_identity_encrypt', __('身份认证凭证加密失败', 'aksrt'));
}
return ['driver' => 'openssl', 'nonce' => base64_encode($nonce), 'tag' => base64_encode($tag), 'cipher' => base64_encode($cipher)];
}
return new \WP_Error('aksrt_identity_crypto', __('服务器不支持安全凭证加密', 'aksrt'));
}
/** @param array<string,mixed> $record */
private static function decrypt(array $record): string {
$nonce = base64_decode((string) ($record['nonce'] ?? ''), true);
$cipher = base64_decode((string) ($record['cipher'] ?? ''), true);
if (!is_string($nonce) || !is_string($cipher)) {
return '';
}
$key = self::key();
if (($record['driver'] ?? '') === 'sodium' && function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_decrypt')) {
$plain = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($cipher, self::CONTEXT, $nonce, $key);
return is_string($plain) ? $plain : '';
}
if (($record['driver'] ?? '') === 'openssl' && function_exists('openssl_decrypt')) {
$tag = base64_decode((string) ($record['tag'] ?? ''), true);
if (!is_string($tag)) {
return '';
}
$plain = openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, self::CONTEXT);
return is_string($plain) ? $plain : '';
}
return '';
}
private static function key(): string {
return hash_hmac('sha256', self::CONTEXT, wp_salt('auth') . wp_salt('secure_auth'), true);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
/**
* Identity verification settings facade.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class SettingsRuntime {
/** @return array<string,mixed> */
public static function get(): array {
$settings = \AKSRT\Settings\Settings::get_all();
$provider = sanitize_key((string) ($settings['user_verify_provider'] ?? 'aliyun'));
if (!in_array($provider, ['aliyun', 'tencent'], true)) {
$provider = 'aliyun';
}
return [
'enabled' => !isset($settings['user_verify_enabled']) || !empty($settings['user_verify_enabled']),
'allow_apply' => !isset($settings['user_verify_allow_apply']) || !empty($settings['user_verify_allow_apply']),
'provider' => $provider,
'allow_manual_fallback' => !isset($settings['user_verify_allow_manual_fallback']) || !empty($settings['user_verify_allow_manual_fallback']),
'session_ttl_minutes' => max(5, min(1440, (int) ($settings['user_verify_session_ttl_minutes'] ?? 30))),
'poll_interval_seconds' => max(3, min(60, (int) ($settings['user_verify_poll_interval_seconds'] ?? 5))),
'max_retries' => max(0, min(3, (int) ($settings['user_verify_max_retries'] ?? 1))),
'personal_flow' => sanitize_text_field((string) ($settings['user_verify_' . $provider . '_personal_flow'] ?? '')),
'product_code' => $provider === 'aliyun' && in_array(($settings['user_verify_aliyun_product_code'] ?? 'ID_PRO'), ['ID_PRO', 'PV_FV', 'LR_FR'], true)
? (string) $settings['user_verify_aliyun_product_code']
: 'ID_PRO',
'enterprise_flow' => sanitize_text_field((string) ($settings['user_verify_' . $provider . '_enterprise_flow'] ?? '')),
'region' => sanitize_text_field((string) ($settings['user_verify_' . $provider . '_region'] ?? '')),
'credentials' => SecretStore::get($provider),
];
}
public static function hmac(string $value): string {
return hash_hmac('sha256', trim($value), wp_salt('secure_auth') . '|aksrt-identity-hmac');
}
public static function mask_id_number(string $value): string {
$value = preg_replace('/\s+/', '', $value) ?: '';
$length = strlen($value);
if ($length <= 8) {
return str_repeat('*', max(0, $length - 2)) . substr($value, -2);
}
return substr($value, 0, 3) . str_repeat('*', $length - 7) . substr($value, -4);
}
public static function mask_name(string $value): string {
$value = trim($value);
$length = function_exists('mb_strlen') ? mb_strlen($value) : strlen($value);
if ($length <= 1) {
return '*';
}
$first = function_exists('mb_substr') ? mb_substr($value, 0, 1) : substr($value, 0, 1);
return $first . str_repeat('*', max(1, $length - 1));
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
/**
* Identity verification state transitions.
*
* @package AKSRT
*/
namespace AKSRT\Identity;
defined('ABSPATH') || exit;
final class TransitionService {
private const ALLOWED = [
'created' => ['provider_pending', 'provider_failed', 'provider_unsupported', 'provider_expired', 'manual_pending', 'cancelled'],
'provider_pending' => ['provider_processing', 'provider_failed', 'provider_unsupported', 'provider_expired', 'verified', 'manual_pending', 'cancelled'],
'provider_processing' => ['provider_failed', 'provider_unsupported', 'provider_expired', 'verified', 'manual_pending'],
'provider_failed' => ['provider_pending', 'manual_pending', 'rejected', 'cancelled'],
'provider_unsupported' => ['manual_pending', 'rejected', 'cancelled'],
'provider_expired' => ['provider_pending', 'manual_pending', 'rejected', 'cancelled'],
'manual_pending' => ['verified', 'rejected', 'cancelled'],
'verified' => ['cancelled'],
];
public function __construct(
private ?ApplicationRepository $applications = null,
private ?EventRepository $events = null
) {
$this->applications ??= new ApplicationRepository();
$this->events ??= new EventRepository();
}
/** @param array<string,mixed> $fields @param array<string,mixed> $event */
public function transition(array $application, string $next, array $fields = [], array $event = []) {
$current = sanitize_key((string) ($application['status'] ?? ''));
$next = sanitize_key($next);
if (!in_array($next, self::ALLOWED[$current] ?? [], true)) {
return new \WP_Error('aksrt_identity_transition', __('该认证记录当前不可执行此操作', 'aksrt'));
}
if (in_array($next, ['verified', 'rejected', 'cancelled'], true)) {
$fields['completed_at'] = current_time('mysql', true);
$fields['sensitive_blob'] = null;
}
if (!$this->applications->transition((int) $application['id'], $current, $next, $fields)) {
return new \WP_Error('aksrt_identity_conflict', __('认证状态已变化,请刷新后重试', 'aksrt'));
}
$dedupe = (string) ($event['dedupe_key'] ?? hash('sha256', implode('|', [
(string) $application['application_uuid'], $current, $next, wp_generate_uuid4(),
])));
$this->events->record([
'application_id' => (int) $application['id'],
'source' => (string) ($event['source'] ?? 'system'),
'event_type' => (string) ($event['event_type'] ?? 'status_changed'),
'external_event_id' => (string) ($event['external_event_id'] ?? ''),
'dedupe_key' => $dedupe,
'from_status' => $current,
'to_status' => $next,
'result_code' => (string) ($event['result_code'] ?? ''),
'summary' => is_array($event['summary'] ?? null) ? $event['summary'] : [],
'actor_user_id' => (int) ($event['actor_user_id'] ?? 0),
]);
if ($next === 'verified') {
$this->send_notification((int) $application['user_id'], 'verified', '');
} elseif ($next === 'rejected' || $next === 'cancelled') {
$this->send_notification((int) $application['user_id'], $next, (string) ($fields['review_note'] ?? ''));
}
do_action('aksrt_user_auth_reviewed', (int) $application['user_id'], self::public_status($next), (string) ($fields['review_note'] ?? ''), (int) ($fields['reviewer_id'] ?? 0));
return $this->applications->find_by_id((int) $application['id']);
}
public static function public_status(string $status): string {
if ($status === 'verified') {
return 'verified';
}
if ($status === 'cancelled') {
return 'cancelled';
}
if ($status === 'rejected') {
return 'rejected';
}
return in_array($status, ApplicationRepository::ACTIVE_STATUSES, true) ? 'pending' : 'rejected';
}
private function send_notification(int $user_id, string $status, string $note): void {
if (!class_exists('\\AKSRT\\Messages\\Message')) {
return;
}
if ($status === 'verified') {
$title = __('官方认证结果', 'aksrt');
$message = __('您的官方认证已通过', 'aksrt');
} elseif ($status === 'cancelled') {
$title = __('官方认证已取消', 'aksrt');
$message = sprintf(__('您的官方认证已被取消:%s', 'aksrt'), $note);
} else {
$title = __('官方认证结果', 'aksrt');
$message = sprintf(__('您的官方认证申请未通过:%s', 'aksrt'), $note);
}
\AKSRT\Messages\Message::get_instance()->send($user_id, 'auth_apply_reply', $message, [
'title' => $title,
'target_url' => aksrt_get_user_center_tab_url('auth'),
]);
}
}