CaiWuXiTong/modules/EcommerceFinance/Services/SupplierSummaryAICard.php
苏木 770ddea8a9 feat(供应商对账): 增加免登录送货确认链接 (#1180)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 11:36:27 +08:00

530 lines
20 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\EcommerceFinance\Services;
use App\Services\Auth\DingTalkOAuthClient;
use Illuminate\Http\Client\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use RuntimeException;
/**
* 供应商月度货款对账的钉钉 AI 互动卡片。
*
* 卡片使用 HTTP 回传请求:厂家点击“厂家确认”后,钉钉直接调用财务系统
* 公网回调,不需要打开 H5 页面。卡片不允许转发,避免把确认权限扩散到其他群。
*/
class SupplierSummaryAICard
{
public function __construct(
private readonly DingTalkOAuthClient $oauth,
private readonly SupplierSummaryConfirmation $confirmations,
) {
}
/**
* @return array{messages:int,qty:float,amount:float,period:string,out_track_id:string}
*/
public function push(
string $supplier,
string $month,
float $qty,
float $amount,
string $pushBasis,
int $companyId,
?int $userId,
string $openConversationId,
string $robotCode = '',
string $robotName = '',
): array {
if (! config('dingtalk.card.enabled', true)) {
throw ValidationException::withMessages([
'dingtalk_summary_push' => '钉钉互动卡片已在系统配置中关闭。',
]);
}
$openConversationId = $this->normalizeOpenConversationId($openConversationId);
if ($openConversationId === '') {
throw ValidationException::withMessages([
'dingtalk_summary_push' => '该厂家尚未配置互动卡片群会话 ID,请展开“厂家钉钉群机器人”补齐后再推送。',
]);
}
if (! $this->oauth->hasApplicationCredentials()) {
throw ValidationException::withMessages([
'dingtalk_summary_push' => '财务系统尚未配置钉钉企业内部应用凭证,无法发送互动卡片。',
]);
}
$period = $this->displayMonth($month);
$outTrackId = 'supplier-summary-c' . $companyId . '-' . bin2hex(random_bytes(16));
$surfaceId = 'supplier-summary-' . substr(hash('sha256', $outTrackId), 0, 20);
$record = $this->confirmations->create(
$outTrackId,
$supplier,
$month,
$pushBasis,
$qty,
$amount,
$companyId,
$userId,
);
try {
$token = $this->oauth->appAccessToken();
$this->registerCallback($token);
$selectedRobotCode = $this->resolveRobotCode($token, $openConversationId, $robotCode, $robotName);
$this->createAndDeliver(
$token,
$outTrackId,
$surfaceId,
$openConversationId,
$selectedRobotCode,
$supplier,
$period,
$qty,
$amount,
);
$this->confirmations->markSent($outTrackId, $companyId);
} catch (\Throwable $exception) {
$this->confirmations->markFailed(
$outTrackId,
$companyId,
$exception->getMessage(),
);
throw $exception;
}
return [
'messages' => 1,
'qty' => round($qty, 4),
'amount' => round($amount, 2),
'period' => $period,
'out_track_id' => $outTrackId,
];
}
/** @param array<string,mixed> $record */
public function updateConfirmed(array $record): void
{
$outTrackId = trim((string) ($record['_action_key'] ?? ''));
if ($outTrackId === '') {
return;
}
$surfaceId = 'supplier-summary-' . substr(hash('sha256', $outTrackId), 0, 20);
$confirmedAt = trim((string) ($record['confirmed_at'] ?? ''));
$statusText = '厂家已确认' . ($confirmedAt !== '' ? ' · ' . $confirmedAt : '');
$messages = [
[
'version' => 'v1.0',
'updateDataModel' => [
'surfaceId' => $surfaceId,
'path' => '/confirmation/text',
'value' => $statusText,
],
],
[
'version' => 'v1.0',
'updateComponents' => [
'surfaceId' => $surfaceId,
'components' => [
[
'id' => 'status',
'component' => 'Text',
'variant' => 'caption',
'text' => ['path' => '/confirmation/text'],
],
[
'id' => 'confirm-button',
'component' => 'Button',
'variant' => 'primary',
'child' => 'confirm-label',
'disabled' => true,
'action' => [
'event' => [
'name' => 'confirm_supplier_summary',
'context' => ['action' => 'confirm'],
],
],
],
[
'id' => 'confirm-label',
'component' => 'Text',
'text' => '已确认',
],
],
],
],
];
$this->put('/v1.0/card/ai/instances/update', [
'outTrackId' => $outTrackId,
'outUpdateId' => $outTrackId . '-confirmed',
'flowStatus' => 'CONFIRMED',
'a2uiMessages' => $this->wireMessages($messages),
], $this->oauth->appAccessToken());
}
public function assertValidCallbackSignature(Request $request): void
{
$timestamp = trim((string) $request->header('x-ddpaas-signature-timestamp', ''));
$signature = trim((string) $request->header('x-ddpaas-signature', ''));
if ($timestamp === '' || $signature === '' || ! ctype_digit($timestamp)) {
abort(403, '互动卡片回调签名缺失。');
}
$timestampSeconds = strlen($timestamp) >= 13
? intdiv((int) $timestamp, 1000)
: (int) $timestamp;
if (abs(now()->timestamp - $timestampSeconds) > 600) {
abort(403, '互动卡片回调签名已过期。');
}
$expected = base64_encode(hash_hmac(
'sha256',
$timestamp,
$this->callbackSecret(),
true,
));
if (! hash_equals($expected, $signature)) {
abort(403, '互动卡片回调签名无效。');
}
}
public function callbackSignature(string $timestamp): string
{
return base64_encode(hash_hmac(
'sha256',
$timestamp,
$this->callbackSecret(),
true,
));
}
public static function normalizeOpenConversationId(string $value): string
{
$value = trim($value);
if ($value === '') {
return '';
}
$value = urldecode($value);
if (preg_match('/cid[A-Za-z0-9+\/_=-]{8,}/', $value, $matches) === 1) {
return rtrim($matches[0], '.,;,。;');
}
if (preg_match('/im_group\.([^;&?\\s]+)/', $value, $matches) === 1) {
return urldecode(rtrim($matches[1], '.,;,。;'));
}
return preg_match('/^cid[A-Za-z0-9+\/_=-]{8,512}$/i', $value) === 1 ? $value : '';
}
private function registerCallback(string $token): void
{
$callbackUrl = trim((string) config('dingtalk.card.callback_url', ''));
if (preg_match('/^https:\/\/[^\\s]+$/i', $callbackUrl) !== 1) {
throw new RuntimeException('互动卡片回调地址必须配置为公网 HTTPS 地址。');
}
$this->post('/v1.0/card/callbacks/register', [
'apiSecret' => $this->callbackSecret(),
'callbackUrl' => $callbackUrl,
'callbackRouteKey' => (string) config('dingtalk.card.callback_route_key', 'caiwu-supplier-summary-v1'),
'forceUpdate' => true,
], $token);
}
private function resolveRobotCode(
string $token,
string $openConversationId,
string $configuredRobotCode,
string $configuredRobotName,
): string {
$configuredRobotCode = trim($configuredRobotCode);
if ($configuredRobotCode === '') {
$configuredRobotCode = trim((string) config('dingtalk.card.robot_code', ''));
}
if ($configuredRobotCode !== '') {
return $configuredRobotCode;
}
$data = $this->post('/v1.0/robot/groups/robots/query', [
'openConversationId' => $openConversationId,
], $token);
$robots = data_get($data, 'chatbotInstanceVOList')
?? data_get($data, 'result.chatbotInstanceVOList')
?? [];
$internalRobots = array_values(array_filter(
is_array($robots) ? $robots : [],
static fn (mixed $robot): bool => is_array($robot)
&& (int) ($robot['openRobotType'] ?? 0) === 2
&& trim((string) ($robot['robotCode'] ?? '')) !== '',
));
$configuredRobotName = trim($configuredRobotName);
if ($configuredRobotName === '') {
$configuredRobotName = trim((string) config('dingtalk.card.robot_name', ''));
}
if ($configuredRobotName !== '') {
$internalRobots = array_values(array_filter(
$internalRobots,
static fn (array $robot): bool =>
trim((string) ($robot['name'] ?? '')) === $configuredRobotName,
));
}
if (count($internalRobots) === 1) {
return trim((string) $internalRobots[0]['robotCode']);
}
if ($internalRobots === []) {
throw new RuntimeException('目标群内没有可用的财务系统企业内部应用机器人,请先将机器人加入该群。');
}
throw new RuntimeException('目标群内有多个企业内部应用机器人,请配置要使用的机器人编码或名称。');
}
private function createAndDeliver(
string $token,
string $outTrackId,
string $surfaceId,
string $openConversationId,
string $robotCode,
string $supplier,
string $period,
float $qty,
float $amount,
): void {
$summary = "### 货款对账确认\n\n"
. '- 厂家:**' . $this->markdown($supplier) . "**\n"
. '- 账期:**' . $period . "**\n"
. '- 件数:**' . $this->number($qty) . "** 件\n"
. '- 货款:**¥' . number_format($amount, 2) . "**\n\n"
. '核对无误后,请直接点击下方“厂家确认”。';
$messages = [
[
'version' => 'v1.0',
'createSurface' => [
'surfaceId' => $surfaceId,
'catalogId' => 'https://dingtalk.com/card/a2ui/catalogs/public/catalog.json',
],
],
[
'version' => 'v1.0',
'updateDataModel' => [
'surfaceId' => $surfaceId,
'path' => '/',
'value' => [
'confirmation' => [
'text' => '等待厂家确认',
],
],
],
],
[
'version' => 'v1.0',
'updateComponents' => [
'surfaceId' => $surfaceId,
'components' => [
[
'id' => 'root',
'component' => 'Column',
'children' => ['summary', 'status', 'actions', 'hint'],
'gap' => 10,
],
[
'id' => 'summary',
'component' => 'Markdown',
'content' => $summary,
],
[
'id' => 'status',
'component' => 'Text',
'variant' => 'caption',
'text' => ['path' => '/confirmation/text'],
],
[
'id' => 'actions',
'component' => 'Row',
'justify' => 'end',
'children' => ['confirm-button'],
],
[
'id' => 'confirm-button',
'component' => 'Button',
'variant' => 'primary',
'child' => 'confirm-label',
'action' => [
'event' => [
'name' => 'confirm_supplier_summary',
'context' => ['action' => 'confirm'],
],
],
],
[
'id' => 'confirm-label',
'component' => 'Text',
'text' => '厂家确认',
],
[
'id' => 'hint',
'component' => 'Text',
'variant' => 'caption',
'text' => '点击即确认,无需打开网页;确认结果会实时回传财务系统。',
],
],
],
],
];
$fallback = '账期:' . $period . ',件数' . $this->number($qty)
. '件,货款' . number_format($amount, 2, '.', '') . '元';
$data = $this->post('/v1.0/card/ai/instances/createAndDeliver', [
'outTrackId' => $outTrackId,
'openSpaceId' => 'dtv1.card//im_group.' . $openConversationId,
'imGroupOpenSpaceModel' => [
'supportForward' => false,
'lastMessageI18n' => [
'ZH_CN' => '[货款对账] ' . $supplier . ' ' . $period . ' 待确认',
'EN_US' => '[Payables] ' . $supplier . ' ' . $period . ' pending confirmation',
],
'notification' => [
'alertContent' => $supplier . ' ' . $period . ' 货款对账待确认',
'notificationOff' => false,
],
],
'imGroupOpenDeliverModel' => [
'robotCode' => $robotCode,
],
'protocolVersion' => '1.0',
'flowStatus' => 'CONFIRMING',
'a2uiMessages' => $this->wireMessages($messages),
'a2uiAnnotations' => [[
'surfaceId' => $surfaceId,
'componentId' => 'summary',
'type' => 'artifact',
]],
'summary' => $fallback,
'callbackType' => 'HTTP',
'callbackRouteKey' => (string) config('dingtalk.card.callback_route_key', 'caiwu-supplier-summary-v1'),
'bizContext' => [
'feature' => 'supplier-summary-confirmation',
],
], $token);
if (($data['success'] ?? true) !== true) {
throw new RuntimeException('钉钉互动卡片创建失败。');
}
$deliverResults = (array) data_get($data, 'result.deliverResults', []);
if ($deliverResults === []) {
throw new RuntimeException('钉钉互动卡片未返回实际投放结果。');
}
foreach ($deliverResults as $delivery) {
if (! is_array($delivery) || ($delivery['success'] ?? false) !== true) {
$error = is_array($delivery) ? trim((string) ($delivery['errorMsg'] ?? '')) : '';
throw new RuntimeException('钉钉互动卡片投放失败。' . ($error !== '' ? ' ' . $error : ''));
}
}
}
private function post(string $path, array $body, string $token): array
{
return $this->request('POST', $path, $body, $token);
}
private function put(string $path, array $body, string $token): array
{
return $this->request('PUT', $path, $body, $token);
}
private function request(string $method, string $path, array $body, string $token): array
{
try {
$response = Http::acceptJson()
->withHeaders(['x-acs-dingtalk-access-token' => $token])
->timeout(max(3, min(30, (int) config('dingtalk.timeout', 10))))
->send($method, 'https://api.dingtalk.com' . $path, ['json' => $body]);
} catch (\Throwable $exception) {
throw new RuntimeException('钉钉互动卡片接口连接失败。', 0, $exception);
}
$data = $this->responseData($response);
if (! $response->successful()) {
$message = trim((string) ($data['message'] ?? $data['errorMsg'] ?? $data['errmsg'] ?? ''));
throw new RuntimeException(
'钉钉互动卡片接口返回 HTTP ' . $response->status()
. ($message !== '' ? ':' . mb_strimwidth($message, 0, 180, '…', 'UTF-8') : '。')
);
}
if ((int) ($data['errcode'] ?? 0) !== 0) {
throw new RuntimeException(
'钉钉互动卡片接口返回错误:'
. trim((string) ($data['errmsg'] ?? $data['message'] ?? '未知错误'))
);
}
if (array_key_exists('success', $data) && $data['success'] !== true) {
throw new RuntimeException('钉钉互动卡片接口未返回成功结果。');
}
return $data;
}
/** @return array<string,mixed> */
private function responseData(Response $response): array
{
try {
$json = $response->json();
} catch (\Throwable) {
$json = null;
}
return is_array($json) ? $json : [];
}
/** @param list<array<string,mixed>> $messages */
private function wireMessages(array $messages): array
{
return array_map(
static fn (array $message): string => json_encode(
$message,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
),
$messages,
);
}
private function callbackSecret(): string
{
$configured = trim((string) config('dingtalk.card.callback_secret', ''));
if ($configured !== '') {
return $configured;
}
$appKey = trim((string) config('app.key', ''));
if ($appKey === '') {
throw new RuntimeException('互动卡片回调密钥不可用,请先配置 APP_KEY。');
}
return hash_hmac(
'sha256',
'caiwu-dingtalk-card-callback-v1',
$appKey,
);
}
private function displayMonth(string $month): string
{
[$year, $monthNumber] = explode('-', $month, 2);
return (int) $year . '年' . (int) $monthNumber . '月';
}
private function number(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
}
private function markdown(string $value): string
{
return preg_replace('/([\\\\`*_{}\[\]()#+.!|>-])/u', '\\\\$1', $value) ?? $value;
}
}