WechatService.php 19 KB

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