WechatService.php 22 KB

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