WeChatOaService.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. namespace app\common\service\wechat;
  15. use app\common\enum\notice\NoticeEnum;
  16. use app\common\logic\NoticeLogic;
  17. use app\common\model\notice\NoticeSetting;
  18. use EasyWeChat\Kernel\Exceptions\Exception;
  19. use EasyWeChat\OfficialAccount\Application;
  20. /**
  21. * 公众号相关
  22. * Class WeChatOaService
  23. * @package app\common\service\wechat
  24. */
  25. class WeChatOaService
  26. {
  27. protected $app;
  28. protected $config;
  29. public function __construct()
  30. {
  31. $this->config = $this->getConfig();
  32. $this->app = new Application($this->config);
  33. }
  34. /**
  35. * @notes easywechat服务端
  36. * @return \EasyWeChat\Kernel\Contracts\Server|\EasyWeChat\OfficialAccount\Server
  37. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  38. * @throws \ReflectionException
  39. * @throws \Throwable
  40. * @author 段誉
  41. * @date 2023/2/27 14:22
  42. */
  43. public function getServer()
  44. {
  45. return $this->app->getServer();
  46. }
  47. /**
  48. * @notes 配置
  49. * @return array
  50. * @throws Exception
  51. * @author 段誉
  52. * @date 2023/2/27 12:03
  53. */
  54. protected function getConfig()
  55. {
  56. $config = WeChatConfigService::getOaConfig();
  57. if (empty($config['app_id']) || empty($config['secret'])) {
  58. throw new Exception('请先设置公众号配置');
  59. }
  60. return $config;
  61. }
  62. /**
  63. * @notes 公众号-根据code获取微信信息
  64. * @param string $code
  65. * @return mixed
  66. * @throws Exception
  67. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  68. * @author 段誉
  69. * @date 2023/2/27 11:04
  70. */
  71. public function getOaResByCode(string $code)
  72. {
  73. $response = $this->app->getOAuth()
  74. ->scopes(['snsapi_userinfo'])
  75. ->userFromCode($code)
  76. ->getRaw();
  77. if (!isset($response['openid']) || empty($response['openid'])) {
  78. throw new Exception('获取openID失败');
  79. }
  80. return $response;
  81. }
  82. /**
  83. * @notes 公众号跳转url
  84. * @param string $url
  85. * @return mixed
  86. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  87. * @author 段誉
  88. * @date 2023/2/27 10:35
  89. */
  90. public function getCodeUrl(string $url)
  91. {
  92. return $this->app->getOAuth()
  93. ->scopes(['snsapi_userinfo'])
  94. ->redirect($url);
  95. }
  96. /**
  97. * @notes 创建公众号菜单
  98. * @param array $buttons
  99. * @param array $matchRule
  100. * @return \EasyWeChat\Kernel\HttpClient\Response|\Symfony\Contracts\HttpClient\ResponseInterface
  101. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  102. * @author 段誉
  103. * @date 2023/2/27 12:07
  104. */
  105. public function createMenu(array $buttons, array $matchRule = [])
  106. {
  107. if (!empty($matchRule)) {
  108. return $this->app->getClient()->postJson('cgi-bin/menu/addconditional', [
  109. 'button' => $buttons,
  110. 'matchrule' => $matchRule,
  111. ]);
  112. }
  113. return $this->app->getClient()->postJson('cgi-bin/menu/create', ['button' => $buttons]);
  114. }
  115. /**
  116. * @notes 获取jssdkConfig
  117. * @param $url
  118. * @param $jsApiList
  119. * @param array $openTagList
  120. * @param false $debug
  121. * @return mixed[]
  122. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  123. * @throws \Psr\SimpleCache\InvalidArgumentException
  124. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  125. * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
  126. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  127. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  128. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  129. * @author 段誉
  130. * @date 2023/3/1 11:46
  131. */
  132. public function getJsConfig($url, $jsApiList, $openTagList = [], $debug = false)
  133. {
  134. return $this->app->getUtils()->buildJsSdkConfig($url, $jsApiList, $openTagList, $debug);
  135. }
  136. public function contentFormat($noticeSetting, $params)
  137. {
  138. $content = $noticeSetting['oa_notice']['content'];
  139. foreach($params['params'] as $k => $v) {
  140. $search = '${' . $k . '}';
  141. $content = str_replace($search, $v, $content);
  142. }
  143. return $content;
  144. }
  145. public function getTemplateMessageParams($noticeSetting, $params)
  146. {
  147. $arr = [];
  148. $content = $noticeSetting['oa_notice']['content'];
  149. foreach ($params['params'] as $item => $val) {
  150. $search = '${' . $item . '}';
  151. if(strpos($content, $search) !== false && !in_array($item, $arr)) {
  152. //arr => 获的数组[nickname, order_sn] //顺序可能是乱的
  153. $arr[] = $item;
  154. }
  155. }
  156. //arr2 => 获得数组[nickname, order_sn] //调整好顺序的变量名数组
  157. $arr2 = [];
  158. if (!empty($arr)) {
  159. foreach ($arr as $v) {
  160. $key = strpos($content, $v);
  161. $arr2[$key] = $v;
  162. }
  163. }
  164. //格式化 arr2 => 以小到大的排序的数组
  165. ksort($arr2);
  166. $arr3 = array_values($arr2);
  167. //arr4 => 获取到变量数组的对应的值 [mofung, 123456789]
  168. $arr4 = [];
  169. foreach ($arr3 as $v2) {
  170. if(isset($params['params'][$v2])) {
  171. $arr4[] = $params['params'][$v2] . "";
  172. }
  173. }
  174. return $arr4;
  175. }
  176. public function sendTemplateMessage(array $params)
  177. {
  178. try {
  179. // 通知设置
  180. $noticeSetting = NoticeSetting::where('scene_id', $params['scene_id'])->findOrEmpty()->toArray();
  181. // 替换通知模板参数
  182. $content = $this->contentFormat($noticeSetting, $params);
  183. // 添加通知记录
  184. $this->notice = NoticeLogic::addNotice($params, $noticeSetting, NoticeEnum::OA, $content);
  185. // 发送
  186. $result = $this->app->getClient()->postJson('cgi-bin/message/template/send', [
  187. 'touser' => $params['params']['openid'],
  188. 'template_id' => $noticeSetting['oa_notice']['template_id'],
  189. 'url' => '',
  190. 'data' => $this->getTemplateMessageParams($noticeSetting, $params)
  191. ]);
  192. if (intval($result["errcode"]) > 0) {
  193. throw new \Exception('微信通知发送失败:'.$result["errmsg"]);
  194. }
  195. return true;
  196. } catch (\Exception $e) {
  197. throw new \Exception($e->getMessage());
  198. }
  199. }
  200. }