|
|
@@ -3,11 +3,14 @@
|
|
|
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()
|
|
|
{
|
|
|
@@ -36,4 +39,49 @@ class EnterpriseWechatService
|
|
|
{
|
|
|
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()];
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|