WechatService.php 19 KB

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