WeChat.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. /**
  3. * 企业微信
  4. *
  5. * @author mybsdc <[email protected]>
  6. * @date 2021/11/1
  7. * @time 17:38
  8. */
  9. namespace Luolongfei\Libs\MessageServices;
  10. use GuzzleHttp\Client;
  11. use Luolongfei\Libs\Connector\MessageGateway;
  12. class WeChat extends MessageGateway
  13. {
  14. const TIMEOUT = 33;
  15. /**
  16. * @var string 企业 ID
  17. */
  18. protected $corpId;
  19. /**
  20. * @var string 企业微信应用的凭证密钥
  21. */
  22. protected $corpSecret;
  23. /**
  24. * @var integer 企业微信应用 ID
  25. */
  26. protected $agentId;
  27. /**
  28. * @var Client
  29. */
  30. protected $client;
  31. /**
  32. * @var string 缓存 access_token 的文件
  33. */
  34. protected $accessTokenFile;
  35. public function __construct()
  36. {
  37. $this->corpId = config('message.wechat.corp_id');
  38. $this->corpSecret = config('message.wechat.corp_secret');
  39. $this->agentId = config('message.wechat.agent_id');
  40. $this->accessTokenFile = DATA_PATH . DS . 'wechat_access_token.txt';
  41. $this->client = new Client([
  42. 'cookies' => false,
  43. 'timeout' => self::TIMEOUT,
  44. 'verify' => config('verify_ssl'),
  45. 'debug' => config('debug'),
  46. ]);
  47. }
  48. /**
  49. * 获取 access_token 缓存
  50. *
  51. * 由于云函数环境中只有 /tmp 目录的读写权限,且每次运行结束后写入的内容不会被保留,故云函数无法真正做到通过文件缓存 access_token
  52. * 参考:https://cloud.tencent.com/document/product/583/9180
  53. *
  54. * @return string|null
  55. */
  56. protected function getAccessTokenCache()
  57. {
  58. if (!file_exists($this->accessTokenFile)) {
  59. return null;
  60. }
  61. $accessTokenFile = file_get_contents($this->accessTokenFile);
  62. if (!preg_match('/^WECHAT_ACCESS_TOKEN_EXPIRES_AT=(?P<expires_at>.*?)$/im', $accessTokenFile, $m)) {
  63. return null;
  64. }
  65. $expiresAt = (int)$m['expires_at'];
  66. if (!preg_match('/^WECHAT_ACCESS_TOKEN=(?P<access_token>.*?)$/im', $accessTokenFile, $m)) {
  67. return null;
  68. }
  69. if (time() + 5 > $expiresAt) {
  70. return null;
  71. }
  72. return $m['access_token'];
  73. }
  74. /**
  75. * 获取 access_token
  76. *
  77. * @param bool $force
  78. *
  79. * @return mixed|string
  80. * @throws \Exception
  81. */
  82. protected function getAccessToken($force = false)
  83. {
  84. if (!$force) {
  85. $accessToken = $this->getAccessTokenCache();
  86. if (!is_null($accessToken)) {
  87. return $accessToken;
  88. }
  89. }
  90. $resp = $this->client->get('https://qyapi.weixin.qq.com/cgi-bin/gettoken', [
  91. 'query' => [
  92. 'corpid' => $this->corpId,
  93. 'corpsecret' => $this->corpSecret
  94. ],
  95. ]);
  96. $resp = $resp->getBody()->getContents();
  97. $resp = (array)json_decode($resp, true);
  98. if (isset($resp['errcode']) && $resp['errcode'] === 0 && isset($resp['access_token']) && isset($resp['expires_in'])) {
  99. $accessTokenFileText = sprintf("WECHAT_ACCESS_TOKEN=%s\nWECHAT_ACCESS_TOKEN_EXPIRES_AT=%s\n", $resp['access_token'], time() + $resp['expires_in']);
  100. if (file_put_contents($this->accessTokenFile, $accessTokenFileText) === false) {
  101. throw new \Exception('企业微信 access_token 写入失败:' . $this->accessTokenFile);
  102. }
  103. return $resp['access_token'];
  104. }
  105. throw new \Exception('获取企业微信 access_token 失败:' . ($resp['errmsg'] ?? '未知原因'));
  106. }
  107. /**
  108. * 生成域名文本
  109. *
  110. * @param array $domains
  111. *
  112. * @return string
  113. */
  114. public function genDomainsText(array $domains)
  115. {
  116. $domainsText = '';
  117. foreach ($domains as $domain) {
  118. $domainsText .= sprintf('<a href="http://%s">%s</a> ', $domain, $domain);
  119. }
  120. $domainsText = trim($domainsText, ' ') . "\n";
  121. return $domainsText;
  122. }
  123. /**
  124. * 获取页脚
  125. *
  126. * @return string
  127. */
  128. public function getFooter()
  129. {
  130. $footer = '';
  131. $footer .= "\n更多信息可以参考 <a href=\"https://my.freenom.com/domains.php?a=renewals\">Freenom官网</a> 哦~";
  132. $footer .= "\n\n(如果你不想每次执行都收到推送,请将 .env 中 NOTICE_FREQ 的值设为 0,使程序只在有续期操作时才推送)";
  133. return $footer;
  134. }
  135. /**
  136. * 生成域名状态文本
  137. *
  138. * @param array $domainStatus
  139. *
  140. * @return string
  141. */
  142. public function genDomainStatusText(array $domainStatus)
  143. {
  144. if (empty($domainStatus)) {
  145. return "无数据。\n";
  146. }
  147. $domainStatusText = '';
  148. foreach ($domainStatus as $domain => $daysLeft) {
  149. $domainStatusText .= sprintf('<a href="http://%s">%s</a> 还有 <a href="http://%s">%d</a> 天到期,', $domain, $domain, $domain, $daysLeft);
  150. }
  151. $domainStatusText = rtrim($domainStatusText, ',') . "。\n";
  152. return $domainStatusText;
  153. }
  154. /**
  155. * 生成域名续期结果文本
  156. *
  157. * @param string $username
  158. * @param array $renewalSuccessArr
  159. * @param array $renewalFailuresArr
  160. * @param array $domainStatus
  161. *
  162. * @return string
  163. */
  164. public function genDomainRenewalResultsText(string $username, array $renewalSuccessArr, array $renewalFailuresArr, array $domainStatus)
  165. {
  166. $text = sprintf("账户 <a href=\"https://www.google.com\">%s</a> 这次续期的结果如下\n\n", $username);
  167. if ($renewalSuccessArr) {
  168. $text .= '续期成功:';
  169. $text .= $this->genDomainsText($renewalSuccessArr);
  170. }
  171. if ($renewalFailuresArr) {
  172. $text .= '续期出错:';
  173. $text .= $this->genDomainsText($renewalFailuresArr);
  174. }
  175. $text .= "\n今次无需续期的域名及其剩余天数如下所示:\n\n";
  176. $text .= $this->genDomainStatusText($domainStatus);
  177. $text .= $this->getFooter();
  178. return $text;
  179. }
  180. /**
  181. * 生成域名状态完整文本
  182. *
  183. * @param string $username
  184. * @param array $domainStatus
  185. *
  186. * @return string
  187. */
  188. public function genDomainStatusFullText(string $username, array $domainStatus)
  189. {
  190. $markDownText = sprintf("我刚刚帮小主看了一下,账户 <a href=\"https://www.google.com\">%s</a> 今天并没有需要续期的域名。所有域名情况如下:\n\n", $username);
  191. $markDownText .= $this->genDomainStatusText($domainStatus);
  192. $markDownText .= $this->getFooter();
  193. return $markDownText;
  194. }
  195. /**
  196. * 送信
  197. *
  198. * 由于腾讯要求 markdown 语法消息必须使用 企业微信 APP 才能查看,然而我并不想单独安装 企业微信 APP,故本方法不使用 markdown 语法,
  199. * 而是直接使用纯文本 text 类型,纯文本类型里腾讯额外支持 a 标签,所以基本满足需求
  200. *
  201. * 参考:
  202. * https://work.weixin.qq.com/api/doc/90000/90135/91039
  203. * https://work.weixin.qq.com/api/doc/90000/90135/90236#%E6%96%87%E6%9C%AC%E6%B6%88%E6%81%AF
  204. *
  205. * @param string $content
  206. * @param string $subject
  207. * @param int $type
  208. * @param array $data
  209. * @param string|null $recipient
  210. * @param mixed ...$params
  211. *
  212. * @return bool
  213. * @throws \Exception
  214. */
  215. public function send(string $content, string $subject = '', int $type = 1, array $data = [], ?string $recipient = null, ...$params)
  216. {
  217. $this->check($content, $data);
  218. if ($type === 1 || $type === 4) {
  219. // Do nothing
  220. } else if ($type === 2) {
  221. $content = $this->genDomainRenewalResultsText($data['username'], $data['renewalSuccessArr'], $data['renewalFailuresArr'], $data['domainStatusArr']);
  222. } else if ($type === 3) {
  223. $content = $this->genDomainStatusFullText($data['username'], $data['domainStatusArr']);
  224. } else {
  225. throw new \Exception(lang('error_msg.100003'));
  226. }
  227. if ($subject !== '') {
  228. $content = $subject . "\n\n" . $content;
  229. }
  230. try {
  231. $accessToken = $this->getAccessToken();
  232. $body = [
  233. 'touser' => '@all', // 可直接通过此地址获取 userId,指定接收用户,多个用户用“|”分割 https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&fetch_child=FETCH_CHILD&department_id=1
  234. 'msgtype' => 'text', // 消息类型,text 类型支持 a 标签以及 \n 换行,基本满足需求。由于腾讯要求 markdown 语法必须使用 企业微信APP 才能查看,不想安装,故弃之
  235. 'agentid' => $this->agentId, // 企业应用的 ID,整型,可在应用的设置页面查看
  236. 'text' => [
  237. 'content' => $content, // 消息内容,最长不超过 2048 个字节,超过将截断
  238. ],
  239. 'enable_duplicate_check' => 1,
  240. 'duplicate_check_interval' => 60,
  241. ];
  242. return $this->doSend($accessToken, $body);
  243. } catch (\Exception $e) {
  244. system_log('企业微信送信失败:<red>' . $e->getMessage() . '</red>');
  245. return false;
  246. }
  247. }
  248. /**
  249. * 执行送信
  250. *
  251. * @param string $accessToken
  252. * @param array $body
  253. * @param int $numOfRetries
  254. *
  255. * @return bool
  256. * @throws \Exception
  257. */
  258. private function doSend(string $accessToken, array $body, int &$numOfRetries = 0)
  259. {
  260. $resp = $this->client->post('https://qyapi.weixin.qq.com/cgi-bin/message/send', [
  261. 'query' => [
  262. 'access_token' => $accessToken
  263. ],
  264. 'headers' => [
  265. 'Content-Type' => 'application/json',
  266. ],
  267. 'body' => json_encode($body),
  268. ]);
  269. $resp = (string)$resp->getBody();
  270. $resp = (array)json_decode($resp, true);
  271. if (!isset($resp['errcode']) || !isset($resp['errmsg'])) {
  272. throw new \Exception('企业微信接口未返回预期的数据响应,本次响应数据为:' . json_encode($resp, JSON_UNESCAPED_UNICODE));
  273. }
  274. if ($resp['errcode'] === 0) {
  275. return true;
  276. } else if ($resp['errcode'] === 40014) { // invalid access_token
  277. $accessToken = $this->getAccessToken(true);
  278. if ($numOfRetries > 2) {
  279. throw new \Exception('检测到多次提示 access_token 失效,可能是未能正确获取 access_token,请介入调查:' . $resp['errmsg']);
  280. }
  281. $numOfRetries++;
  282. return $this->doSend($accessToken, $body, $numOfRetries);
  283. }
  284. throw new \Exception($resp['errmsg']);
  285. }
  286. }