WechatService.php 23 KB

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