WechatService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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 crmeb\services;
  12. use app\common\repositories\store\product\ProductAssistSetRepository;
  13. use app\common\repositories\store\product\ProductGroupBuyingRepository;
  14. use app\common\repositories\store\product\ProductGroupRepository;
  15. use app\common\repositories\store\product\ProductPresellRepository;
  16. use app\common\repositories\store\product\ProductRepository;
  17. use app\common\repositories\system\config\ConfigValueRepository;
  18. use app\common\repositories\system\merchant\MerchantRepository;
  19. use app\common\repositories\wechat\WechatQrcodeRepository;
  20. use app\common\repositories\wechat\WechatReplyRepository;
  21. use app\common\repositories\wechat\WechatUserRepository;
  22. use crmeb\exceptions\WechatException;
  23. use EasyWeChat\Core\Exceptions\FaultException;
  24. use EasyWeChat\Core\Exceptions\InvalidArgumentException;
  25. use EasyWeChat\Core\Exceptions\RuntimeException;
  26. use EasyWeChat\Foundation\Application;
  27. use EasyWeChat\Message\Article;
  28. use EasyWeChat\Message\Image;
  29. use EasyWeChat\Message\Material;
  30. use EasyWeChat\Message\News;
  31. use EasyWeChat\Message\Text;
  32. use EasyWeChat\Message\Video;
  33. use EasyWeChat\Message\Voice;
  34. use EasyWeChat\Payment\Order;
  35. use EasyWeChat\Server\BadRequestException;
  36. use EasyWeChat\Support\Collection;
  37. use Exception;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use think\exception\ValidateException;
  40. use think\facade\Cache;
  41. use think\facade\Log;
  42. use think\facade\Route;
  43. use think\Response;
  44. /**
  45. * Class WechatService
  46. * @package crmeb\services
  47. * @author xaboy
  48. * @day 2020-04-20
  49. */
  50. class WechatService
  51. {
  52. /**
  53. * @var Application
  54. */
  55. protected $application;
  56. protected $config;
  57. /**
  58. * WechatService constructor.
  59. * @param $config
  60. */
  61. public function __construct(array $config)
  62. {
  63. $this->config = $config;
  64. $this->application = new Application($config);
  65. $this->application->register(new \crmeb\services\easywechat\certficates\ServiceProvider());
  66. $this->application->register(new \crmeb\services\easywechat\merchant\ServiceProvider);
  67. $this->application->register(new \crmeb\services\easywechat\combinePay\ServiceProvider);
  68. }
  69. /**
  70. * @return array
  71. * @author xaboy
  72. * @day 2020-04-24
  73. */
  74. public static function getConfig($isApp)
  75. {
  76. /** @var ConfigValueRepository $make */
  77. $make = app()->make(ConfigValueRepository::class);
  78. $wechat = $make->more([
  79. 'wechat_appid', 'wechat_appsecret', 'wechat_token', 'wechat_encodingaeskey', 'wechat_encode', 'wecaht_app_appid', 'wechat_app_appsecret'
  80. ], 0);
  81. if ($isApp ?? request()->isApp()) {
  82. $wechat['wechat_appid'] = trim($wechat['wecaht_app_appid']);
  83. $wechat['wechat_appsecret'] = trim($wechat['wechat_app_appsecret']);
  84. }
  85. $payment = $make->more(['site_url', 'pay_weixin_mchid', 'pay_weixin_client_cert', 'pay_weixin_client_key', 'pay_weixin_key', 'pay_weixin_open',
  86. 'wechat_service_merid', 'wechat_service_key', 'wechat_service_v3key', 'wechat_service_client_cert', 'wechat_service_client_key', 'wechat_service_serial_no'], 0);
  87. $config = [
  88. 'app_id' => trim($wechat['wechat_appid']),
  89. 'secret' => trim($wechat['wechat_appsecret']),
  90. 'token' => trim($wechat['wechat_token']),
  91. 'guzzle' => [
  92. 'timeout' => 10.0, // 超时时间(秒)
  93. 'verify' => false
  94. ],
  95. 'debug' => false,
  96. ];
  97. if ($wechat['wechat_encode'] > 0 && $wechat['wechat_encodingaeskey'])
  98. $config['aes_key'] = trim($wechat['wechat_encodingaeskey']);
  99. if (isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1) {
  100. $config['payment'] = [
  101. 'merchant_id' => trim($payment['pay_weixin_mchid']),
  102. 'key' => trim($payment['pay_weixin_key']),
  103. 'cert_path' => (app()->getRootPath() . 'public' . $payment['pay_weixin_client_cert']),
  104. 'key_path' => (app()->getRootPath() . 'public' . $payment['pay_weixin_client_key']),
  105. 'notify_url' => $payment['site_url'] . Route::buildUrl('wechatNotify')->build(),
  106. 'pay_weixin_client_cert' => $payment['pay_weixin_client_cert'],
  107. 'pay_weixin_client_key' => $payment['pay_weixin_client_key'],
  108. ];
  109. }
  110. $config['service_payment'] = [
  111. 'merchant_id' => trim($payment['wechat_service_merid']),
  112. 'type' => 'wechat',
  113. 'key' => trim($payment['wechat_service_key']),
  114. 'cert_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_cert']),
  115. 'key_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_key']),
  116. 'pay_weixin_client_cert' => $payment['wechat_service_client_cert'],
  117. 'pay_weixin_client_key' => $payment['wechat_service_client_key'],
  118. 'serial_no' => trim($payment['wechat_service_serial_no']),
  119. 'apiv3_key' => trim($payment['wechat_service_v3key']),
  120. ];
  121. return $config;
  122. }
  123. /**
  124. * @return self
  125. * @author xaboy
  126. * @day 2020-04-24
  127. */
  128. public static function create($isApp = null)
  129. {
  130. return new self(self::getConfig($isApp));
  131. }
  132. /**
  133. * @return Application
  134. * @author xaboy
  135. * @day 2020-04-20
  136. */
  137. public function getApplication()
  138. {
  139. return $this->application;
  140. }
  141. /**
  142. * @param \think\Request $request
  143. * @return Response
  144. * @throws BadRequestException
  145. * @throws InvalidArgumentException
  146. * @author xaboy
  147. * @day 2020-04-26
  148. */
  149. public function serve(\think\Request $request)
  150. {
  151. $this->serverRequest($request);
  152. $this->wechatEventHook();
  153. return response($this->application->server->serve()->getContent());
  154. }
  155. protected function serverRequest(\think\Request $request)
  156. {
  157. $this->application->server->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
  158. }
  159. /**
  160. * @throws InvalidArgumentException
  161. * @author xaboy
  162. * @day 2020-04-20
  163. */
  164. public function wechatEventHook()
  165. {
  166. $this->application->server->setMessageHandler(function ($message) {
  167. $openId = $message->FromUserName;
  168. $message->EventKey = str_replace('qrscene_','',$message->EventKey);
  169. $userInfo = $this->getUserInfo($openId);
  170. /** @var WechatUserRepository $wechatUserRepository */
  171. $wechatUserRepository = app()->make(WechatUserRepository::class);
  172. $users = $wechatUserRepository->syncUser($openId, $userInfo, true);
  173. $scanLogin = function () use ($message, $users) {
  174. $ticket = $message->EventKey;
  175. if (strpos($ticket, '_sys_scan_login.') === 0) {
  176. $key = str_replace('_sys_scan_login.', '', $ticket);
  177. Cache::set('_scan_login' . $key, $users[1]['uid']);
  178. }
  179. };
  180. $response = null;
  181. /** @var WechatReplyRepository $make * */
  182. $make = app()->make(WechatReplyRepository::class);
  183. event('WechatMessage', $message);
  184. switch ($message->MsgType) {
  185. case 'event':
  186. switch (strtolower($message->Event)) {
  187. case 'subscribe':
  188. $scanLogin();
  189. $response = $this->qrKeyByMessage($message->EventKey) ?: $make->reply('subscribe');
  190. if (isset($message->EventKey) && $message->EventKey) {
  191. /** @var WechatQrcodeRepository $qr */
  192. $qr = app()->make(WechatQrcodeRepository::class);
  193. if ($qrInfo = $qr->ticketByQrcode($message->Ticket)) {
  194. $qrInfo->incTicket();
  195. if (strtolower($qrInfo['third_type']) == 'spread' && $users) {
  196. $spreadUid = $qrInfo['third_id'];
  197. if ($users[1]['uid'] == $spreadUid)
  198. return '自己不能推荐自己';
  199. else if ($users[1]['spread_uid'])
  200. return '已有推荐人!';
  201. try {
  202. $users[1]->setSpread($spreadUid);
  203. } catch (Exception $e) {
  204. return '绑定推荐人失败';
  205. }
  206. }
  207. }
  208. }
  209. event('WechatEventSubscribe', $message);
  210. break;
  211. case 'unsubscribe':
  212. $wechatUserRepository->unsubscribe($openId);
  213. event('WechatEventUnsubscribe', $message);
  214. break;
  215. case 'scan':
  216. $scanLogin();
  217. $response = $this->qrKeyByMessage($message->EventKey) ?: $make->reply('subscribe');
  218. /** @var WechatQrcodeRepository $qr */
  219. $qr = app()->make(WechatQrcodeRepository::class);
  220. if ($message->EventKey && ($qrInfo = $qr->ticketByQrcode($message->Ticket))) {
  221. $qrInfo->incTicket();
  222. if (strtolower($qrInfo['third_type']) == 'spread' && $users) {
  223. $spreadUid = $qrInfo['third_id'];
  224. if ($users[1]['uid'] == $spreadUid)
  225. return '自己不能推荐自己';
  226. else if ($users[1]['spread_uid'])
  227. return '已有推荐人!';
  228. try {
  229. $users[1]->setSpread($spreadUid);
  230. } catch (Exception $e) {
  231. return '绑定推荐人失败';
  232. }
  233. }
  234. }
  235. event('WechatEventScan', $message);
  236. break;
  237. case 'location':
  238. event('wechatEventLocation', $message);
  239. break;
  240. case 'click':
  241. $response = $make->reply($message->EventKey);
  242. break;
  243. case 'view':
  244. event('wechatEventView', $message);
  245. break;
  246. }
  247. break;
  248. case 'text':
  249. $response = $make->reply($message->Content);
  250. event('wechatMessageText', $message);
  251. break;
  252. case 'image':
  253. event('wechatMessageImage', $message);
  254. break;
  255. case 'voice':
  256. event('wechatMessageVoice', $message);
  257. break;
  258. case 'video':
  259. event('wechatMessageVideo', $message);
  260. break;
  261. case 'location':
  262. event('wechatMessageLocation', $message);
  263. break;
  264. case 'link':
  265. event('wechatMessageLink', $message);
  266. break;
  267. // ... 其它消息
  268. default:
  269. event('WechatMessageOther', $message);
  270. break;
  271. }
  272. return $response ?? false;
  273. });
  274. }
  275. /**
  276. * @param $value
  277. * @return Collection
  278. * @author xaboy
  279. * @day 2020-04-20
  280. */
  281. public function qrcodeForever($value)
  282. {
  283. return $this->application->qrcode->forever($value);
  284. }
  285. /**
  286. * @param $value
  287. * @param int $expireSeconds
  288. * @return Collection
  289. * @author xaboy
  290. * @day 2020-04-20
  291. */
  292. public function qrcodeTemp($value, $expireSeconds = 2592000)
  293. {
  294. return $this->application->qrcode->temporary($value, $expireSeconds);
  295. }
  296. /**
  297. * @param string $openid
  298. * @param string $templateId
  299. * @param array $data
  300. * @param null $url
  301. * @param null $defaultColor
  302. * @return mixed
  303. * @author xaboy
  304. * @day 2020-04-20
  305. */
  306. public function sendTemplate(string $openid, string $templateId, array $data, $url = null, $defaultColor = null)
  307. {
  308. $notice = $this->application->notice->to($openid)->template($templateId)->andData($data);
  309. if ($url !== null) $notice->url($url);
  310. if ($defaultColor !== null) $notice->defaultColor($defaultColor);
  311. return $notice->send();
  312. }
  313. /**
  314. * @param $openid
  315. * @param $out_trade_no
  316. * @param $total_fee
  317. * @param $attach
  318. * @param $body
  319. * @param string $detail
  320. * @param string $trade_type
  321. * @param array $options
  322. * @return Order
  323. * @author xaboy
  324. * @day 2020-04-20
  325. */
  326. protected function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  327. {
  328. $total_fee = bcmul($total_fee, 100, 0);
  329. $order = array_merge(compact('out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  330. if (!is_null($openid)) $order['openid'] = $openid;
  331. if ($order['detail'] == '') unset($order['detail']);
  332. $order['spbill_create_ip'] = \request()->ip();
  333. return new Order($order);
  334. }
  335. /**
  336. * @param $openid
  337. * @param $out_trade_no
  338. * @param $total_fee
  339. * @param $attach
  340. * @param $body
  341. * @param string $detail
  342. * @param string $trade_type
  343. * @param array $options
  344. * @return Collection
  345. * @author xaboy
  346. * @day 2020-04-20
  347. */
  348. public function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  349. {
  350. $order = $this->paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  351. $result = $this->application->payment->prepare($order);
  352. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  353. return $result;
  354. } else {
  355. if ($result->return_code == 'FAIL') {
  356. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  357. } else if (isset($result->err_code)) {
  358. throw new WechatException('微信支付错误返回:' . $result->err_code_des);
  359. } else {
  360. throw new WechatException('没有获取微信支付的预支付ID,请重新发起支付!');
  361. }
  362. }
  363. }
  364. /**
  365. * @param $openid
  366. * @param $out_trade_no
  367. * @param $total_fee
  368. * @param $attach
  369. * @param $body
  370. * @param string $detail
  371. * @param string $trade_type
  372. * @param array $options
  373. * @return array|string
  374. * @author xaboy
  375. * @day 2020-04-20
  376. */
  377. public function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  378. {
  379. $paymentPrepare = $this->paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  380. return $trade_type === 'APP'
  381. ? $this->application->payment->configForAppPayment($paymentPrepare->prepay_id)
  382. : $this->application->payment->configForJSSDKPayment($paymentPrepare->prepay_id);
  383. }
  384. /**
  385. * @param $orderNo
  386. * @param $refundNo
  387. * @param $totalFee
  388. * @param null $refundFee
  389. * @param null $opUserId
  390. * @param string $refundReason
  391. * @param string $type
  392. * @param string $refundAccount
  393. * @return Collection
  394. * @author xaboy
  395. * @day 2020-04-20
  396. */
  397. public function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  398. {
  399. if (empty($this->config['payment']['pay_weixin_client_cert']) || empty($this->config['payment']['pay_weixin_client_key'])) {
  400. throw new \Exception('请配置微信支付证书');
  401. }
  402. $totalFee = floatval($totalFee);
  403. $refundFee = floatval($refundFee);
  404. return $this->application->payment->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  405. }
  406. /**
  407. * @param $orderNo
  408. * @param array $opt
  409. * @author xaboy
  410. * @day 2020-04-20
  411. */
  412. public function payOrderRefund($orderNo, array $opt)
  413. {
  414. if (!isset($opt['pay_price'])) throw new WechatException('缺少pay_price');
  415. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  416. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  417. $refundReason = isset($opt['desc']) ? $opt['desc'] : '';
  418. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  419. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  420. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  421. /*仅针对老资金流商户使用
  422. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  423. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
  424. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  425. try {
  426. $res = ($this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  427. if ($res->return_code == 'FAIL') throw new WechatException('退款失败:' . $res->return_msg);
  428. if (isset($res->err_code)) throw new WechatException('退款失败:' . $res->err_code_des);
  429. } catch (Exception $e) {
  430. throw new WechatException($e->getMessage());
  431. }
  432. }
  433. /**
  434. * array (
  435. * 'appid' => '****',
  436. * 'attach' => 'user_recharge',
  437. * 'bank_type' => 'COMM_CREDIT',
  438. * 'cash_fee' => '1',
  439. * 'fee_type' => 'CNY',
  440. * 'is_subscribe' => 'Y',
  441. * 'mch_id' => ''*****'',
  442. * 'nonce_str' => '5ee9dac1bc302',
  443. * 'openid' => '*****',
  444. * 'out_trade_no' => ''*****'',
  445. * 'result_code' => 'SUCCESS',
  446. * 'return_code' => 'SUCCESS',
  447. * 'sign' => '51'*****'',
  448. * 'time_end' => '20200617165651',
  449. * 'total_fee' => '1',
  450. * 'trade_type' => 'JSAPI',
  451. * 'transaction_id' => ''*****'',
  452. * )
  453. *
  454. * @throws FaultException
  455. * @author xaboy
  456. * @day 2020-04-20
  457. */
  458. public function handleNotify()
  459. {
  460. $this->application->payment = new PaymentService($this->application->merchant);
  461. //TODO 微信支付
  462. return $this->application->payment->handleNotify(function ($notify, $successful) {
  463. Log::info('微信支付成功回调' . var_export($notify, 1));
  464. if (!$successful) return false;
  465. try {
  466. event('pay_success_' . $notify['attach'], ['order_sn' => $notify['out_trade_no'], 'data' => $notify, 'is_combine' => 0]);
  467. } catch (\Exception $e) {
  468. Log::info('微信支付回调失败:' . $e->getMessage());
  469. return false;
  470. }
  471. return true;
  472. });
  473. }
  474. public function handleCombinePayNotify($type)
  475. {
  476. $this->application->combinePay->handleNotify(function ($notify, $successful) use ($type) {
  477. Log::info('微信支付成功回调' . var_export($notify, 1));
  478. if (!$successful) return false;
  479. try {
  480. event('pay_success_' . $type, ['order_sn' => $notify['combine_out_trade_no'], 'data' => $notify, 'is_combine' => 1]);
  481. } catch (\Exception $e) {
  482. Log::info('微信支付回调失败:' . $e->getMessage());
  483. return false;
  484. }
  485. return true;
  486. });
  487. }
  488. /**
  489. * @param string $url
  490. * @return array|string
  491. * @author xaboy
  492. * @day 2020-04-20
  493. */
  494. public function jsSdk($url)
  495. {
  496. $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'];
  497. $jsService = $this->application->js;
  498. $jsService->setUrl($url);
  499. try {
  500. return $jsService->config($apiList, false, false, false);
  501. } catch (Exception $e) {
  502. Log::info('微信参数获取失败' . $e->getMessage());
  503. return [];
  504. }
  505. }
  506. /**
  507. * 回复文本消息
  508. * @param string $content 文本内容
  509. * @return Text
  510. * @author xaboy
  511. * @day 2020-04-20
  512. */
  513. public static function textMessage($content)
  514. {
  515. return new Text(compact('content'));
  516. }
  517. /**
  518. * 回复图片消息
  519. * @param string $media_id 媒体资源 ID
  520. * @return Image
  521. * @author xaboy
  522. * @day 2020-04-20
  523. */
  524. public static function imageMessage($media_id)
  525. {
  526. return new Image(compact('media_id'));
  527. }
  528. /**
  529. * 回复视频消息
  530. * @param string $media_id 媒体资源 ID
  531. * @param string $title 标题
  532. * @param string $description 描述
  533. * @param null $thumb_media_id 封面资源 ID
  534. * @return Video
  535. * @author xaboy
  536. * @day 2020-04-20
  537. */
  538. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  539. {
  540. return new Video(compact('media_id', 'title', 'description', 'thumb_media_id'));
  541. }
  542. /**
  543. * 回复声音消息
  544. * @param string $media_id 媒体资源 ID
  545. * @return Voice
  546. * @author xaboy
  547. * @day 2020-04-20
  548. */
  549. public static function voiceMessage($media_id)
  550. {
  551. return new Voice(compact('media_id'));
  552. }
  553. /**
  554. * 回复图文消息
  555. * @param string|array $title 标题
  556. * @param string $description 描述
  557. * @param string $url URL
  558. * @param string $image 图片链接
  559. * @return News|array<News>
  560. * @author xaboy
  561. * @day 2020-04-20
  562. */
  563. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  564. {
  565. if (is_array($title)) {
  566. if (isset($title[0]) && is_array($title[0])) {
  567. $newsList = [];
  568. foreach ($title as $news) {
  569. $newsList[] = self::newsMessage($news);
  570. }
  571. return $newsList;
  572. } else {
  573. $data = $title;
  574. }
  575. } else {
  576. $data = compact('title', 'description', 'url', 'image');
  577. }
  578. return new News($data);
  579. }
  580. /**
  581. * 回复文章消息
  582. * @param string|array $title 标题
  583. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  584. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  585. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  586. * @param string $author 作者
  587. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  588. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  589. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  590. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  591. * @return Article
  592. * @author xaboy
  593. * @day 2020-04-20
  594. */
  595. 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)
  596. {
  597. $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');
  598. return new Article($data);
  599. }
  600. /**
  601. * 回复素材消息
  602. * @param string $type [mpnews、 mpvideo、voice、image]
  603. * @param string $media_id 素材 ID
  604. * @return Material
  605. * @author xaboy
  606. * @day 2020-04-20
  607. */
  608. public static function materialMessage($type, $media_id)
  609. {
  610. return new Material($type, $media_id);
  611. }
  612. /**
  613. * @param $to
  614. * @param $message
  615. * @return bool
  616. * @throws InvalidArgumentException
  617. * @throws RuntimeException
  618. * @author xaboy
  619. * @day 2020-04-20
  620. */
  621. public function staffTo($to, $message)
  622. {
  623. $staff = $this->application->staff;
  624. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  625. $res = $staff->to($to)->send();
  626. return $res;
  627. }
  628. /**
  629. * @param $openid
  630. * @return array
  631. * @author xaboy
  632. * @day 2020-04-20
  633. */
  634. public function getUserInfo($openid)
  635. {
  636. $userService = $this->application->user;
  637. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  638. return $userInfo->toArray();
  639. }
  640. /**
  641. * 模板消息接口
  642. * @return \EasyWeChat\Notice\Notice
  643. */
  644. public function noticeService()
  645. {
  646. return $this->application->notice;
  647. }
  648. /**
  649. * 微信二维码生成接口
  650. * @return \EasyWeChat\QRCode\QRCode
  651. */
  652. public function qrcodeService()
  653. {
  654. return $this->application->qrcode;
  655. }
  656. public function merchantPay($data)
  657. {
  658. $ret = [
  659. 'partner_trade_no' => $data['sn'], //随机字符串作为订单号,跟红包和支付一个概念。
  660. 'openid' => $data['openid'], //收款人的openid
  661. 'check_name' => 'NO_CHECK', //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
  662. //'re_user_name'=>'张三', //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
  663. 'amount' => $data['price'] * 100, //单位为分
  664. 'desc' => '企业付款',
  665. 'spbill_create_ip' => request()->ip(), //发起交易的IP地址
  666. ];
  667. $result = $this->application->merchant_pay->send($ret);
  668. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  669. return $result;
  670. } else {
  671. if ($result->return_code == 'FAIL') {
  672. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  673. } else if (isset($result->err_code)) {
  674. throw new WechatException('微信支付错误返回:' . $result->err_code_des);
  675. } else {
  676. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  677. }
  678. }
  679. }
  680. /**
  681. * TODO 分账商户
  682. * @return mixed
  683. * @author Qinii
  684. * @day 6/24/21
  685. */
  686. public function applyments()
  687. {
  688. return $this->application->sub_merchant;
  689. }
  690. /**
  691. * TODO 上传图片
  692. * @param array $filed
  693. * @return mixed
  694. * @author Qinii
  695. * @day 6/21/21
  696. */
  697. public function uploadImages(array $filed)
  698. {
  699. foreach ($filed as $file) {
  700. $item = $this->application->sub_merchant->upload($file['path'], $file['name']);
  701. $data[] = [
  702. 'dir' => $file['dir'],
  703. 'media_id' => $item['media_id'],
  704. ];
  705. }
  706. return $data;
  707. }
  708. public function qrKeyByMessage($key)
  709. {
  710. if (strpos($key, '_scan_url_') === 0) {
  711. $key = str_replace('_scan_url_', '', $key);
  712. $data = explode('_', $key);
  713. $siteUrl = rtrim(systemConfig('site_url'), '/');
  714. $make = app()->make(ProductRepository::class);
  715. if ($data[0] === 'home') {
  716. $share = systemConfig(['share_title', 'share_info', 'share_pic']);
  717. $share['url'] = $siteUrl . '?spid=' . $data[1];
  718. } else if ($data[0] === 'mer') {
  719. $ret = app()->make(MerchantRepository::class)->get($data[1]);
  720. if (!$ret) return;
  721. $share = [
  722. 'share_title' => $ret['mer_name'],
  723. 'share_info' => $ret['mer_info'],
  724. 'share_pic' => $ret['mer_avatar'],
  725. 'url' => $siteUrl . '/pages/store/home/index?id=' . $data[1],
  726. ];
  727. } else if ($data[0] === 'p0') {
  728. $ret = $make->get($data[1]);
  729. if (!$ret) return;
  730. $share = [
  731. 'share_title' => $ret['store_name'],
  732. 'share_info' => $ret['store_info'],
  733. 'share_pic' => $ret['image'],
  734. 'url' => $siteUrl . '/pages/goods_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  735. ];
  736. } else if ($data[0] === 'p1') {
  737. $ret = $make->get($data[1]);
  738. if (!$ret) return;
  739. $share = [
  740. 'share_title' => $ret['store_name'],
  741. 'share_info' => $ret['store_info'],
  742. 'share_pic' => $ret['image'],
  743. 'url' => $siteUrl . '/pages/activity/goods_seckill_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  744. ];
  745. } else if ($data[0] === 'p2') {
  746. $ret = app()->make(ProductPresellRepository::class)->search(['product_presell_id' => $data[1]])->find();
  747. $res = $make->get($ret['product_id']);
  748. if (!$ret) return;
  749. $share = [
  750. 'share_title' => $ret['store_name'],
  751. 'share_info' => $ret['store_info'],
  752. 'share_pic' => $res['image'],
  753. 'url' => $siteUrl . '/pages/activity/presell_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  754. ];
  755. } else if ($data[0] === 'p3') {
  756. $ret = app()->make(ProductAssistSetRepository::class)->getSearch(['product_assist_set_id' => $data[1]])->find();
  757. $res = $make->get($ret['product_id']);
  758. if (!$ret) return;
  759. $share = [
  760. 'share_title' => $res['store_name'],
  761. 'share_info' => $res['store_info'],
  762. 'share_pic' => $res['image'],
  763. 'url' => $siteUrl . '/pages/activity/assist_detail/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  764. ];
  765. } else if ($data[0] === 'p4') {
  766. $ret = app()->make(ProductGroupRepository::class)->get($data[1]);
  767. $res = $make->get($ret['product_id']);
  768. if (!$ret) return;
  769. $share = [
  770. 'share_title' => $res['store_name'],
  771. 'share_info' => $res['store_info'],
  772. 'share_pic' => $res['image'],
  773. 'url' => $siteUrl . '/pages/activity/combination_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  774. ];
  775. } else if ($data[0] === 'p40') {
  776. $res = app()->make(ProductGroupBuyingRepository::class)->getSearch(['group_buying_id' => $data[1]])->find();
  777. $ret = $make->get($res->productGroup['product_id']);
  778. if (!$ret) return;
  779. $share = [
  780. 'share_title' => $ret['store_name'],
  781. 'share_info' => $ret['store_info'],
  782. 'share_pic' => $ret['image'],
  783. 'url' => $siteUrl . '/pages/activity/combination_status/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  784. ];
  785. } else {
  786. return;
  787. }
  788. return self::newsMessage($share['share_title'], $share['share_info'], $share['url'], $share['share_pic']);
  789. }
  790. }
  791. /**
  792. * @return easywechat\combinePay\Client
  793. */
  794. public function combinePay()
  795. {
  796. return $this->application->combinePay;
  797. }
  798. }