WechatService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/23
  6. */
  7. namespace service;
  8. use app\admin\model\wechat\WechatMessage;
  9. use behavior\wechat\MessageBehavior;
  10. use behavior\wechat\PaymentBehavior;
  11. use EasyWeChat\Foundation\Application;
  12. use EasyWeChat\Message\Article;
  13. use EasyWeChat\Message\Image;
  14. use EasyWeChat\Message\Material;
  15. use EasyWeChat\Message\News;
  16. use EasyWeChat\Message\Text;
  17. use EasyWeChat\Message\Video;
  18. use EasyWeChat\Message\Voice;
  19. use EasyWeChat\Payment\Order;
  20. use EasyWeChat\Server\Guard;
  21. use EasyWeChat\Support\XML;
  22. use think\Url;
  23. class WechatService
  24. {
  25. private static $instance = null;
  26. /**获取微信配置参数
  27. * @return array
  28. */
  29. public static function options()
  30. {
  31. $wechat = SystemConfigService::more(['wechat_appid','wechat_appsecret','wechat_token']);
  32. $payment = SystemConfigService::more(['pay_weixin_mchid','pay_weixin_client_cert','pay_weixin_client_key','pay_weixin_key','pay_weixin_open']);
  33. $config = [
  34. 'app_id'=>isset($wechat['wechat_appid']) ? trim($wechat['wechat_appid']):'',
  35. 'secret'=>isset($wechat['wechat_appsecret']) ? trim($wechat['wechat_appsecret']):'',
  36. 'token'=>isset($wechat['wechat_token']) ? trim($wechat['wechat_token']):'',
  37. 'guzzle' => [
  38. 'timeout' => 10.0, // 超时时间(秒)
  39. ],
  40. ];
  41. if(isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1){
  42. $config['payment'] = [
  43. 'merchant_id'=>trim($payment['pay_weixin_mchid']),
  44. 'key'=>trim($payment['pay_weixin_key']),
  45. 'cert_path'=>realpath('.'.$payment['pay_weixin_client_cert']),
  46. 'key_path'=>realpath('.'.$payment['pay_weixin_client_key']),
  47. 'notify_url'=>SystemConfigService::get('site_url').Url::build('wap/Wechat/notify')
  48. ];
  49. }
  50. return $config;
  51. }
  52. public static function application($cache = false)
  53. {
  54. (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
  55. return self::$instance;
  56. }
  57. /**
  58. * 微信接口
  59. */
  60. public static function serve()
  61. {
  62. $wechat = self::application(true);
  63. $server = $wechat->server;
  64. self::hook($server);
  65. $response = $server->serve();
  66. exit($response->getContent());
  67. }
  68. /**
  69. * 监听行为
  70. * @param Guard $server
  71. */
  72. private static function hook($server)
  73. {
  74. $server->setMessageHandler(function($message){
  75. $behavior = MessageBehavior::class;
  76. HookService::beforeListen('wechat_message',$message,null,true,$behavior);
  77. switch ($message->MsgType){
  78. case 'event':
  79. switch (strtolower($message->Event)){
  80. case 'subscribe':
  81. if(isset($message->EventKey)){
  82. $response = HookService::resultListen('wechat_event_scan_subscribe',$message,$message->EventKey,true,$behavior);
  83. }else{
  84. $response = HookService::resultListen('wechat_event_subscribe',$message,null,true,$behavior);
  85. }
  86. break;
  87. case 'unsubscribe':
  88. $response = HookService::resultListen('wechat_event_unsubscribe',$message,null,true,$behavior);
  89. break;
  90. case 'scan':
  91. $response = HookService::resultListen('wechat_event_scan',$message,$message->EventKey,true,$behavior);
  92. break;
  93. case 'location':
  94. $response = HookService::resultListen('wechat_event_location',$message,null,true,$behavior);
  95. break;
  96. case 'click':
  97. $response = HookService::resultListen('wechat_event_click',$message,null,true,$behavior);
  98. break;
  99. case 'view':
  100. $response = HookService::resultListen('wechat_event_view',$message,null,true,$behavior);
  101. break;
  102. }
  103. break;
  104. case 'text':
  105. $response = HookService::resultListen('wechat_message_text',$message,null,true,$behavior);
  106. break;
  107. case 'image':
  108. $response = HookService::resultListen('wechat_message_image',$message,null,true,$behavior);
  109. break;
  110. case 'voice':
  111. $response = HookService::resultListen('wechat_message_voice',$message,null,true,$behavior);
  112. break;
  113. case 'video':
  114. $response = HookService::resultListen('wechat_message_video',$message,null,true,$behavior);
  115. break;
  116. case 'location':
  117. $response = HookService::resultListen('wechat_message_location',$message,null,true,$behavior);
  118. break;
  119. case 'link':
  120. $response = HookService::resultListen('wechat_message_link',$message,null,true,$behavior);
  121. break;
  122. // ... 其它消息
  123. default:
  124. $response = HookService::resultListen('wechat_message_other',$message,null,true,$behavior);
  125. break;
  126. }
  127. return $response;
  128. });
  129. }
  130. /**
  131. * 多客服消息转发
  132. * @param string $account
  133. * @return \EasyWeChat\Message\Transfer
  134. */
  135. public static function transfer($account = '')
  136. {
  137. $transfer = new \EasyWeChat\Message\Transfer();
  138. return empty($account) ? $transfer : $transfer->to($account);
  139. }
  140. /**
  141. * 上传永久素材接口
  142. * @return \EasyWeChat\Material\Material
  143. */
  144. public static function materialService()
  145. {
  146. return self::application()->material;
  147. }
  148. /**
  149. * 上传临时素材接口
  150. * @return \EasyWeChat\Material\Temporary
  151. */
  152. public static function materialTemporaryService()
  153. {
  154. return self::application()->material_temporary;
  155. }
  156. /**
  157. * 用户接口
  158. * @return \EasyWeChat\User\User
  159. */
  160. public static function userService()
  161. {
  162. return self::application()->user;
  163. }
  164. /**
  165. * 客服消息接口
  166. * @param null $to
  167. * @param null $message
  168. */
  169. public static function staffService()
  170. {
  171. return self::application()->staff;
  172. }
  173. /**
  174. * 微信公众号菜单接口
  175. * @return \EasyWeChat\Menu\Menu
  176. */
  177. public static function menuService()
  178. {
  179. return self::application()->menu;
  180. }
  181. /**
  182. * 微信二维码生成接口
  183. * @return \EasyWeChat\QRCode\QRCode
  184. */
  185. public static function qrcodeService()
  186. {
  187. return self::application()->qrcode;
  188. }
  189. /**
  190. * 短链接生成接口
  191. * @return \EasyWeChat\Url\Url
  192. */
  193. public static function urlService()
  194. {
  195. return self::application()->url;
  196. }
  197. /**
  198. * 用户授权
  199. * @return \Overtrue\Socialite\Providers\WeChatProvider
  200. */
  201. public static function oauthService()
  202. {
  203. return self::application()->oauth;
  204. }
  205. /**
  206. * 模板消息接口
  207. * @return \EasyWeChat\Notice\Notice
  208. */
  209. public static function noticeService()
  210. {
  211. return self::application()->notice;
  212. }
  213. public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = null)
  214. {
  215. $notice = self::noticeService()->to($openid)->template($templateId)->andData($data);
  216. if($url !== null) $notice->url($url);
  217. if($defaultColor !== null) $notice->defaultColor($defaultColor);
  218. return $notice->send();
  219. }
  220. /**
  221. * 支付
  222. * @return \EasyWeChat\Payment\Payment
  223. */
  224. public static function paymentService()
  225. {
  226. return self::application()->payment;
  227. }
  228. public static function downloadBill($day,$type = 'ALL')
  229. {
  230. // $payment = self::paymentService();
  231. // $merchant = $payment->getMerchant();
  232. // $params = [
  233. // 'appid' => $merchant->app_id,
  234. // 'bill_date'=>$day,
  235. // 'bill_type'=>strtoupper($type),
  236. // 'mch_id'=> $merchant->merchant_id,
  237. // 'nonce_str' => uniqid()
  238. // ];
  239. // $params['sign'] = \EasyWeChat\Payment\generate_sign($params, $merchant->key, 'md5');
  240. // $xml = XML::build($params);
  241. // dump(self::paymentService()->downloadBill($day)->getContents());
  242. // dump($payment->getHttp()->request('https://api.mch.weixin.qq.com/pay/downloadbill','POST',[
  243. // 'body' => $xml,
  244. // 'stream'=>true
  245. // ])->getBody()->getContents());
  246. }
  247. public static function userTagService()
  248. {
  249. return self::application()->user_tag;
  250. }
  251. public static function userGroupService()
  252. {
  253. return self::application()->user_group;
  254. }
  255. /**
  256. * 生成支付订单对象
  257. * @param $openid
  258. * @param $out_trade_no
  259. * @param $total_fee
  260. * @param $attach
  261. * @param $body
  262. * @param string $detail
  263. * @param string $trade_type
  264. * @param array $options
  265. * @return Order
  266. */
  267. protected static function paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail='',$trade_type='JSAPI',$options = [])
  268. {
  269. $total_fee = bcmul($total_fee,100,0);
  270. $order = array_merge(compact('openid','out_trade_no','total_fee','attach','body','detail','trade_type'),$options);
  271. if($order['detail'] == '') unset($order['detail']);
  272. return new Order($order);
  273. }
  274. /**
  275. * 获得下单ID
  276. * @param $openid
  277. * @param $out_trade_no
  278. * @param $total_fee
  279. * @param $attach
  280. * @param $body
  281. * @param string $detail
  282. * @param string $trade_type
  283. * @param array $options
  284. * @return mixed
  285. */
  286. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
  287. {
  288. $order = self::paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options);
  289. $result = self::paymentService()->prepare($order);
  290. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
  291. try{
  292. HookService::listen('wechat_payment_prepare',$order,$result->prepay_id,false,PaymentBehavior::class);
  293. }catch (\Exception $e){}
  294. return $result->prepay_id;
  295. }else{
  296. if($result->return_code == 'FAIL'){
  297. exception('微信支付错误返回:'.$result->return_msg);
  298. }else if(isset($result->err_code)){
  299. exception('微信支付错误返回:'.$result->err_code_des);
  300. }else{
  301. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  302. }
  303. exit;
  304. }
  305. }
  306. /**
  307. * 获得jsSdk支付参数
  308. * @param $openid
  309. * @param $out_trade_no
  310. * @param $total_fee
  311. * @param $attach
  312. * @param $body
  313. * @param string $detail
  314. * @param string $trade_type
  315. * @param array $options
  316. * @return array|string
  317. */
  318. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
  319. {
  320. return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options));
  321. }
  322. /**
  323. * 使用商户订单号退款
  324. * @param $orderNo
  325. * @param $refundNo
  326. * @param $totalFee
  327. * @param null $refundFee
  328. * @param null $opUserId
  329. * @param string $refundReason
  330. * @param string $type
  331. * @param string $refundAccount
  332. */
  333. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '' , $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  334. {
  335. $totalFee = floatval($totalFee);
  336. $refundFee = floatval($refundFee);
  337. return self::paymentService()->refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$type,$refundAccount,$refundReason);
  338. }
  339. /**订单退款
  340. * @param $orderNo
  341. * @param array $opt
  342. * @return bool
  343. */
  344. public static function payOrderRefund($orderNo, array $opt)
  345. {
  346. if(!isset($opt['pay_price'])) exception('缺少pay_price');
  347. $totalFee = floatval(bcmul($opt['pay_price'],100,0));
  348. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'],100,0)) : null;
  349. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  350. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  351. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  352. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  353. /*仅针对老资金流商户使用
  354. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  355. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  356. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  357. try{
  358. $res = (self::refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$refundReason,$type,$refundAccount));
  359. if($res->return_code == 'FAIL') exception('退款失败:'.$res->return_msg);
  360. if(isset($res->err_code)) exception('退款失败:'.$res->err_code_des);
  361. }catch (\Exception $e){
  362. exception($e->getMessage());
  363. }
  364. return true;
  365. }
  366. /**
  367. * 微信支付成功回调接口
  368. */
  369. public static function handleNotify()
  370. {
  371. self::paymentService()->handleNotify(function($notify, $successful){
  372. if($successful && isset($notify->out_trade_no)){
  373. WechatMessage::setOnceMessage($notify,$notify->openid,'payment_success',$notify->out_trade_no);
  374. return HookService::listen('wechat_pay_success',$notify,null,true,PaymentBehavior::class);
  375. }
  376. });
  377. }
  378. /**
  379. * jsSdk
  380. * @return \EasyWeChat\Js\Js
  381. */
  382. public static function jsService()
  383. {
  384. return self::application()->js;
  385. }
  386. /** jsSdk
  387. * @param string $url
  388. * @return array|string
  389. */
  390. public static function jsSdk($url = '')
  391. {
  392. $apiList = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'];
  393. $jsService = self::jsService();
  394. if($url) $jsService->setUrl($url);
  395. try{
  396. return $jsService->config($apiList);
  397. }catch (\Exception $e){
  398. return '{}';
  399. }
  400. }
  401. /**
  402. * 回复文本消息
  403. * @param string $content 文本内容
  404. * @return Text
  405. */
  406. public static function textMessage($content)
  407. {
  408. return new Text(compact('content'));
  409. }
  410. /**
  411. * 回复图片消息
  412. * @param string $media_id 媒体资源 ID
  413. * @return Image
  414. */
  415. public static function imageMessage($media_id)
  416. {
  417. return new Image(compact('media_id'));
  418. }
  419. /**
  420. * 回复视频消息
  421. * @param string $media_id 媒体资源 ID
  422. * @param string $title 标题
  423. * @param string $description 描述
  424. * @param null $thumb_media_id 封面资源 ID
  425. * @return Video
  426. */
  427. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  428. {
  429. return new Video(compact('media_id','title','description','thumb_media_id'));
  430. }
  431. /**
  432. * 回复声音消息
  433. * @param string $media_id 媒体资源 ID
  434. * @return Voice
  435. */
  436. public static function voiceMessage($media_id)
  437. {
  438. return new Voice(compact('media_id'));
  439. }
  440. /**
  441. * 回复图文消息
  442. * @param string|array $title 标题
  443. * @param string $description 描述
  444. * @param string $url URL
  445. * @param string $image 图片链接
  446. */
  447. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  448. {
  449. if(is_array($title)){
  450. if(isset($title[0]) && is_array($title[0])){
  451. $newsList = [];
  452. foreach ($title as $news){
  453. $newsList[] = self::newsMessage($news);
  454. }
  455. return $newsList;
  456. }else{
  457. $data = $title;
  458. }
  459. }else{
  460. $data = compact('title','description','url','image');
  461. }
  462. return new News($data);
  463. }
  464. /**
  465. * 回复文章消息
  466. * @param string|array $title 标题
  467. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  468. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  469. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  470. * @param string $author 作者
  471. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  472. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  473. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  474. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  475. * @return Article
  476. */
  477. 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)
  478. {
  479. $data = is_array($title) ? $title : compact('title','thumb_media_id','source_url','content','author','digest','show_cover_pic','need_open_comment','only_fans_can_comment');
  480. return new Article($data);
  481. }
  482. /**
  483. * 回复素材消息
  484. * @param string $type [mpnews、 mpvideo、voice、image]
  485. * @param string $media_id 素材 ID
  486. * @return Material
  487. */
  488. public static function materialMessage($type, $media_id)
  489. {
  490. return new Material($type,$media_id);
  491. }
  492. /**
  493. * 作为客服消息发送
  494. * @param $to
  495. * @param $message
  496. * @return bool
  497. */
  498. public static function staffTo($to, $message)
  499. {
  500. $staff = self::staffService();
  501. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  502. $res = $staff->to($to)->send();
  503. HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
  504. return $res;
  505. }
  506. /**
  507. * 获得用户信息
  508. * @param array|string $openid
  509. * @return \EasyWeChat\Support\Collection
  510. */
  511. public static function getUserInfo($openid)
  512. {
  513. $userService = self::userService();
  514. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  515. return $userInfo;
  516. }
  517. }