Files
x-server-mobile/backend/app/service/FeishuService.php
T
root 6899bad529 refactor: 重构飞书授权代码,提取公共工具类
1. 创建 app/util/HttpClient.php
   - 公共 HTTP 请求类
   - httpGet() 和 httpPost() 方法
   - 支持自定义 headers 和 timeout
   - 统一错误处理和日志

2. 创建 app/util/FeishuUtil.php
   - 飞书授权工具类,可被其他业务模块复用
   - getAppAccessToken() - 获取应用访问令牌(带缓存)
   - getUserAccessToken() - 获取用户访问令牌
   - getUserInfo() - 获取用户信息
   - getCompleteUserInfo() - 一步获取完整用户信息
   - clearTokenCache() - 清除 token 缓存

3. 重构 app/service/FeishuService.php
   - 使用新的工具类
   - 移除重复的 HTTP 请求方法
   - 保持向后兼容

飞书授权流程:
1. app_access_token (应用级令牌)
2. user_access_token (用户级令牌,需要 app_access_token)
3. 用户信息 (需要 user_access_token)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 10:43:29 +08:00

235 lines
6.4 KiB
PHP

<?php
namespace app\service;
use app\model\Company;
use app\model\CompanyFeishuApp;
use app\model\User;
use app\util\FeishuUtil;
use app\util\HttpClient;
use Exception;
class FeishuService
{
private ?int $companyId = null;
private ?int $appId = null;
/**
* 设置当前操作的公司
*/
public function setCompany(int $companyId): self
{
$this->companyId = $companyId;
return $this;
}
/**
* 设置飞书应用ID(支持多应用)
*/
public function setApp(int $appId): self
{
$this->appId = $appId;
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);
}
/**
* 获取当前应用ID
*/
private function getAppId(): int
{
$app = $this->getAppConfig();
return $app['id'];
}
/**
* 获取飞书 access_token(保留用于向后兼容)
* @deprecated 建议直接使用 FeishuUtil::getAppAccessToken()
*/
public function getAccessToken(): string
{
return FeishuUtil::getAppAccessToken($this->getAppId());
}
/**
* 根据 auth_code 获取用户信息(扫码登录)
*/
public function getUserInfo(string $authCode): array
{
$app = $this->getAppConfig();
$appId = $app['id'];
error_log("🔑 使用应用ID: {$appId}, app_id: {$app['app_id']}");
// 使用 FeishuUtil 获取完整用户信息
return FeishuUtil::getCompleteUserInfo($authCode, $appId);
}
/**
* 创建或更新用户
*/
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 = HttpClient::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;
}
}
}