WeChatOaService.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. use think\facade\Log;
  21. use WpOrg\Requests\Requests;
  22. /**
  23. * 公众号相关
  24. * Class WeChatOaService
  25. * @package app\common\service\wechat
  26. */
  27. class WeChatOaService
  28. {
  29. protected $app;
  30. protected $config;
  31. public function __construct()
  32. {
  33. $this->config = $this->getConfig();
  34. $this->app = new Application($this->config);
  35. }
  36. /**
  37. * @notes easywechat服务端
  38. * @return \EasyWeChat\Kernel\Contracts\Server|\EasyWeChat\OfficialAccount\Server
  39. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  40. * @throws \ReflectionException
  41. * @throws \Throwable
  42. * @author 段誉
  43. * @date 2023/2/27 14:22
  44. */
  45. public function getServer()
  46. {
  47. return $this->app->getServer();
  48. }
  49. /**
  50. * @notes 配置
  51. * @return array
  52. * @throws Exception
  53. * @author 段誉
  54. * @date 2023/2/27 12:03
  55. */
  56. protected function getConfig()
  57. {
  58. $config = WeChatConfigService::getOaConfig();
  59. if (empty($config['app_id']) || empty($config['secret'])) {
  60. throw new Exception('请先设置公众号配置');
  61. }
  62. return $config;
  63. }
  64. /**
  65. * @notes 只获取微信用户openid信息
  66. * @return array
  67. * @throws Exception
  68. * @author 段誉
  69. * @date 2023/2/27 12:03
  70. */
  71. public function getOpenIdByCode(string $code)
  72. {
  73. $config = WeChatConfigService::getOaConfig();
  74. $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
  75. $url .= '?appid=' . $config['app_id'] . '&secret=' . $config['secret'] . '&code=' . $code;
  76. $url .= '&grant_type=authorization_code';
  77. $requests = Requests::get($url);
  78. return json_decode($requests->body, true);
  79. }
  80. /**
  81. * @notes 公众号-根据code获取微信信息
  82. * @param string $code
  83. * @return mixed
  84. * @throws Exception
  85. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  86. * @author 段誉
  87. * @date 2023/2/27 11:04
  88. */
  89. public function getOaResByCode(string $code)
  90. {
  91. $response = $this->app->getOAuth()
  92. ->scopes(['snsapi_userinfo'])
  93. ->userFromCode($code)
  94. ->getRaw();
  95. if (!isset($response['openid']) || empty($response['openid'])) {
  96. throw new Exception('获取openID失败');
  97. }
  98. return $response;
  99. }
  100. /**
  101. * @notes 公众号跳转url
  102. * @param string $url
  103. * @return mixed
  104. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  105. * @author 段誉
  106. * @date 2023/2/27 10:35
  107. */
  108. public function getCodeUrl(string $url)
  109. {
  110. return $this->app->getOAuth()
  111. ->scopes(['snsapi_userinfo'])
  112. ->redirect($url);
  113. }
  114. /**
  115. * @notes 创建公众号菜单
  116. * @param array $buttons
  117. * @param array $matchRule
  118. * @return \EasyWeChat\Kernel\HttpClient\Response|\Symfony\Contracts\HttpClient\ResponseInterface
  119. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  120. * @author 段誉
  121. * @date 2023/2/27 12:07
  122. */
  123. public function createMenu(array $buttons, array $matchRule = [])
  124. {
  125. if (!empty($matchRule)) {
  126. return $this->app->getClient()->postJson('cgi-bin/menu/addconditional', [
  127. 'button' => $buttons,
  128. 'matchrule' => $matchRule,
  129. ]);
  130. }
  131. return $this->app->getClient()->postJson('cgi-bin/menu/create', ['button' => $buttons]);
  132. }
  133. /**
  134. * @notes 获取jssdkConfig
  135. * @param $url
  136. * @param $jsApiList
  137. * @param array $openTagList
  138. * @param false $debug
  139. * @return mixed[]
  140. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  141. * @throws \Psr\SimpleCache\InvalidArgumentException
  142. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  143. * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
  144. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  145. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  146. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  147. * @author 段誉
  148. * @date 2023/3/1 11:46
  149. */
  150. public function getJsConfig($url, $jsApiList, $openTagList = [], $debug = false)
  151. {
  152. return $this->app->getUtils()->buildJsSdkConfig($url, $jsApiList, $openTagList, $debug);
  153. }
  154. public function contentFormat($noticeSetting, $params)
  155. {
  156. $content = $noticeSetting['oa_notice']['content'];
  157. foreach($params['params'] as $k => $v) {
  158. $search = '${' . $k . '}';
  159. $content = str_replace($search, $v, $content);
  160. }
  161. return $content;
  162. }
  163. public function getTemplateMessageParams($noticeSetting, $params)
  164. {
  165. $arr = [];
  166. $content = $noticeSetting['oa_notice']['content'];
  167. foreach ($params['params'] as $item => $val) {
  168. $search = '${' . $item . '}';
  169. if(strpos($content, $search) !== false && !in_array($item, $arr)) {
  170. $arr[] = $item;
  171. }
  172. }
  173. $arr2 = [];
  174. if (!empty($arr)) {
  175. foreach ($arr as $v) {
  176. $key = strpos($content, $v);
  177. $arr2[$key] = $v;
  178. }
  179. }
  180. ksort($arr2);
  181. $arr3 = array_values($arr2);
  182. $arr4 = [];
  183. foreach ($arr3 as $v2) {
  184. if(isset($params['params'][$v2])) {
  185. $arr4[$v2]['value'] = $params['params'][$v2] . "";
  186. }
  187. }
  188. return $arr4;
  189. }
  190. public function sendTemplateMessage(array $params)
  191. {
  192. try {
  193. // 通知设置
  194. $noticeSetting = NoticeSetting::where('scene_id', $params['scene_id'])->findOrEmpty()->toArray();
  195. Log::info('WeChatOa-sendTemplateMessage:'.json_encode([$noticeSetting,$params,$this->getTemplateMessageParams($noticeSetting, $params)]));
  196. // 发送
  197. $wx_data = [
  198. 'touser' => $params['params']['openid'],
  199. 'template_id' => $noticeSetting['oa_notice']['template_id'],
  200. 'url' => (isset($params['url']) && !empty($params['url']))?$params['url']:'',
  201. 'data' => $this->getTemplateMessageParams($noticeSetting, $params)
  202. ];
  203. // 可跳小程序
  204. if(isset($params['page']) && !empty($params['page'])) {
  205. $wx_data["miniprogram"]=[
  206. "appid" => 'wx8e44db3741ea212c',
  207. "pagepath" => $params['page']
  208. ];
  209. }
  210. $result = $this->app->getClient()->postJson('cgi-bin/message/template/send', $wx_data);
  211. if (intval($result["errcode"]) > 0) {
  212. throw new \Exception('微信通知发送失败:'.$result["errmsg"]);
  213. }
  214. // 替换通知模板参数
  215. $content = $this->contentFormat($noticeSetting, $params);
  216. // 添加通知记录
  217. NoticeLogic::addNotice($params, $noticeSetting, NoticeEnum::OA, $content);
  218. return true;
  219. } catch (\Exception $e) {
  220. Log::info('WeChatOa-sendTemplateMessage:'.$e->getMessage());
  221. throw new \Exception($e->getMessage());
  222. }
  223. }
  224. public function getUserInfo($openid)
  225. {
  226. $response =$this->app->getClient()->get("/cgi-bin/user/info?openid={$openid}&lang=zh_CN");
  227. return $response->toArray();
  228. }
  229. }