WeChat.php 10 KB

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