WechatService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. namespace addons\weixin\library;
  3. use addons\weixin\library\MessageRepositories;
  4. use EasyWeChat\Foundation\Application;
  5. use EasyWeChat\Message\Article;
  6. use EasyWeChat\Message\Image;
  7. use EasyWeChat\Message\Material;
  8. use EasyWeChat\Message\News;
  9. use EasyWeChat\Message\Text;
  10. use EasyWeChat\Message\Video;
  11. use EasyWeChat\Message\Voice;
  12. use EasyWeChat\Payment\Order;
  13. use EasyWeChat\Server\Guard;
  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 = new Application(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->setMessageHandler(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. * @param string $account
  120. * @return \EasyWeChat\Message\Transfer
  121. */
  122. public static function transfer($account = '')
  123. {
  124. $transfer = new \EasyWeChat\Message\Transfer();
  125. return empty($account) ? $transfer : $transfer->to($account);
  126. }
  127. /**
  128. * 上传永久素材接口
  129. * @return \EasyWeChat\Material\Material
  130. */
  131. public static function materialService()
  132. {
  133. return self::application()->material;
  134. }
  135. /**
  136. * 上传临时素材接口
  137. * @return \EasyWeChat\Material\Temporary
  138. */
  139. public static function materialTemporaryService()
  140. {
  141. return self::application()->material_temporary;
  142. }
  143. /**
  144. * 用户接口
  145. * @return \EasyWeChat\User\User
  146. */
  147. public static function userService()
  148. {
  149. return self::application()->user;
  150. }
  151. /**
  152. * 客服消息接口
  153. * @param null $to
  154. * @param null $message
  155. */
  156. public static function staffService()
  157. {
  158. return self::application()->staff;
  159. }
  160. /**
  161. * 微信公众号菜单接口
  162. * @return \EasyWeChat\Menu\Menu
  163. */
  164. public static function menuService()
  165. {
  166. return self::application()->menu;
  167. }
  168. /**
  169. * 微信二维码生成接口
  170. * @return \EasyWeChat\QRCode\QRCode
  171. */
  172. public static function qrcodeService()
  173. {
  174. return self::application()->qrcode;
  175. }
  176. /**
  177. * 短链接生成接口
  178. * @return \EasyWeChat\Url\Url
  179. */
  180. public static function urlService()
  181. {
  182. return self::application()->url;
  183. }
  184. /**
  185. * 用户授权
  186. * @return \Overtrue\Socialite\Providers\WeChatProvider
  187. */
  188. public static function oauthService()
  189. {
  190. return self::application()->oauth;
  191. }
  192. /**
  193. * 模板消息接口
  194. * @return \EasyWeChat\Notice\Notice
  195. */
  196. public static function noticeService()
  197. {
  198. return self::application()->notice;
  199. }
  200. public static function sendTemplate($openid, $templateId, array $data, $url = null, $defaultColor = null)
  201. {
  202. $notice = self::noticeService()->to($openid)->template($templateId)->andData($data);
  203. if ($url !== null) {
  204. $notice->url($url);
  205. }
  206. if ($defaultColor !== null) {
  207. $notice->defaultColor($defaultColor);
  208. }
  209. return $notice->send();
  210. }
  211. /**
  212. * 支付
  213. * @return \EasyWeChat\Payment\Payment
  214. */
  215. public static function paymentService()
  216. {
  217. return self::application()->payment;
  218. }
  219. public static function downloadBill($day, $type = 'ALL')
  220. {
  221. // $payment = self::paymentService();
  222. // $merchant = $payment->getMerchant();
  223. // $params = [
  224. // 'appid' => $merchant->app_id,
  225. // 'bill_date'=>$day,
  226. // 'bill_type'=>strtoupper($type),
  227. // 'mch_id'=> $merchant->merchant_id,
  228. // 'nonce_str' => uniqid()
  229. // ];
  230. // $params['sign'] = \EasyWeChat\Payment\generate_sign($params, $merchant->key, 'md5');
  231. // $xml = XML::build($params);
  232. // dump(self::paymentService()->downloadBill($day)->getContents());
  233. // dump($payment->getHttp()->request('https://api.mch.weixin.qq.com/pay/downloadbill','POST',[
  234. // 'body' => $xml,
  235. // 'stream'=>true
  236. // ])->getBody()->getContents());
  237. }
  238. public static function userTagService()
  239. {
  240. return self::application()->user_tag;
  241. }
  242. public static function userGroupService()
  243. {
  244. return self::application()->user_group;
  245. }
  246. /**
  247. * jsSdk
  248. * @return \EasyWeChat\Js\Js
  249. */
  250. public static function jsService()
  251. {
  252. return self::application()->js;
  253. }
  254. public static function jsSdk($url = '')
  255. {
  256. $apiList = [
  257. 'editAddress', 'openAddress', 'updateTimelineShareData', 'updateAppMessageShareData', 'onMenuShareTimeline',
  258. 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord',
  259. 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice',
  260. 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice',
  261. 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems',
  262. 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode',
  263. 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'
  264. ];
  265. $jsService = self::jsService();
  266. if ($url) {
  267. $jsService->setUrl($url);
  268. }
  269. try {
  270. return $jsService->config($apiList);
  271. } catch (\Exception $e) {
  272. return '{}';
  273. }
  274. }
  275. /**
  276. * 回复文本消息
  277. * @param string $content 文本内容
  278. * @return Text
  279. */
  280. public static function textMessage($content)
  281. {
  282. return new Text(compact('content'));
  283. }
  284. /**
  285. * 回复图片消息
  286. * @param string $media_id 媒体资源 ID
  287. * @return Image
  288. */
  289. public static function imageMessage($media_id)
  290. {
  291. return new Image(compact('media_id'));
  292. }
  293. /**
  294. * 回复视频消息
  295. * @param string $media_id 媒体资源 ID
  296. * @param string $title 标题
  297. * @param string $description 描述
  298. * @param null $thumb_media_id 封面资源 ID
  299. * @return Video
  300. */
  301. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  302. {
  303. return new Video(compact('media_id', 'title', 'description', 'thumb_media_id'));
  304. }
  305. /**
  306. * 回复声音消息
  307. * @param string $media_id 媒体资源 ID
  308. * @return Voice
  309. */
  310. public static function voiceMessage($media_id)
  311. {
  312. return new Voice(compact('media_id'));
  313. }
  314. /**
  315. * 回复图文消息
  316. * @param string|array $title 标题
  317. * @param string $description 描述
  318. * @param string $url URL
  319. * @param string $image 图片链接
  320. */
  321. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  322. {
  323. if (is_array($title)) {
  324. if (isset($title[0]) && is_array($title[0])) {
  325. $newsList = [];
  326. foreach ($title as $news) {
  327. $newsList[] = self::newsMessage($news);
  328. }
  329. return $newsList;
  330. } else {
  331. $data = $title;
  332. }
  333. } else {
  334. $data = compact('title', 'description', 'url', 'image');
  335. }
  336. return new News($data);
  337. }
  338. /**
  339. * 回复文章消息
  340. * @param string|array $title 标题
  341. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  342. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  343. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  344. * @param string $author 作者
  345. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  346. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  347. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  348. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  349. * @return Article
  350. */
  351. public static function articleMessage($title, $thumb_media_id, $source_url, $content = '', $author = '', $digest = '', $show_cover_pic = 0, $need_open_comment = 0, $only_fans_can_comment = 1)
  352. {
  353. $data = is_array($title) ? $title : compact('title', 'thumb_media_id', 'source_url', 'content', 'author',
  354. 'digest', 'show_cover_pic', 'need_open_comment', 'only_fans_can_comment');
  355. return new Article($data);
  356. }
  357. /**
  358. * 回复素材消息
  359. * @param string $type [mpnews、 mpvideo、voice、image]
  360. * @param string $media_id 素材 ID
  361. * @return Material
  362. */
  363. public static function materialMessage($type, $media_id)
  364. {
  365. return new Material($type, $media_id);
  366. }
  367. /**
  368. * 作为客服消息发送
  369. * @param $to
  370. * @param $message
  371. * @return bool
  372. */
  373. public static function staffTo($to, $message)
  374. {
  375. $staff = self::staffService();
  376. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  377. $res = $staff->to($to)->send();
  378. return $res;
  379. }
  380. /**
  381. * 获得用户信息
  382. * @param array|string $openid
  383. * @return \EasyWeChat\Support\Collection
  384. */
  385. public static function getUserInfo($openid)
  386. {
  387. $userService = self::userService();
  388. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  389. $userInfo = json_decode(json_encode($userInfo), true);
  390. return $userInfo;
  391. }
  392. }