| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Service;
- use EasyWeChat\Factory;
- use EasyWeChat\Kernel\Messages\TextCard;
- use Exception;
- use Illuminate\Support\Facades\Log;
- class EnterpriseWechatService
- {
- private $app;
- private $agentId; // 提出来作为类属性,发消息时需要用到
- public function __construct()
- {
- $config = config('enterprise_wechat.work');
- if (empty($config['corp_id']) || empty($config['agent_id']) || empty($config['secret']) || empty($config['token']) || empty($config['aes_key'])) {
- throw new Exception("企业微信配置缺失,请检查 .env 文件");
- }
- // 构造 EasyWeChat 实例
- $this->app = Factory::work($config);
- }
- /**
- * 获取 EasyWeChat 应用实例
- */
- public function getApp()
- {
- return $this->app;
- }
- /**
- * 快捷获取 OA (审批) 实例
- */
- public function getOA()
- {
- return $this->app->oa;
- }
- /**
- * 发送文本卡片消息 (返回详细的错误提示)
- *
- * @param string $userId 接收人的企业微信userid(多个用竖线隔开)
- * @param string $title 标题
- * @param string $description 内容
- * @param string $url 跳转链接
- * @return array [bool, string]
- */
- public function sendTextCard($userId, $title, $description, $url)
- {
- try {
- // EasyWeChat 4.x 的 TextCard 构造函数只接收一个规范的数组
- $attributes = [
- 'title' => $title,
- 'description' => $description,
- 'url' => $url ?? '',
- ];
- // 如果 url 不为空,才加入 btntxt
- if (!empty($url)) {
- $attributes['btntxt'] = '点击查看详情';
- }
- // 实例化时,将整个数组作为第 1 个参数传入
- $cardElement = new TextCard($attributes);
- // 直接把对象传给 message() 方法发送
- $response = $this->app->messenger
- ->message($cardElement)
- ->toUser($userId)
- ->send();
- // 如果企业微信返回 errcode 且为 0,说明成功
- if (isset($response['errcode']) && $response['errcode'] === 0) return [true, ''];
- $errorCode = $response['errcode'] ?? '未知代码';
- $errorMsg = $response['errmsg'] ?? '未知错误';
- return [false, "企业微信返回错误 [Code: {$errorCode}]: {$errorMsg}"];
- } catch (Exception $e) {
- return [false, $e->getMessage() . '|' . $e->getLine() . '|' . $e->getFile()];
- }
- }
- }
|