WechatService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace service;
  12. use app\admin\model\wechat\WechatMessage;
  13. use behavior\wechat\MessageBehavior;
  14. use behavior\wechat\PaymentBehavior;
  15. use EasyWeChat\Foundation\Application;
  16. use EasyWeChat\Message\Article;
  17. use EasyWeChat\Message\Image;
  18. use EasyWeChat\Message\Material;
  19. use EasyWeChat\Message\News;
  20. use EasyWeChat\Message\Text;
  21. use EasyWeChat\Message\Video;
  22. use EasyWeChat\Message\Voice;
  23. use EasyWeChat\Payment\Order;
  24. use EasyWeChat\Server\Guard;
  25. use EasyWeChat\Support\XML;
  26. use think\Request;
  27. use think\Url;
  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']);
  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']) ? $wechat['wechat_appid']:'',
  37. 'secret'=>isset($wechat['wechat_appsecret']) ? $wechat['wechat_appsecret']:'',
  38. 'token'=>isset($wechat['wechat_token']) ? $wechat['wechat_token']:'',
  39. 'aes_key' => isset($wechat['wechat_encodingaeskey']) ? $wechat['wechat_encodingaeskey']:'',
  40. 'guzzle' => [
  41. 'timeout' => 10.0, // 超时时间(秒)
  42. ],
  43. ];
  44. if(isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1){
  45. $config['payment'] = [
  46. 'merchant_id'=>$payment['pay_weixin_mchid'],
  47. 'key'=>$payment['pay_weixin_key'],
  48. 'cert_path'=>realpath('.'.$payment['pay_weixin_client_cert']),
  49. 'key_path'=>realpath('.'.$payment['pay_weixin_client_key']),
  50. 'notify_url'=>SystemConfigService::get('site_url').Url::build('wap/Wechat/notify')
  51. ];
  52. }
  53. return $config;
  54. }
  55. public static function application($cache = false)
  56. {
  57. (self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
  58. return self::$instance;
  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 ? $response : false;
  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 merchantPayService()
  145. {
  146. return self::application()->merchant_pay;
  147. }
  148. /**
  149. * 上传永久素材接口
  150. * @return \EasyWeChat\Material\Material
  151. */
  152. public static function materialService()
  153. {
  154. return self::application()->material;
  155. }
  156. /**
  157. * 上传临时素材接口
  158. * @return \EasyWeChat\Material\Temporary
  159. */
  160. public static function materialTemporaryService()
  161. {
  162. return self::application()->material_temporary;
  163. }
  164. /**
  165. * 用户接口
  166. * @return \EasyWeChat\User\User
  167. */
  168. public static function userService()
  169. {
  170. return self::application()->user;
  171. }
  172. /**
  173. * 客服消息接口
  174. * @param null $to
  175. * @param null $message
  176. */
  177. public static function staffService()
  178. {
  179. return self::application()->staff;
  180. }
  181. /**
  182. * 微信公众号菜单接口
  183. * @return \EasyWeChat\Menu\Menu
  184. */
  185. public static function menuService()
  186. {
  187. return self::application()->menu;
  188. }
  189. /**
  190. * 微信二维码生成接口
  191. * @return \EasyWeChat\QRCode\QRCode
  192. */
  193. public static function qrcodeService()
  194. {
  195. return self::application()->qrcode;
  196. }
  197. /**
  198. * 短链接生成接口
  199. * @return \EasyWeChat\Url\Url
  200. */
  201. public static function urlService()
  202. {
  203. return self::application()->url;
  204. }
  205. /**
  206. * 用户授权
  207. * @return \Overtrue\Socialite\Providers\WeChatProvider
  208. */
  209. public static function oauthService()
  210. {
  211. return self::application()->oauth;
  212. }
  213. /**
  214. * 模板消息接口
  215. * @return \EasyWeChat\Notice\Notice
  216. */
  217. public static function noticeService()
  218. {
  219. return self::application()->notice;
  220. }
  221. public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = null)
  222. {
  223. $notice = self::noticeService()->to($openid)->template($templateId)->andData($data);
  224. if($url !== null) $notice->url($url);
  225. if($defaultColor !== null) $notice->defaultColor($defaultColor);
  226. return $notice->send();
  227. }
  228. /*
  229. * 企业支付给个人
  230. * @param $partner_trade_no string 订单号
  231. * @param $openid string 被支付用户openid
  232. * @param $re_user_name string 真实姓名
  233. * @param $money string 支付金额
  234. * @return array
  235. * */
  236. public static function PayPersonal($partner_trade_no,$openid,$money,$re_user_name='默认姓名')
  237. {
  238. $merchantPayData = [
  239. 'partner_trade_no' => $partner_trade_no, //随机字符串作为订单号,跟红包和支付一个概念。
  240. 'openid' => $openid, //收款人的openid
  241. 'check_name' => 'NO_CHECK', //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
  242. 're_user_name'=>$re_user_name, //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
  243. 'amount' =>bcmul($money,100,0), //单位为分
  244. 'desc' => '企业付款',
  245. 'spbill_create_ip' =>Request::instance()->ip(), //发起交易的IP地址
  246. ];
  247. return self::merchantPayService()->send($merchantPayData);
  248. }
  249. /**
  250. * 支付
  251. * @return \EasyWeChat\Payment\Payment
  252. */
  253. public static function paymentService()
  254. {
  255. return self::application()->payment;
  256. }
  257. public static function downloadBill($day,$type = 'ALL')
  258. {
  259. }
  260. public static function userTagService()
  261. {
  262. return self::application()->user_tag;
  263. }
  264. public static function userGroupService()
  265. {
  266. return self::application()->user_group;
  267. }
  268. /**
  269. * 生成支付订单对象
  270. * @param $openid
  271. * @param $out_trade_no
  272. * @param $total_fee
  273. * @param $attach
  274. * @param $body
  275. * @param string $detail
  276. * @param string $trade_type
  277. * @param array $options
  278. * @return Order
  279. */
  280. protected static function paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail='',$trade_type='JSAPI',$options = [])
  281. {
  282. $total_fee = bcmul($total_fee,100,0);
  283. $order = array_merge(compact('openid','out_trade_no','total_fee','attach','body','detail','trade_type'),$options);
  284. if($order['detail'] == '') unset($order['detail']);
  285. return new Order($order);
  286. }
  287. /**
  288. * 获得下单ID
  289. * @param $openid
  290. * @param $out_trade_no
  291. * @param $total_fee
  292. * @param $attach
  293. * @param $body
  294. * @param string $detail
  295. * @param string $trade_type
  296. * @param array $options
  297. * @return mixed
  298. */
  299. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
  300. {
  301. $order = self::paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options);
  302. $result = self::paymentService()->prepare($order);
  303. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
  304. try{
  305. HookService::listen('wechat_payment_prepare',$order,$result->prepay_id,false,PaymentBehavior::class);
  306. }catch (\Exception $e){}
  307. return $result->prepay_id;
  308. }else{
  309. if($result->return_code == 'FAIL'){
  310. exception('微信支付错误返回:'.$result->return_msg);
  311. }else if(isset($result->err_code)){
  312. exception('微信支付错误返回:'.$result->err_code_des);
  313. }else{
  314. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  315. }
  316. exit;
  317. }
  318. }
  319. /**
  320. * 获得jsSdk支付参数
  321. * @param $openid
  322. * @param $out_trade_no
  323. * @param $total_fee
  324. * @param $attach
  325. * @param $body
  326. * @param string $detail
  327. * @param string $trade_type
  328. * @param array $options
  329. * @return array|string
  330. */
  331. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
  332. {
  333. return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options));
  334. }
  335. /**
  336. * 使用商户订单号退款
  337. * @param $orderNo
  338. * @param $refundNo
  339. * @param $totalFee
  340. * @param null $refundFee
  341. * @param null $opUserId
  342. * @param string $refundReason
  343. * @param string $type
  344. * @param string $refundAccount
  345. */
  346. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '' , $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  347. {
  348. $totalFee = floatval($totalFee);
  349. $refundFee = floatval($refundFee);
  350. return self::paymentService()->refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$type,$refundAccount,$refundReason);
  351. }
  352. public static function payOrderRefund($orderNo, array $opt)
  353. {
  354. if(!isset($opt['pay_price'])) exception('缺少pay_price');
  355. $totalFee = floatval(bcmul($opt['pay_price'],100,0));
  356. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'],100,0)) : null;
  357. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  358. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  359. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  360. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  361. /*仅针对老资金流商户使用
  362. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  363. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  364. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  365. try{
  366. $res = (self::refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$refundReason,$type,$refundAccount));
  367. if($res->return_code == 'FAIL') exception('退款失败:'.$res->return_msg);
  368. if(isset($res->err_code)) exception('退款失败:'.$res->err_code_des);
  369. }catch (\Exception $e){
  370. exception($e->getMessage());
  371. }
  372. return true;
  373. }
  374. /**
  375. * 微信支付成功回调接口
  376. */
  377. public static function handleNotify()
  378. {
  379. self::paymentService()->handleNotify(function($notify, $successful){
  380. if($successful && isset($notify->out_trade_no)){
  381. WechatMessage::setOnceMessage($notify,$notify->openid,'payment_success',$notify->out_trade_no);
  382. return HookService::listen('wechat_pay_success',$notify,null,true,PaymentBehavior::class);
  383. }
  384. });
  385. }
  386. /**
  387. * jsSdk
  388. * @return \EasyWeChat\Js\Js
  389. */
  390. public static function jsService()
  391. {
  392. return self::application()->js;
  393. }
  394. public static function jsSdk($url = '')
  395. {
  396. $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'];
  397. $jsService = self::jsService();
  398. if($url) $jsService->setUrl($url);
  399. try{
  400. return $jsService->config($apiList);
  401. }catch (\Exception $e){
  402. return '{}';
  403. }
  404. }
  405. /**
  406. * 回复文本消息
  407. * @param string $content 文本内容
  408. * @return Text
  409. */
  410. public static function textMessage($content)
  411. {
  412. return new Text(compact('content'));
  413. }
  414. /**
  415. * 回复图片消息
  416. * @param string $media_id 媒体资源 ID
  417. * @return Image
  418. */
  419. public static function imageMessage($media_id)
  420. {
  421. return new Image(compact('media_id'));
  422. }
  423. /**
  424. * 回复视频消息
  425. * @param string $media_id 媒体资源 ID
  426. * @param string $title 标题
  427. * @param string $description 描述
  428. * @param null $thumb_media_id 封面资源 ID
  429. * @return Video
  430. */
  431. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  432. {
  433. return new Video(compact('media_id','title','description','thumb_media_id'));
  434. }
  435. /**
  436. * 回复声音消息
  437. * @param string $media_id 媒体资源 ID
  438. * @return Voice
  439. */
  440. public static function voiceMessage($media_id)
  441. {
  442. return new Voice(compact('media_id'));
  443. }
  444. /**
  445. * 回复图文消息
  446. * @param string|array $title 标题
  447. * @param string $description 描述
  448. * @param string $url URL
  449. * @param string $image 图片链接
  450. */
  451. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  452. {
  453. if(is_array($title)){
  454. if(isset($title[0]) && is_array($title[0])){
  455. $newsList = [];
  456. foreach ($title as $news){
  457. $newsList[] = self::newsMessage($news);
  458. }
  459. return $newsList;
  460. }else{
  461. $data = $title;
  462. }
  463. }else{
  464. $data = compact('title','description','url','image');
  465. }
  466. return new News($data);
  467. }
  468. /**
  469. * 回复文章消息
  470. * @param string|array $title 标题
  471. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  472. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  473. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  474. * @param string $author 作者
  475. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  476. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  477. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  478. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  479. * @return Article
  480. */
  481. 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)
  482. {
  483. $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');
  484. return new Article($data);
  485. }
  486. /**
  487. * 回复素材消息
  488. * @param string $type [mpnews、 mpvideo、voice、image]
  489. * @param string $media_id 素材 ID
  490. * @return Material
  491. */
  492. public static function materialMessage($type, $media_id)
  493. {
  494. return new Material($type,$media_id);
  495. }
  496. /**
  497. * 作为客服消息发送
  498. * @param $to
  499. * @param $message
  500. * @return bool
  501. */
  502. public static function staffTo($to, $message)
  503. {
  504. $staff = self::staffService();
  505. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  506. $res = $staff->to($to)->send();
  507. HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
  508. return $res;
  509. }
  510. /**
  511. * 获得用户信息
  512. * @param array|string $openid
  513. * @return \EasyWeChat\Support\Collection
  514. */
  515. public static function getUserInfo($openid)
  516. {
  517. $userService = self::userService();
  518. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  519. return $userInfo;
  520. }
  521. }