WechatService.php 22 KB

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