66b61eada4
- 创建 support/Db.php 和 support/Model.php - 在 bootstrap.php 中自动初始化数据库 - 移除 app/util/Db.php - 更新所有模型和控制器使用官方类 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
310 lines
8.9 KiB
PHP
310 lines
8.9 KiB
PHP
<?php
|
|
|
|
namespace app\service;
|
|
|
|
use app\model\Company;
|
|
use app\model\CompanyFeishuApp;
|
|
use app\model\User;
|
|
use support\Db;
|
|
|
|
class FeishuService
|
|
{
|
|
private ?string $accessToken = null;
|
|
private ?int $companyId = null;
|
|
private ?int $appId = null;
|
|
|
|
// 简单的内存缓存(生产环境应使用 Redis)
|
|
private static array $tokenCache = [];
|
|
|
|
/**
|
|
* 设置当前操作的公司
|
|
*/
|
|
public function setCompany(int $companyId): self
|
|
{
|
|
$this->companyId = $companyId;
|
|
$this->accessToken = null;
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* 设置飞书应用ID(支持多应用)
|
|
*/
|
|
public function setApp(int $appId): self
|
|
{
|
|
$this->appId = $appId;
|
|
$this->accessToken = null;
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* 根据 tenant_key 获取公司配置
|
|
*/
|
|
public function getCompanyByTenantKey(string $tenantKey): ?Company
|
|
{
|
|
return Company::active()->byTenantKey($tenantKey)->first();
|
|
}
|
|
|
|
/**
|
|
* 获取公司的飞书应用配置
|
|
*/
|
|
private function getFeishuApp(int $appId): array
|
|
{
|
|
$app = CompanyFeishuApp::find($appId);
|
|
|
|
if (!$app || $app->status !== 1) {
|
|
throw new \Exception('飞书应用配置不存在');
|
|
}
|
|
|
|
return $app->toArray();
|
|
}
|
|
|
|
/**
|
|
* 获取公司的默认飞书应用
|
|
*/
|
|
private function getDefaultFeishuApp(int $companyId): array
|
|
{
|
|
$app = CompanyFeishuApp::where('company_id', $companyId)
|
|
->where('system_id', 1)
|
|
->where('status', 1)
|
|
->orderBy('sort')
|
|
->first();
|
|
|
|
if (!$app) {
|
|
throw new \Exception('未配置飞书应用');
|
|
}
|
|
|
|
return $app->toArray();
|
|
}
|
|
|
|
/**
|
|
* 获取飞书应用配置(优先使用指定应用,否则使用默认应用)
|
|
*/
|
|
private function getAppConfig(): array
|
|
{
|
|
if (!$this->companyId) {
|
|
throw new \Exception('未设置公司ID');
|
|
}
|
|
|
|
if ($this->appId) {
|
|
return $this->getFeishuApp($this->appId);
|
|
}
|
|
|
|
return $this->getDefaultFeishuApp($this->companyId);
|
|
}
|
|
|
|
/**
|
|
* 获取飞书 access_token
|
|
*/
|
|
public function getAccessToken(): string
|
|
{
|
|
if ($this->accessToken) {
|
|
return $this->accessToken;
|
|
}
|
|
|
|
$app = $this->getAppConfig();
|
|
$cacheKey = "feishu:access_token:{$app['id']}";
|
|
|
|
// 从内存缓存获取
|
|
if (isset(self::$tokenCache[$cacheKey]) && self::$tokenCache[$cacheKey]['expire'] > time()) {
|
|
$this->accessToken = self::$tokenCache[$cacheKey]['token'];
|
|
return $this->accessToken;
|
|
}
|
|
|
|
// 请求新的 token
|
|
$response = $this->httpPost('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', [
|
|
'app_id' => $app['app_id'],
|
|
'app_secret' => $app['app_secret'],
|
|
]);
|
|
|
|
if ($response['code'] !== 0) {
|
|
throw new \Exception('获取飞书 token 失败: ' . ($response['msg'] ?? '未知错误'));
|
|
}
|
|
|
|
$token = $response['tenant_access_token'];
|
|
$expire = $response['expire'] ?? 7200;
|
|
|
|
// 缓存 token(提前5分钟过期)
|
|
self::$tokenCache[$cacheKey] = [
|
|
'token' => $token,
|
|
'expire' => time() + $expire - 300,
|
|
];
|
|
|
|
$this->accessToken = $token;
|
|
return $token;
|
|
}
|
|
|
|
/**
|
|
* 根据 auth_code 获取用户信息
|
|
*/
|
|
public function getUserInfo(string $authCode): array
|
|
{
|
|
$app = $this->getAppConfig();
|
|
$token = $this->getAccessToken();
|
|
|
|
// 获取用户 access_token
|
|
$response = $this->httpPost('https://open.feishu.cn/open-apis/authen/v1/oidc/access_token', [
|
|
'grant_type' => 'authorization_code',
|
|
'client_id' => $app['app_id'],
|
|
'client_secret' => $app['app_secret'],
|
|
'code' => $authCode,
|
|
], [
|
|
'Authorization: Bearer ' . $token,
|
|
]);
|
|
|
|
if ($response['code'] !== 0) {
|
|
throw new \Exception('获取用户信息失败: ' . ($response['msg'] ?? '未知错误'));
|
|
}
|
|
|
|
return $response['data'] ?? [];
|
|
}
|
|
|
|
/**
|
|
* 创建或更新用户
|
|
*/
|
|
public function createOrUpdateUser(array $feishuData, int $companyId): User
|
|
{
|
|
$unionId = $feishuData['union_id'] ?? null;
|
|
$userId = $feishuData['user_id'] ?? null;
|
|
$name = $feishuData['name'] ?? '未知';
|
|
$avatar = $feishuData['avatar_url'] ?? null;
|
|
$email = $feishuData['email'] ?? null;
|
|
|
|
if (!$unionId) {
|
|
throw new \Exception('缺少 union_id');
|
|
}
|
|
|
|
// 查找或创建用户
|
|
$user = User::byFeishuUnionId($unionId)->first();
|
|
|
|
if (!$user) {
|
|
$user = User::create([
|
|
'company_id' => $companyId,
|
|
'feishu_user_id' => $userId,
|
|
'feishu_union_id' => $unionId,
|
|
'name' => $name,
|
|
'email' => $email,
|
|
'avatar' => $avatar,
|
|
'status' => 1,
|
|
]);
|
|
} else {
|
|
// 更新用户信息
|
|
$user->update([
|
|
'feishu_user_id' => $userId,
|
|
'name' => $name,
|
|
'avatar' => $avatar,
|
|
'email' => $email,
|
|
]);
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
|
|
/**
|
|
* 发送审批消息通知
|
|
*/
|
|
public function sendApprovalMessage(int $userId, string $title, string $url): bool
|
|
{
|
|
try {
|
|
$user = User::findOrFail($userId);
|
|
$company = Company::findOrFail($user->company_id);
|
|
|
|
$this->setCompany($company->id);
|
|
$token = $this->getAccessToken();
|
|
|
|
// 构建消息内容
|
|
$message = [
|
|
'msg_type' => 'interactive',
|
|
'card' => [
|
|
'header' => [
|
|
'title' => [
|
|
'content' => '审批通知',
|
|
'tag' => 'plain_text',
|
|
],
|
|
'template' => 'blue',
|
|
],
|
|
'elements' => [
|
|
[
|
|
'tag' => 'div',
|
|
'text' => [
|
|
'content' => $title,
|
|
'tag' => 'plain_text',
|
|
],
|
|
],
|
|
[
|
|
'tag' => 'action',
|
|
'actions' => [
|
|
[
|
|
'tag' => 'button',
|
|
'text' => [
|
|
'content' => '查看详情',
|
|
'tag' => 'plain_text',
|
|
],
|
|
'type' => 'default',
|
|
'url' => $url,
|
|
],
|
|
],
|
|
],
|
|
],
|
|
],
|
|
];
|
|
|
|
// 发送消息
|
|
$response = $this->httpPost(
|
|
"https://open.feishu.cn/open-apis/message/v4/send_messages",
|
|
[
|
|
'receive_id_type' => 'user_id',
|
|
'receive_id' => $user->feishu_user_id,
|
|
'msg_type' => 'interactive',
|
|
'content' => json_encode(['card' => $message['card']]),
|
|
],
|
|
[
|
|
'Authorization: Bearer ' . $token,
|
|
]
|
|
);
|
|
|
|
return ($response['code'] ?? -1) === 0;
|
|
} catch (\Exception $e) {
|
|
// 记录错误但不中断流程
|
|
error_log('发送飞书消息失败: ' . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* HTTP POST 请求
|
|
*/
|
|
private function httpPost(string $url, array $data, array $headers = []): array
|
|
{
|
|
$ch = curl_init();
|
|
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
|
|
|
$defaultHeaders = [
|
|
'Content-Type: application/json',
|
|
];
|
|
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($defaultHeaders, $headers));
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
// curl_close($ch); // 不再需要,PHP 8.5+ 自动关闭
|
|
|
|
if ($httpCode !== 200) {
|
|
throw new \Exception("HTTP 请求失败: {$httpCode}");
|
|
}
|
|
|
|
$result = json_decode($response, true);
|
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
throw new \Exception('JSON 解析失败');
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
}
|