CaiWuXiTong/modules/EcommerceFinance/Services/PlantingDingTalkClient.php

172 lines
8.5 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 Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* 种菜报销流程用到的钉钉开放接口:应用凭证、表单结构、发起人 unionId、审批钉盘空间、上传附件、发起审批。
* 发起审批的请求绝不自动重试(超时视为「可能已发起」,由调用方标记待核查)。
*/
class PlantingDingTalkClient
{
private const API = 'https://api.dingtalk.com/v1.0';
private const OAPI = 'https://oapi.dingtalk.com';
/** @return array<string,mixed> */
public function settings(): array
{
return (array) config('planting_reimbursement.dingtalk', []);
}
public function token(): string
{
$settings = $this->settings();
if (trim((string) ($settings['client_id'] ?? '')) === '' || trim((string) ($settings['client_secret'] ?? '')) === '') {
throw new RuntimeException('没有配置钉钉应用凭据(PLANTING_DINGTALK_CLIENT_ID / SECRET)。');
}
return Cache::remember('planting-dingtalk:token:' . md5((string) $settings['client_id']), 5400, function () use ($settings): string {
$response = $this->send(fn () => Http::acceptJson()->connectTimeout(3)->timeout(8)->post(self::API . '/oauth2/accessToken', [
'appKey' => $settings['client_id'], 'appSecret' => $settings['client_secret'],
]), '获取钉钉应用凭证');
$token = $response->json('accessToken');
if (! is_string($token) || $token === '') {
throw new RuntimeException('获取钉钉应用凭证失败,请检查应用凭据。');
}
return $token;
});
}
/** @return list<array<string,mixed>> 表单组件(schemaContent.items) */
public function formSchema(string $processCode): array
{
$response = $this->send(fn () => $this->api()->get(self::API . '/workflow/forms/schemas/processCodes', ['processCode' => $processCode]), '读取钉钉流程表单');
$items = $response->json('result.schemaContent.items');
if (! is_array($items) || $items === []) {
throw new RuntimeException('钉钉没有返回「种菜报销流程」的表单结构,请检查流程编码和应用的审批权限。');
}
return $items;
}
public function unionId(string $userId): string
{
$response = $this->send(fn () => Http::acceptJson()->connectTimeout(3)->timeout(8)
->post(self::OAPI . '/topapi/v2/user/get?access_token=' . urlencode($this->token()), ['userid' => $userId, 'language' => 'zh_CN']), '读取发起人信息');
$unionId = $response->json('result.unionid');
if ((int) $response->json('errcode', 0) !== 0 || ! is_string($unionId) || $unionId === '') {
throw new RuntimeException('读取发起人钉钉信息失败(' . $response->json('errmsg', '无 unionId') . '),请检查应用的通讯录权限。');
}
return $unionId;
}
/** @return list<int> 发起人所在部门 */
public function deptIds(string $userId): array
{
$response = $this->send(fn () => Http::acceptJson()->connectTimeout(3)->timeout(8)
->post(self::OAPI . '/topapi/v2/user/get?access_token=' . urlencode($this->token()), ['userid' => $userId, 'language' => 'zh_CN']), '读取发起人部门');
return array_values(array_map('intval', (array) $response->json('result.dept_id_list', [])));
}
/**
* 把文件上传到发起人的审批钉盘空间,返回审批附件组件要的值。
*
* @return array{spaceId:string,fileName:string,fileSize:string,fileType:string,fileId:string}
*/
public function uploadAttachment(string $userId, string $fileName, string $content): array
{
$agentId = trim((string) ($this->settings()['agent_id'] ?? ''));
if ($agentId === '') {
throw new RuntimeException('没有配置钉钉应用 AgentId(PLANTING_DINGTALK_AGENT_ID),无法上传打款明细附件。');
}
$space = $this->send(fn () => $this->api()->post(self::API . '/workflow/processInstances/spaces/infos/query', [
'userId' => $userId, 'agentId' => (int) $agentId,
]), '获取审批钉盘空间');
$spaceId = (string) $space->json('result.spaceId', '');
if ($spaceId === '') {
throw new RuntimeException('钉钉没有返回审批钉盘空间。');
}
$unionId = $this->unionId($userId);
$info = $this->send(fn () => $this->api()->post(self::API . '/storage/spaces/' . $spaceId . '/files/uploadInfos/query?unionId=' . urlencode($unionId), [
'protocol' => 'HEADER_SIGNATURE', 'multipart' => false,
]), '获取附件上传地址');
$uploadKey = (string) $info->json('uploadKey', '');
$url = (string) ($info->json('headerSignatureInfo.resourceUrls.0') ?? '');
$headers = (array) $info->json('headerSignatureInfo.headers', []);
if ($uploadKey === '' || $url === '') {
throw new RuntimeException('钉钉没有返回附件上传地址。');
}
$this->send(fn () => Http::withHeaders($headers)->connectTimeout(5)->timeout(30)->withBody($content, 'application/octet-stream')->put($url), '上传打款明细附件');
$commit = $this->send(fn () => $this->api()->post(self::API . '/storage/spaces/' . $spaceId . '/files/commit?unionId=' . urlencode($unionId), [
'uploadKey' => $uploadKey, 'name' => $fileName, 'parentId' => '0',
'option' => ['conflictStrategy' => 'AUTO_RENAME', 'size' => strlen($content)],
]), '提交打款明细附件');
$dentry = (array) $commit->json('dentry', []);
if (($dentry['id'] ?? '') === '') {
throw new RuntimeException('钉钉没有返回附件编号。');
}
return [
'spaceId' => (string) ($dentry['spaceId'] ?? $spaceId),
'fileName' => (string) ($dentry['name'] ?? $fileName),
'fileSize' => (string) ($dentry['size'] ?? strlen($content)),
'fileType' => (string) ($dentry['extension'] ?? pathinfo($fileName, PATHINFO_EXTENSION)),
'fileId' => (string) $dentry['id'],
];
}
/** 发起审批。失败抛异常;$uncertain=true 表示可能已经发起成功(超时 / 服务端错误)。 */
public function startInstance(array $payload): string
{
try {
$response = $this->api()->connectTimeout(3)->timeout(15)->post(self::API . '/workflow/processInstances', $payload);
} catch (ConnectionException) {
throw new PlantingDingTalkUncertainException('发起审批超时,可能已经发起成功,请先到钉钉核查,勿重复提交。');
}
if (! $response->successful()) {
$code = preg_replace('/[^a-zA-Z0-9_.-]/', '', (string) $response->json('code', ''));
$message = mb_substr((string) $response->json('message', ''), 0, 120);
if ($response->serverError() || $response->status() === 408) {
throw new PlantingDingTalkUncertainException('钉钉返回 HTTP ' . $response->status() . ',可能已经发起成功,请先到钉钉核查,勿重复提交。');
}
throw new RuntimeException('钉钉拒绝发起(HTTP ' . $response->status() . ($code !== '' ? ' ' . $code : '') . ($message !== '' ? ':' . $message : '') . '),请检查表单字段和发起权限。');
}
$id = $response->json('instanceId');
if (! is_string($id) || $id === '') {
throw new PlantingDingTalkUncertainException('钉钉响应缺少审批编号,可能已经发起成功,请先到钉钉核查。');
}
return $id;
}
private function api()
{
return Http::acceptJson()->connectTimeout(3)->timeout(10)->withHeaders(['x-acs-dingtalk-access-token' => $this->token()]);
}
private function send(callable $request, string $step)
{
try {
$response = $request();
} catch (ConnectionException) {
throw new RuntimeException($step . '超时,请稍后重试。');
}
if (! $response->successful()) {
$code = preg_replace('/[^a-zA-Z0-9_.-]/', '', (string) $response->json('code', ''));
throw new RuntimeException($step . '失败(HTTP ' . $response->status() . ($code !== '' ? ' ' . $code : '') . ')。');
}
return $response;
}
}