WechatService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. <?php
  2. namespace addons\weixin\library;
  3. use addons\weixin\library\MessageRepositories;
  4. use EasyWeChat\Factory;
  5. use EasyWeChat\Kernel\Messages\Article;
  6. use EasyWeChat\Kernel\Messages\Image;
  7. use EasyWeChat\Kernel\Messages\Material;
  8. use EasyWeChat\Kernel\Messages\News;
  9. use EasyWeChat\Kernel\Messages\NewsItem;
  10. use EasyWeChat\Kernel\Messages\Text;
  11. use EasyWeChat\Kernel\Messages\Video;
  12. use EasyWeChat\Kernel\Messages\Voice;
  13. use EasyWeChat\Kernel\Messages\Media;
  14. use app\admin\model\weixin\Reply as WechatReply;
  15. use think\Response;
  16. class WechatService
  17. {
  18. private static $instance = null;
  19. public static function options()
  20. {
  21. $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
  22. foreach ($wechat_data as $k => $v) {
  23. $value = $v->toArray();
  24. if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
  25. $value['value'] = explode(',', $value['value']);
  26. }
  27. if ($value['type'] == 'array') {
  28. $value['value'] = (array)json_decode($value['value'], true);
  29. }
  30. $wechat[$value['name']] = $value['value'];
  31. }
  32. $config = [
  33. 'app_id' => isset($wechat['appid']) ? trim($wechat['appid']) : '',
  34. 'secret' => isset($wechat['appsecret']) ? trim($wechat['appsecret']) : '',
  35. 'token' => isset($wechat['token']) ? trim($wechat['token']) : '',
  36. 'guzzle' => [
  37. 'timeout' => 10.0, // 超时时间(秒)
  38. 'verify' => false
  39. ],
  40. ];
  41. if (isset($wechat['encode']) && (int)$wechat['encode']>0 && isset($wechat['encodingaeskey']) &&
  42. !empty($wechat['encodingaeskey'])) {
  43. $config['aes_key'] = $wechat['encodingaeskey'];
  44. }
  45. return $config;
  46. }
  47. public static function application($cache = false)
  48. {
  49. (self::$instance === null || $cache === true) && (self::$instance = Factory::officialAccount(self::options()));
  50. return self::$instance;
  51. }
  52. public static function serve():Response
  53. {
  54. $wechat = self::application(true);
  55. $server = $wechat->server;
  56. self::hook($server);
  57. $response = $server->serve();
  58. return response($response->getContent());
  59. }
  60. /**
  61. * 监听行为
  62. * @param Guard $server
  63. */
  64. private static function hook($server)
  65. {
  66. $server->push(function ($message) {
  67. //微信消息前置操作
  68. switch ($message['MsgType']) {
  69. case 'event':
  70. switch (strtolower($message['Event'])) {
  71. case 'subscribe':
  72. $response = WechatReply::reply('subscribe');//关注回复
  73. break;
  74. case 'unsubscribe':
  75. //用户取消关注公众号前置操作
  76. break;
  77. case 'scan':
  78. $response = WechatReply::reply('subscribe');//扫码关注
  79. break;
  80. case 'location':
  81. $response = MessageRepositories::wechatEventLocation($message);
  82. break;
  83. case 'click':
  84. $response = WechatReply::reply($message['EventKey']);//点击事件
  85. break;
  86. case 'view':
  87. $response = MessageRepositories::wechatEventView($message);
  88. break;
  89. }
  90. break;
  91. case 'text':
  92. $response = WechatReply::reply($message['Content']);
  93. break;
  94. case 'image':
  95. $response = MessageRepositories::wechatMessageImage($message);
  96. break;
  97. case 'voice':
  98. $response = MessageRepositories::wechatMessageVoice($message);
  99. break;
  100. case 'video':
  101. $response = MessageRepositories::wechatMessageVideo($message);
  102. break;
  103. case 'location':
  104. $response = MessageRepositories::wechatMessageLocation($message);
  105. break;
  106. case 'link':
  107. $response = MessageRepositories::wechatMessageLink($message);
  108. break;
  109. // ... 其它消息
  110. default:
  111. $response = MessageRepositories::wechatMessageOther($message);
  112. break;
  113. }
  114. return $response ?? false;
  115. });
  116. }
  117. /**
  118. * 上传永久素材接口
  119. * @return object
  120. */
  121. public static function materialService()
  122. {
  123. return self::application()->material;
  124. }
  125. /**
  126. * 客服消息接口
  127. * @return object
  128. */
  129. public static function staffService()
  130. {
  131. return self::application()->customer_service;
  132. }
  133. /**
  134. * 微信公众号菜单接口
  135. * @return object
  136. */
  137. public static function menuService()
  138. {
  139. return self::application()->menu;
  140. }
  141. /**
  142. * 用户标签接口
  143. * @return object
  144. */
  145. public static function userTagService()
  146. {
  147. return self::application()->user_tag;
  148. }
  149. /**
  150. * 回复文本消息
  151. * @param string $content 文本内容
  152. * @return Text
  153. */
  154. public static function textMessage($content)
  155. {
  156. return new Text($content);
  157. }
  158. /**
  159. * 回复图片消息
  160. * @param string $media_id 媒体资源 ID
  161. * @return Image
  162. */
  163. public static function imageMessage($media_id)
  164. {
  165. return new Image($media_id);
  166. }
  167. /**
  168. * 回复视频消息
  169. * @param string $media_id 媒体资源 ID
  170. * @param string $title 标题
  171. * @param string $description 描述
  172. * @param null $thumb_media_id 封面资源 ID
  173. * @return Video
  174. */
  175. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  176. {
  177. return new Video(
  178. $media_id,
  179. ['title' => $title, 'description' => $description, 'thumb_media_id' => $thumb_media_id]
  180. );
  181. }
  182. /**
  183. * 回复声音消息
  184. * @param string $media_id 媒体资源 ID
  185. * @return Voice
  186. */
  187. public static function voiceMessage($media_id)
  188. {
  189. return new Voice($media_id);
  190. }
  191. /**
  192. * 回复图文消息
  193. * @param string|array $title 标题
  194. * @param string $description 描述
  195. * @param string $url URL
  196. * @param string $image 图片链接
  197. * @return Video
  198. */
  199. public static function newsMessage($data)
  200. {
  201. $items = [
  202. new NewsItem([
  203. 'title' => $data['title'],
  204. 'description' => $data['description'],
  205. 'url' => $data['url'],
  206. 'image' => $data['image'],
  207. ]),
  208. ];
  209. return new News($items);
  210. }
  211. /**
  212. * 回复素材消息
  213. * @param string $type [mpnews、 mpvideo、voice、image]
  214. * @param string $media_id 素材 ID
  215. * @return Material
  216. */
  217. public static function materialMessage($type, $media_id)
  218. {
  219. return new Media($media_id, $type);
  220. }
  221. /**
  222. * 作为客服消息发送
  223. * @param $to
  224. * @param $message
  225. * @return bool
  226. */
  227. public static function staffTo($to, $message)
  228. {
  229. $staff = self::staffService();
  230. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  231. $res = $staff->to($to)->send();
  232. return $res;
  233. }
  234. /**
  235. * jsSdk
  236. * @return object
  237. */
  238. public static function jsService()
  239. {
  240. return self::application()->jssdk;
  241. }
  242. public static function jsSdk($url = '')
  243. {
  244. $apiList = [
  245. 'editAddress', 'openAddress', 'updateTimelineShareData', 'updateAppMessageShareData', 'onMenuShareTimeline',
  246. 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord',
  247. 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice',
  248. 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice',
  249. 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems',
  250. 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode',
  251. 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'
  252. ];
  253. $jsService = self::jsService();
  254. if ($url) {
  255. $jsService->setUrl($url);
  256. }
  257. try {
  258. return $jsService->buildConfig($apiList, $debug = false, $beta = false, $json = false);
  259. } catch (\Exception $e) {
  260. return '{}';
  261. }
  262. }
  263. /**
  264. * 用户授权
  265. * @return object
  266. */
  267. public static function oauthService()
  268. {
  269. return self::application()->oauth;
  270. }
  271. /**
  272. * 用户接口
  273. * @return object
  274. */
  275. public static function userService()
  276. {
  277. return self::application()->user;
  278. }
  279. /**
  280. * 获得用户信息
  281. * @param array|string $openid
  282. * @return object
  283. */
  284. public static function getUserInfo($openid)
  285. {
  286. $userService = self::userService();
  287. $userInfo = $userService->get($openid);
  288. return $userInfo;
  289. }
  290. /**
  291. * 获得用户列表
  292. * @param array|string $openid
  293. * @return object
  294. */
  295. public static function getUserList()
  296. {
  297. $userService = self::userService();
  298. $userList = $userService->list();
  299. return $userList;
  300. }
  301. /**
  302. * 模板消息接口
  303. * @return \EasyWeChat\Notice\Notice
  304. */
  305. public static function noticeService()
  306. {
  307. return self::application()->template_message;
  308. }
  309. public static function sendTemplate($openid, $templateId, array $data, $url = null, $defaultColor = null)
  310. {
  311. $data = [
  312. 'touser' => $openid,
  313. 'template_id' => $templateId,
  314. 'url' => $url,
  315. 'data' => $data
  316. ];
  317. return self::noticeService()->send($data);
  318. }
  319. /**
  320. * 微信二维码生成接口
  321. * @return \EasyWeChat\QRCode\QRCode
  322. */
  323. public static function qrcodeService()
  324. {
  325. return self::application()->qrcode;
  326. }
  327. /**
  328. * 短链接生成接口
  329. * @return \EasyWeChat\Url\Url
  330. */
  331. public static function urlService()
  332. {
  333. return self::application()->url;
  334. }
  335. }