WechatService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 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. $response = '';
  78. switch ($message->MsgType) {
  79. case 'event':
  80. switch (strtolower($message->Event)) {
  81. case 'subscribe':
  82. if (isset($message->EventKey)) {
  83. $response = HookService::resultListen('wechat_event_scan_subscribe', $message, $message->EventKey, true, $behavior);
  84. } else {
  85. $response = HookService::resultListen('wechat_event_subscribe', $message, null, true, $behavior);
  86. }
  87. break;
  88. case 'unsubscribe':
  89. $response = HookService::resultListen('wechat_event_unsubscribe', $message, null, true, $behavior);
  90. break;
  91. case 'scan':
  92. $response = HookService::resultListen('wechat_event_scan', $message, $message->EventKey, true, $behavior);
  93. break;
  94. case 'location':
  95. $response = HookService::resultListen('wechat_event_location', $message, null, true, $behavior);
  96. break;
  97. case 'click':
  98. $response = HookService::resultListen('wechat_event_click', $message, null, true, $behavior);
  99. break;
  100. case 'view':
  101. $response = HookService::resultListen('wechat_event_view', $message, null, true, $behavior);
  102. break;
  103. }
  104. break;
  105. case 'text':
  106. $response = HookService::resultListen('wechat_message_text', $message, null, true, $behavior);
  107. break;
  108. case 'image':
  109. $response = HookService::resultListen('wechat_message_image', $message, null, true, $behavior);
  110. break;
  111. case 'voice':
  112. $response = HookService::resultListen('wechat_message_voice', $message, null, true, $behavior);
  113. break;
  114. case 'video':
  115. $response = HookService::resultListen('wechat_message_video', $message, null, true, $behavior);
  116. break;
  117. case 'location':
  118. $response = HookService::resultListen('wechat_message_location', $message, null, true, $behavior);
  119. break;
  120. case 'link':
  121. $response = HookService::resultListen('wechat_message_link', $message, null, true, $behavior);
  122. break;
  123. // ... 其它消息
  124. default:
  125. $response = HookService::resultListen('wechat_message_other', $message, null, true, $behavior);
  126. break;
  127. }
  128. return $response ? $response : false;
  129. });
  130. }
  131. /**
  132. * 多客服消息转发
  133. * @param string $account
  134. * @return \EasyWeChat\Message\Transfer
  135. */
  136. public static function transfer($account = '')
  137. {
  138. $transfer = new \EasyWeChat\Message\Transfer();
  139. return empty($account) ? $transfer : $transfer->to($account);
  140. }
  141. /**
  142. * 企业付款
  143. * @return \EasyWeChat\Material\Material
  144. */
  145. public static function merchantPayService()
  146. {
  147. return self::application()->merchant_pay;
  148. }
  149. /**
  150. * 上传永久素材接口
  151. * @return \EasyWeChat\Material\Material
  152. */
  153. public static function materialService()
  154. {
  155. return self::application()->material;
  156. }
  157. /**
  158. * 上传临时素材接口
  159. * @return \EasyWeChat\Material\Temporary
  160. */
  161. public static function materialTemporaryService()
  162. {
  163. return self::application()->material_temporary;
  164. }
  165. /**
  166. * 用户接口
  167. * @return \EasyWeChat\User\User
  168. */
  169. public static function userService()
  170. {
  171. return self::application()->user;
  172. }
  173. /**
  174. * 客服消息接口
  175. * @param null $to
  176. * @param null $message
  177. */
  178. public static function staffService()
  179. {
  180. return self::application()->staff;
  181. }
  182. /**
  183. * 微信公众号菜单接口
  184. * @return \EasyWeChat\Menu\Menu
  185. */
  186. public static function menuService()
  187. {
  188. return self::application()->menu;
  189. }
  190. /**
  191. * 微信二维码生成接口
  192. * @return \EasyWeChat\QRCode\QRCode
  193. */
  194. public static function qrcodeService()
  195. {
  196. return self::application()->qrcode;
  197. }
  198. /**
  199. * 短链接生成接口
  200. * @return \EasyWeChat\Url\Url
  201. */
  202. public static function urlService()
  203. {
  204. return self::application()->url;
  205. }
  206. /**
  207. * 用户授权
  208. * @return \Overtrue\Socialite\Providers\WeChatProvider
  209. */
  210. public static function oauthService()
  211. {
  212. return self::application()->oauth;
  213. }
  214. /**
  215. * 模板消息接口
  216. * @return \EasyWeChat\Notice\Notice
  217. */
  218. public static function noticeService()
  219. {
  220. return self::application()->notice;
  221. }
  222. public static function sendTemplate($openid, $templateId, array $data, $url = null, $defaultColor = null)
  223. {
  224. $notice = self::noticeService()->to($openid)->template($templateId)->andData($data);
  225. if ($url !== null) $notice->url($url);
  226. if ($defaultColor !== null) $notice->defaultColor($defaultColor);
  227. return $notice->send();
  228. }
  229. /*
  230. * 企业支付给个人
  231. * @param $partner_trade_no string 订单号
  232. * @param $openid string 被支付用户openid
  233. * @param $re_user_name string 真实姓名
  234. * @param $money string 支付金额
  235. * @return array
  236. * */
  237. public static function PayPersonal($partner_trade_no, $openid, $money, $re_user_name = '默认姓名')
  238. {
  239. $merchantPayData = [
  240. 'partner_trade_no' => $partner_trade_no, //随机字符串作为订单号,跟红包和支付一个概念。
  241. 'openid' => $openid, //收款人的openid
  242. 'check_name' => 'NO_CHECK', //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
  243. 're_user_name' => $re_user_name, //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
  244. 'amount' => bcmul($money, 100, 0), //单位为分
  245. 'desc' => '企业付款',
  246. 'spbill_create_ip' => Request::instance()->ip(), //发起交易的IP地址
  247. ];
  248. return self::merchantPayService()->send($merchantPayData);
  249. }
  250. /**
  251. * 支付
  252. * @return \EasyWeChat\Payment\Payment
  253. */
  254. public static function paymentService()
  255. {
  256. return self::application()->payment;
  257. }
  258. public static function downloadBill($day, $type = 'ALL')
  259. {
  260. }
  261. public static function userTagService()
  262. {
  263. return self::application()->user_tag;
  264. }
  265. public static function userGroupService()
  266. {
  267. return self::application()->user_group;
  268. }
  269. /**
  270. * 生成支付订单对象
  271. * @param $openid
  272. * @param $out_trade_no
  273. * @param $total_fee
  274. * @param $attach
  275. * @param $body
  276. * @param string $detail
  277. * @param string $trade_type
  278. * @param array $options
  279. * @return Order
  280. */
  281. protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  282. {
  283. $total_fee = bcmul($total_fee, 100, 0);
  284. $order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  285. if ($order['detail'] == '') unset($order['detail']);
  286. return new Order($order);
  287. }
  288. /**
  289. * 获得下单ID
  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 mixed
  299. */
  300. public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  301. {
  302. $order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  303. $result = self::paymentService()->prepare($order);
  304. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  305. try {
  306. HookService::listen('wechat_payment_prepare', $order, $result->prepay_id, false, PaymentBehavior::class);
  307. } catch (\Exception $e) {
  308. }
  309. return $result;
  310. } else {
  311. if ($result->return_code == 'FAIL') {
  312. exception('微信支付错误返回:' . $result->return_msg);
  313. } else if (isset($result->err_code)) {
  314. exception('微信支付错误返回:' . $result->err_code_des);
  315. } else {
  316. exception('没有获取微信支付的预支付ID,请重新发起支付!');
  317. }
  318. exit;
  319. }
  320. }
  321. /**获取二维码链接
  322. * @param $openid
  323. * @param $out_trade_no
  324. * @param $total_fee
  325. * @param $attach
  326. * @param $body
  327. * @param string $detail
  328. * @param string $trade_type
  329. * @param array $options
  330. * @return mixed
  331. */
  332. public static function nativePay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'NATIVE', $options = [])
  333. {
  334. $paymentPrepare = self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  335. return $paymentPrepare->code_url;
  336. }
  337. /**
  338. * 获得jsSdk支付参数
  339. * @param $openid
  340. * @param $out_trade_no
  341. * @param $total_fee
  342. * @param $attach
  343. * @param $body
  344. * @param string $detail
  345. * @param string $trade_type
  346. * @param array $options
  347. * @return array|string
  348. */
  349. public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  350. {
  351. $paymentPrepare = self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  352. return self::paymentService()->configForJSSDKPayment($paymentPrepare->prepay_id);
  353. }
  354. /**
  355. * 使用商户订单号退款
  356. * @param $orderNo
  357. * @param $refundNo
  358. * @param $totalFee
  359. * @param null $refundFee
  360. * @param null $opUserId
  361. * @param string $refundReason
  362. * @param string $type
  363. * @param string $refundAccount
  364. */
  365. public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  366. {
  367. $totalFee = floatval($totalFee);
  368. $refundFee = floatval($refundFee);
  369. return self::paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  370. }
  371. public static function payOrderRefund($orderNo, array $opt)
  372. {
  373. if (!isset($opt['pay_price'])) exception('缺少pay_price');
  374. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  375. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  376. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  377. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  378. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  379. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  380. /*仅针对老资金流商户使用
  381. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  382. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  383. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  384. try {
  385. $res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  386. if ($res->return_code == 'FAIL') exception('退款失败:' . $res->return_msg);
  387. if (isset($res->err_code)) exception('退款失败:' . $res->err_code_des);
  388. } catch (\Exception $e) {
  389. exception($e->getMessage());
  390. }
  391. return true;
  392. }
  393. /**
  394. * 微信支付成功回调接口
  395. */
  396. public static function handleNotify()
  397. {
  398. self::paymentService()->handleNotify(function ($notify, $successful) {
  399. if ($successful && isset($notify->out_trade_no)) {
  400. if (($count = strpos($notify->out_trade_no, '_')) !== false) {
  401. $notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
  402. }
  403. WechatMessage::setOnceMessage($notify, $notify->openid, 'payment_success', $notify->out_trade_no);
  404. return HookService::listen('wechat_pay_success', $notify, null, true, PaymentBehavior::class);
  405. }
  406. });
  407. }
  408. /**
  409. * jsSdk
  410. * @return \EasyWeChat\Js\Js
  411. */
  412. public static function jsService()
  413. {
  414. return self::application()->js;
  415. }
  416. public static function jsSdk($url = '')
  417. {
  418. $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'];
  419. $jsService = self::jsService();
  420. if ($url) $jsService->setUrl($url);
  421. try {
  422. return $jsService->config($apiList);
  423. } catch (\Exception $e) {
  424. return '{}';
  425. }
  426. }
  427. /**
  428. * 回复文本消息
  429. * @param string $content 文本内容
  430. * @return Text
  431. */
  432. public static function textMessage($content)
  433. {
  434. return new Text(compact('content'));
  435. }
  436. /**
  437. * 回复图片消息
  438. * @param string $media_id 媒体资源 ID
  439. * @return Image
  440. */
  441. public static function imageMessage($media_id)
  442. {
  443. return new Image(compact('media_id'));
  444. }
  445. /**
  446. * 回复视频消息
  447. * @param string $media_id 媒体资源 ID
  448. * @param string $title 标题
  449. * @param string $description 描述
  450. * @param null $thumb_media_id 封面资源 ID
  451. * @return Video
  452. */
  453. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  454. {
  455. return new Video(compact('media_id', 'title', 'description', 'thumb_media_id'));
  456. }
  457. /**
  458. * 回复声音消息
  459. * @param string $media_id 媒体资源 ID
  460. * @return Voice
  461. */
  462. public static function voiceMessage($media_id)
  463. {
  464. return new Voice(compact('media_id'));
  465. }
  466. /**
  467. * 回复图文消息
  468. * @param string|array $title 标题
  469. * @param string $description 描述
  470. * @param string $url URL
  471. * @param string $image 图片链接
  472. */
  473. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  474. {
  475. if (is_array($title)) {
  476. if (isset($title[0]) && is_array($title[0])) {
  477. $newsList = [];
  478. foreach ($title as $news) {
  479. $newsList[] = self::newsMessage($news);
  480. }
  481. return $newsList;
  482. } else {
  483. $data = $title;
  484. }
  485. } else {
  486. $data = compact('title', 'description', 'url', 'image');
  487. }
  488. return new News($data);
  489. }
  490. /**
  491. * 回复文章消息
  492. * @param string|array $title 标题
  493. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  494. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  495. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  496. * @param string $author 作者
  497. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  498. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  499. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  500. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  501. * @return Article
  502. */
  503. 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)
  504. {
  505. $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');
  506. return new Article($data);
  507. }
  508. /**
  509. * 回复素材消息
  510. * @param string $type [mpnews、 mpvideo、voice、image]
  511. * @param string $media_id 素材 ID
  512. * @return Material
  513. */
  514. public static function materialMessage($type, $media_id)
  515. {
  516. return new Material($type, $media_id);
  517. }
  518. /**
  519. * 作为客服消息发送
  520. * @param $to
  521. * @param $message
  522. * @return bool
  523. */
  524. public static function staffTo($to, $message)
  525. {
  526. $staff = self::staffService();
  527. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  528. $res = $staff->to($to)->send();
  529. HookService::afterListen('wechat_staff_to', compact('to', 'message'), $res);
  530. return $res;
  531. }
  532. /**
  533. * 获得用户信息
  534. * @param array|string $openid
  535. * @return \EasyWeChat\Support\Collection
  536. */
  537. public static function getUserInfo($openid)
  538. {
  539. $userService = self::userService();
  540. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  541. if (is_array($openid)) {
  542. foreach ($userInfo as $key => &$item) {
  543. unset($item['nickname'], $item['headimgurl']);
  544. }
  545. } else {
  546. unset($userInfo['nickname'], $userInfo['headimgurl']);
  547. }
  548. return $userInfo;
  549. }
  550. }