WeChat.php 10 KB

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