WeChat.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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(lang('100113') . $this->accessTokenFile);
  102. }
  103. return $resp['access_token'];
  104. }
  105. throw new \Exception(lang('100114') . ($resp['errmsg'] ?? lang('100115')));
  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. * @param bool $isRenewalResult 是否续期结果,续期结果不用提醒调整推送频率
  127. *
  128. * @return string
  129. */
  130. public function getFooter(bool $isRenewalResult = false)
  131. {
  132. $footer = '';
  133. $footer .= lang('100116');
  134. $this->setCommonFooter($footer, "\n", !$isRenewalResult);
  135. return $footer;
  136. }
  137. /**
  138. * 生成域名状态文本
  139. *
  140. * @param array $domainStatus
  141. *
  142. * @return string
  143. */
  144. public function genDomainStatusText(array $domainStatus)
  145. {
  146. if (empty($domainStatus)) {
  147. return lang('100118');
  148. }
  149. $domainStatusText = '';
  150. foreach ($domainStatus as $domain => $daysLeft) {
  151. $domainStatusText .= sprintf(lang('100119'), $domain, $domain, $domain, $daysLeft);
  152. }
  153. $domainStatusText = rtrim(rtrim($domainStatusText, ' '), ',,') . lang('100120');
  154. return $domainStatusText;
  155. }
  156. /**
  157. * 生成域名续期结果文本
  158. *
  159. * @param string $username
  160. * @param array $renewalSuccessArr
  161. * @param array $renewalFailuresArr
  162. * @param array $domainStatus
  163. *
  164. * @return string
  165. */
  166. public function genDomainRenewalResultsText(string $username, array $renewalSuccessArr, array $renewalFailuresArr, array $domainStatus)
  167. {
  168. $text = sprintf(lang('100121'), $username);
  169. if ($renewalSuccessArr) {
  170. $text .= lang('100122');
  171. $text .= $this->genDomainsText($renewalSuccessArr);
  172. }
  173. if ($renewalFailuresArr) {
  174. $text .= lang('100123');
  175. $text .= $this->genDomainsText($renewalFailuresArr);
  176. }
  177. $text .= lang('100124');
  178. $text .= $this->genDomainStatusText($domainStatus);
  179. $text .= $this->getFooter(true);
  180. return $text;
  181. }
  182. /**
  183. * 生成域名状态完整文本
  184. *
  185. * @param string $username
  186. * @param array $domainStatus
  187. *
  188. * @return string
  189. */
  190. public function genDomainStatusFullText(string $username, array $domainStatus)
  191. {
  192. $markDownText = sprintf(lang('100125'), $username);
  193. $markDownText .= $this->genDomainStatusText($domainStatus);
  194. $markDownText .= $this->getFooter();
  195. return $markDownText;
  196. }
  197. /**
  198. * 送信
  199. *
  200. * 由于腾讯要求 markdown 语法消息必须使用 企业微信 APP 才能查看,然而我并不想单独安装 企业微信 APP,故本方法不使用 markdown 语法,
  201. * 而是直接使用纯文本 text 类型,纯文本类型里腾讯额外支持 a 标签,所以基本满足需求
  202. *
  203. * 参考:
  204. * https://work.weixin.qq.com/api/doc/90000/90135/91039
  205. * https://work.weixin.qq.com/api/doc/90000/90135/90236#%E6%96%87%E6%9C%AC%E6%B6%88%E6%81%AF
  206. *
  207. * @param string $content
  208. * @param string $subject
  209. * @param int $type
  210. * @param array $data
  211. * @param string|null $recipient
  212. * @param mixed ...$params
  213. *
  214. * @return bool
  215. * @throws \Exception
  216. */
  217. public function send(string $content, string $subject = '', int $type = 1, array $data = [], ?string $recipient = null, ...$params)
  218. {
  219. $this->check($content, $data);
  220. if ($type === 1 || $type === 4) {
  221. // Do nothing
  222. } else if ($type === 2) {
  223. $content = $this->genDomainRenewalResultsText($data['username'], $data['renewalSuccessArr'], $data['renewalFailuresArr'], $data['domainStatusArr']);
  224. } else if ($type === 3) {
  225. $content = $this->genDomainStatusFullText($data['username'], $data['domainStatusArr']);
  226. } else {
  227. throw new \Exception(lang('100003'));
  228. }
  229. if ($subject !== '') {
  230. $content = $subject . "\n\n" . $content;
  231. }
  232. try {
  233. $accessToken = $this->getAccessToken();
  234. $body = [
  235. 'touser' => '@all', // 可直接通过此地址获取 userId,指定接收用户,多个用户用“|”分割 https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&fetch_child=FETCH_CHILD&department_id=1
  236. 'msgtype' => 'text', // 消息类型,text 类型支持 a 标签以及 \n 换行,基本满足需求。由于腾讯要求 markdown 语法必须使用 企业微信APP 才能查看,不想安装,故弃之
  237. 'agentid' => $this->agentId, // 企业应用的 ID,整型,可在应用的设置页面查看
  238. 'text' => [
  239. 'content' => $content, // 消息内容,最长不超过 2048 个字节,超过将截断
  240. ],
  241. 'enable_duplicate_check' => 1,
  242. 'duplicate_check_interval' => 60,
  243. ];
  244. return $this->doSend($accessToken, $body);
  245. } catch (\Exception $e) {
  246. system_log(sprintf(lang('100126'), $e->getMessage()));
  247. return false;
  248. }
  249. }
  250. /**
  251. * 执行送信
  252. *
  253. * @param string $accessToken
  254. * @param array $body
  255. * @param int $numOfRetries
  256. *
  257. * @return bool
  258. * @throws \Exception
  259. */
  260. private function doSend(string $accessToken, array $body, int &$numOfRetries = 0)
  261. {
  262. $resp = $this->client->post('https://qyapi.weixin.qq.com/cgi-bin/message/send', [
  263. 'query' => [
  264. 'access_token' => $accessToken
  265. ],
  266. 'headers' => [
  267. 'Content-Type' => 'application/json',
  268. ],
  269. 'body' => json_encode($body),
  270. ]);
  271. $resp = (string)$resp->getBody();
  272. $resp = (array)json_decode($resp, true);
  273. if (!isset($resp['errcode']) || !isset($resp['errmsg'])) {
  274. throw new \Exception(lang('100127') . json_encode($resp, JSON_UNESCAPED_UNICODE));
  275. }
  276. if ($resp['errcode'] === 0) {
  277. return true;
  278. } else if ($resp['errcode'] === 40014) { // invalid access_token
  279. $accessToken = $this->getAccessToken(true);
  280. if ($numOfRetries > 2) {
  281. throw new \Exception(lang('100128') . $resp['errmsg']);
  282. }
  283. $numOfRetries++;
  284. return $this->doSend($accessToken, $body, $numOfRetries);
  285. }
  286. throw new \Exception($resp['errmsg']);
  287. }
  288. }