WechatService.php 23 KB

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