EnterpriseWechatService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Service;
  3. use EasyWeChat\Factory;
  4. use EasyWeChat\Kernel\Messages\TextCard;
  5. use Exception;
  6. use Illuminate\Support\Facades\Log;
  7. class EnterpriseWechatService
  8. {
  9. private $app;
  10. private $agentId; // 提出来作为类属性,发消息时需要用到
  11. public function __construct()
  12. {
  13. $config = config('enterprise_wechat.work');
  14. if (empty($config['corp_id']) || empty($config['agent_id']) || empty($config['secret']) || empty($config['token']) || empty($config['aes_key'])) {
  15. throw new Exception("企业微信配置缺失,请检查 .env 文件");
  16. }
  17. // 构造 EasyWeChat 实例
  18. $this->app = Factory::work($config);
  19. }
  20. /**
  21. * 获取 EasyWeChat 应用实例
  22. */
  23. public function getApp()
  24. {
  25. return $this->app;
  26. }
  27. /**
  28. * 快捷获取 OA (审批) 实例
  29. */
  30. public function getOA()
  31. {
  32. return $this->app->oa;
  33. }
  34. /**
  35. * 发送文本卡片消息 (返回详细的错误提示)
  36. *
  37. * @param string $userId 接收人的企业微信userid(多个用竖线隔开)
  38. * @param string $title 标题
  39. * @param string $description 内容
  40. * @param string $url 跳转链接
  41. * @return array [bool, string]
  42. */
  43. public function sendTextCard($userId, $title, $description, $url)
  44. {
  45. try {
  46. // EasyWeChat 4.x 的 TextCard 构造函数只接收一个规范的数组
  47. $attributes = [
  48. 'title' => $title,
  49. 'description' => $description,
  50. 'url' => $url ?? '',
  51. ];
  52. // 如果 url 不为空,才加入 btntxt
  53. if (!empty($url)) {
  54. $attributes['btntxt'] = '点击查看详情';
  55. }
  56. // 实例化时,将整个数组作为第 1 个参数传入
  57. $cardElement = new TextCard($attributes);
  58. // 直接把对象传给 message() 方法发送
  59. $response = $this->app->messenger
  60. ->message($cardElement)
  61. ->toUser($userId)
  62. ->send();
  63. // 如果企业微信返回 errcode 且为 0,说明成功
  64. if (isset($response['errcode']) && $response['errcode'] === 0) return [true, ''];
  65. $errorCode = $response['errcode'] ?? '未知代码';
  66. $errorMsg = $response['errmsg'] ?? '未知错误';
  67. return [false, "企业微信返回错误 [Code: {$errorCode}]: {$errorMsg}"];
  68. } catch (Exception $e) {
  69. return [false, $e->getMessage() . '|' . $e->getLine() . '|' . $e->getFile()];
  70. }
  71. }
  72. }