WechatService.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2024 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\order\StoreOrderRepository;
  13. use app\common\repositories\store\product\ProductAssistSetRepository;
  14. use app\common\repositories\store\product\ProductGroupBuyingRepository;
  15. use app\common\repositories\store\product\ProductGroupRepository;
  16. use app\common\repositories\store\product\ProductPresellRepository;
  17. use app\common\repositories\store\product\ProductRepository;
  18. use app\common\repositories\store\StoreActivityRepository;
  19. use app\common\repositories\system\config\ConfigValueRepository;
  20. use app\common\repositories\system\merchant\MerchantRepository;
  21. use app\common\repositories\wechat\WechatQrcodeRepository;
  22. use app\common\repositories\wechat\WechatReplyRepository;
  23. use app\common\repositories\wechat\WechatUserRepository;
  24. use crmeb\exceptions\WechatException;
  25. use crmeb\utils\ApiErrorCode;
  26. use EasyWeChat\Core\Exceptions\FaultException;
  27. use EasyWeChat\Core\Exceptions\InvalidArgumentException;
  28. use EasyWeChat\Core\Exceptions\RuntimeException;
  29. use EasyWeChat\Foundation\Application;
  30. use EasyWeChat\Message\Article;
  31. use EasyWeChat\Message\Image;
  32. use EasyWeChat\Message\Material;
  33. use EasyWeChat\Message\News;
  34. use EasyWeChat\Message\Text;
  35. use EasyWeChat\Message\Video;
  36. use EasyWeChat\Message\Voice;
  37. use EasyWeChat\Payment\Order;
  38. use EasyWeChat\Server\BadRequestException;
  39. use EasyWeChat\Support\Collection;
  40. use Exception;
  41. use Symfony\Component\HttpFoundation\Request;
  42. use think\exception\ValidateException;
  43. use think\facade\Cache;
  44. use think\facade\Event;
  45. use think\facade\Log;
  46. use think\facade\Route;
  47. use think\Response;
  48. /**
  49. * Class WechatService
  50. * @package crmeb\services
  51. * @author xaboy
  52. * @day 2020-04-20
  53. */
  54. class WechatService
  55. {
  56. /**
  57. * @var Application
  58. */
  59. protected $application;
  60. protected $config;
  61. /**
  62. * WechatService constructor.
  63. * @param $config
  64. */
  65. public function __construct(array $config)
  66. {
  67. $this->config = $config;
  68. $this->application = new Application($config);
  69. $this->application->register(new \crmeb\services\easywechat\certficates\ServiceProvider());
  70. $this->application->register(new \crmeb\services\easywechat\merchant\ServiceProvider);
  71. $this->application->register(new \crmeb\services\easywechat\combinePay\ServiceProvider);
  72. $this->application->register(new \crmeb\services\easywechat\pay\ServiceProvider);
  73. $this->application->register(new \crmeb\services\easywechat\batches\ServiceProvider);
  74. $this->application->register(new \crmeb\services\easywechat\wechatTemplate\ServiceProvider);
  75. }
  76. /**
  77. * @return array
  78. * @author xaboy
  79. * @day 2020-04-24
  80. */
  81. public static function getConfig($isApp)
  82. {
  83. /** @var ConfigValueRepository $make */
  84. $make = app()->make(ConfigValueRepository::class);
  85. $wechat = $make->more([
  86. 'wechat_appid', 'wechat_appsecret', 'wechat_token', 'wechat_encodingaeskey', 'wechat_encode', 'wecaht_app_appid', 'wechat_app_appsecret'
  87. ], 0);
  88. if ($isApp ?? request()->isApp()) {
  89. $wechat['wechat_appid'] = trim($wechat['wecaht_app_appid']);
  90. $wechat['wechat_appsecret'] = trim($wechat['wechat_app_appsecret']);
  91. }
  92. $payment = $make->more(['site_url', 'pay_weixin_mchid', 'pay_weixin_client_cert', 'pay_weixin_client_key', 'pay_weixin_key', 'pay_weixin_v3_key', 'pay_weixin_open','pay_wechat_serial_no_v3', 'wechat_service_merid', 'wechat_service_key', 'wechat_service_v3key', 'wechat_service_client_cert', 'wechat_service_client_key', 'wechat_service_serial_no','pay_wechat_type','pay_weixin_public_id','pay_weixin_public_key'], 0);
  93. $config = [
  94. 'app_id' => trim($wechat['wechat_appid']),
  95. 'secret' => trim($wechat['wechat_appsecret']),
  96. 'token' => trim($wechat['wechat_token']),
  97. 'routine_appId' => systemConfig('routine_appId'),
  98. 'guzzle' => [
  99. 'timeout' => 10.0, // 超时时间(秒)
  100. 'verify' => false
  101. ],
  102. 'debug' => false,
  103. ];
  104. if ($wechat['wechat_encode'] > 0 && $wechat['wechat_encodingaeskey'])
  105. $config['aes_key'] = trim($wechat['wechat_encodingaeskey']);
  106. if (isset($payment['pay_weixin_open']) && $payment['pay_weixin_open'] == 1) {
  107. $config['payment'] = [
  108. 'merchant_id' => trim($payment['pay_weixin_mchid']),
  109. 'key' => trim($payment['pay_weixin_key']),
  110. 'apiv3_key' => trim($payment['pay_weixin_v3_key']),
  111. 'serial_no' => trim($payment['pay_wechat_serial_no_v3']),
  112. 'cert_path' => (app()->getRootPath() . 'public' . $payment['pay_weixin_client_cert']),
  113. 'key_path' => (app()->getRootPath() . 'public' . $payment['pay_weixin_client_key']),
  114. 'notify_url' => $payment['site_url'] . Route::buildUrl('wechatNotify')->build(),
  115. 'pay_weixin_client_cert' => $payment['pay_weixin_client_cert'],
  116. 'pay_weixin_client_key' => $payment['pay_weixin_client_key'],
  117. 'pay_weixin_public_key' => $payment['pay_weixin_public_key'],
  118. 'pay_weixin_public_id' => $payment['pay_weixin_public_id'],
  119. ];
  120. }
  121. $config['is_v3'] = $payment['pay_wechat_type'] ? true : false;
  122. $config['service_payment'] = [
  123. 'merchant_id' => trim($payment['wechat_service_merid']),
  124. 'type' => 'wechat',
  125. 'key' => trim($payment['wechat_service_key']),
  126. 'cert_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_cert']),
  127. 'key_path' => (app()->getRootPath() . 'public' . $payment['wechat_service_client_key']),
  128. 'pay_weixin_client_cert' => $payment['wechat_service_client_cert'],
  129. 'pay_weixin_client_key' => $payment['wechat_service_client_key'],
  130. 'serial_no' => trim($payment['wechat_service_serial_no']),
  131. 'apiv3_key' => trim($payment['wechat_service_v3key']),
  132. 'pay_weixin_public_key' => trim($payment['pay_weixin_public_key']),
  133. 'pay_weixin_public_id' => trim($payment['pay_weixin_public_id']),
  134. ];
  135. return $config;
  136. }
  137. /**
  138. * @return self
  139. * @author xaboy
  140. * @day 2020-04-24
  141. */
  142. public static function create($isApp = null)
  143. {
  144. // $config = self::getConfig($isApp);
  145. // @file_put_contents('quanju3.txt',json_encode($config)."-getConfig\r\n",8);
  146. return new self(self::getConfig($isApp));
  147. }
  148. public function isV3()
  149. {
  150. return $this->config['is_v3'] ?? false;
  151. }
  152. public function v3Pay()
  153. {
  154. return $this->application->v3Pay;
  155. }
  156. /**
  157. * @return Application
  158. * @author xaboy
  159. * @day 2020-04-20
  160. */
  161. public function getApplication()
  162. {
  163. return $this->application;
  164. }
  165. /**
  166. * @param \think\Request $request
  167. * @return Response
  168. * @throws BadRequestException
  169. * @throws InvalidArgumentException
  170. * @author xaboy
  171. * @day 2020-04-26
  172. */
  173. public function serve(\think\Request $request)
  174. {
  175. @file_put_contents('quanju3.txt',json_encode($request)."-是走这里吗\r\n",8);
  176. $res1=$this->serverRequest($request);
  177. @file_put_contents('quanju3.txt',json_encode($res1)."-two\r\n",8);
  178. $res2=$this->wechatEventHook();
  179. @file_put_contents('quanju3.txt',$res2."-hair\r\n",8);
  180. $air=response($this->application->server->serve()->getContent());
  181. @file_put_contents('quanju3.txt',json_encode($air)."-测试hair\r\n",8);
  182. return response($this->application->server->serve()->getContent());
  183. }
  184. protected function serverRequest(\think\Request $request)
  185. {
  186. $this->application->server->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
  187. }
  188. /**
  189. * @throws InvalidArgumentException
  190. * @author xaboy
  191. * @day 2020-04-20
  192. */
  193. public function wechatEventHook()
  194. {
  195. $this->application->server->setMessageHandler(function ($message) {
  196. $openId = $message->FromUserName;
  197. $message->EventKey = str_replace('qrscene_', '', $message->EventKey);
  198. $userInfo = $this->getUserInfo($openId);
  199. $wechatUserRepository = app()->make(WechatUserRepository::class);
  200. $users = $wechatUserRepository->syncUser($openId, $userInfo, true);
  201. $scanLogin = function () use ($message, $users) {
  202. $ticket = $message->EventKey;
  203. if (strpos($ticket, '_sys_scan_login.') === 0) {
  204. $key = str_replace('_sys_scan_login.', '', $ticket);
  205. if(Cache::has('_scan_login' . $key) && ($users[1]['uid'] ?? 0)){
  206. Cache::set('_scan_login' . $key, $users[1]['uid'] );
  207. }
  208. }
  209. };
  210. $response = null;
  211. /** @var WechatReplyRepository $make * */
  212. $make = app()->make(WechatReplyRepository::class);
  213. event('wechat.message', compact('message'));
  214. switch ($message->MsgType) {
  215. case 'event':
  216. event('wechat.event', compact('message'));
  217. switch (strtolower($message->Event)) {
  218. case 'subscribe':
  219. $scanLogin();
  220. $response = $this->qrKeyByMessage($message->EventKey) ?: $make->reply('subscribe');
  221. if (isset($message->EventKey) && $message->EventKey) {
  222. /** @var WechatQrcodeRepository $qr */
  223. $qr = app()->make(WechatQrcodeRepository::class);
  224. if ($qrInfo = $qr->ticketByQrcode($message->Ticket)) {
  225. $qrInfo->incTicket();
  226. if (strtolower($qrInfo['third_type']) == 'spread' && $users) {
  227. $spreadUid = $qrInfo['third_id'];
  228. if ($users[1]['uid'] == $spreadUid)
  229. return '自己不能推荐自己';
  230. else if ($users[1]['spread_uid'])
  231. return '已有推荐人!';
  232. try {
  233. $users[1]->setSpread($spreadUid);
  234. } catch (Exception $e) {
  235. return '绑定推荐人失败';
  236. }
  237. }
  238. }
  239. }
  240. event('wechat.event.subscribe', compact('message'));
  241. break;
  242. case 'unsubscribe':
  243. $wechatUserRepository->unsubscribe($openId);
  244. event('wechat.event.unsubscribe', compact('message'));
  245. break;
  246. case 'scan':
  247. $scanLogin();
  248. $response = $this->qrKeyByMessage($message->EventKey) ?: $make->reply('subscribe');
  249. /** @var WechatQrcodeRepository $qr */
  250. $qr = app()->make(WechatQrcodeRepository::class);
  251. if ($message->EventKey && ($qrInfo = $qr->ticketByQrcode($message->Ticket))) {
  252. $qrInfo->incTicket();
  253. if (strtolower($qrInfo['third_type']) == 'spread' && $users) {
  254. $spreadUid = $qrInfo['third_id'];
  255. if ($users[1]['uid'] == $spreadUid)
  256. return '自己不能推荐自己';
  257. else if ($users[1]['spread_uid'])
  258. return '已有推荐人!';
  259. try {
  260. $users[1]->setSpread($spreadUid);
  261. } catch (Exception $e) {
  262. return '绑定推荐人失败';
  263. }
  264. }
  265. }
  266. event('wechat.event.scan', compact('message'));
  267. break;
  268. case 'location':
  269. event('wechat.event.location', compact('message'));
  270. break;
  271. case 'click':
  272. $response = $make->reply($message->EventKey);
  273. event('wechat.event.click', compact('message'));
  274. break;
  275. case 'view':
  276. event('wechat.event.view', compact('message'));
  277. break;
  278. case 'funds_order_pay':
  279. if (($count = strpos($message['order_info']['trade_no'], '_')) !== false) {
  280. $trade_no = substr($message['order_info']['trade_no'], $count + 1);
  281. } else {
  282. $trade_no = $message['order_info']['trade_no'];
  283. }
  284. $prefix = substr($trade_no, 0, 3);
  285. //处理一下参数
  286. switch ($prefix) {
  287. case StoreOrderRepository::TYPE_SN_ORDER:
  288. $attach = 'order';
  289. break;
  290. case StoreOrderRepository::TYPE_SN_PRESELL:
  291. $attach = 'presell';
  292. break;
  293. case StoreOrderRepository::TYPE_SN_USER_ORDER:
  294. $attach = 'user_order';
  295. break;
  296. case StoreOrderRepository::TYPE_SN_USER_RECHARGE:
  297. $attach = 'user_recharge';
  298. break;
  299. }
  300. event('pay_success_' . $attach, ['order_sn' => $message['order_info']['trade_no'], 'data' => $message, 'is_combine' => 0]);
  301. break;
  302. }
  303. break;
  304. case 'text':
  305. if (preg_match('/^(\/@[1-9]{1}).*\*\//', $message->Content)) {
  306. $command = app()->make(CopyCommand::class)->getMassage($message->Content);
  307. if (empty($command)) {
  308. $response = self::textMessage('无效口令');
  309. } else {
  310. if ($command['type'] == 30) $command['type'] = 3;
  311. $key = '_scan_url_' . $command['type'] . '_' . $command['id'] . '_' . $command['uid'];
  312. $response = $this->qrKeyByMessage($key);
  313. }
  314. } else {
  315. $response = $make->reply($message->Content);
  316. }
  317. event('wechat.message.text', compact('message'));
  318. break;
  319. case 'image':
  320. event('wechat.message.image', compact('message'));
  321. break;
  322. case 'voice':
  323. event('wechat.message.voice', compact('message'));
  324. break;
  325. case 'video':
  326. event('wechat.message.video', compact('message'));
  327. break;
  328. case 'location':
  329. event('wechat.message.location', compact('message'));
  330. break;
  331. case 'link':
  332. event('wechat.message.link', compact('message'));
  333. break;
  334. // ... 其它消息
  335. default:
  336. event('wechat.message.other', compact('message'));
  337. break;
  338. }
  339. return $response ?? false;
  340. });
  341. }
  342. /**
  343. * @param $value
  344. * @return Collection
  345. * @author xaboy
  346. * @day 2020-04-20
  347. */
  348. public function qrcodeForever($value)
  349. {
  350. return $this->application->qrcode->forever($value);
  351. }
  352. /**
  353. * @param $value
  354. * @param int $expireSeconds
  355. * @return Collection
  356. * @author xaboy
  357. * @day 2020-04-20
  358. */
  359. public function qrcodeTemp($value, $expireSeconds = 2592000)
  360. {
  361. return $this->application->qrcode->temporary($value, $expireSeconds);
  362. }
  363. /**
  364. * @param string $openid
  365. * @param string $templateId
  366. * @param array $data
  367. * @param null $url
  368. * @param null $defaultColor
  369. * @return mixed
  370. * @author xaboy
  371. * @day 2020-04-20
  372. */
  373. public function sendTemplate(string $openid, string $templateId, array $data, $url = null, $defaultColor = null, $miniprogram = [])
  374. {
  375. $notice = $this->application->notice->to($openid)->template($templateId)->andData($data);
  376. if ($url !== null) $notice->url($url);
  377. if ($defaultColor !== null) $notice->defaultColor($defaultColor);
  378. return $notice->send($miniprogram);
  379. }
  380. /**
  381. * @param $openid
  382. * @param $out_trade_no
  383. * @param $total_fee
  384. * @param $attach
  385. * @param $body
  386. * @param string $detail
  387. * @param string $trade_type
  388. * @param array $options
  389. * @return Order
  390. * @author xaboy
  391. * @day 2020-04-20
  392. */
  393. protected function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  394. {
  395. $total_fee = bcmul($total_fee, 100, 0);
  396. $order = array_merge(compact('out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
  397. if (!is_null($openid)) $order['openid'] = $openid;
  398. if ($order['detail'] == '') unset($order['detail']);
  399. $order['spbill_create_ip'] = \request()->ip();
  400. $order['time_expire'] = date('YmdHis', strtotime("+14 minute"));
  401. return new Order($order);
  402. }
  403. /**
  404. * @param $openid
  405. * @param $out_trade_no
  406. * @param $total_fee
  407. * @param $attach
  408. * @param $body
  409. * @param string $detail
  410. * @param string $trade_type
  411. * @param array $options
  412. * @return Collection
  413. * @author xaboy
  414. * @day 2020-04-20
  415. */
  416. public function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  417. {
  418. $order = $this->paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  419. if ($this->isV3()) {
  420. if ($trade_type == 'MWEB') $trade_type = 'H5';
  421. $payFunction = 'pay'.ucfirst($trade_type);
  422. return $this->application->v3Pay->{$payFunction}($order);
  423. } else {
  424. $result = $this->application->payment->prepare($order);
  425. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  426. return $result;
  427. } else {
  428. if ($result->return_code == 'FAIL') {
  429. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  430. } else if (isset($result->err_code)) {
  431. throw new WechatException('微信支付错误返回:' . $result->err_code_des);
  432. } else {
  433. throw new WechatException('没有获取微信支付的预支付ID,请重新发起支付!');
  434. }
  435. }
  436. }
  437. }
  438. /**
  439. * 微信扫码枪支付
  440. * 只有v2版本支持
  441. *
  442. * @param $out_trade_no
  443. * @param $total_fee
  444. * @param $attach
  445. * @param $body
  446. * @param $auth_code
  447. * @return void
  448. */
  449. public function payWeixinBarCode($out_trade_no, $total_fee, $attach, $body, $auth_code)
  450. {
  451. $order = $this->paymentOrderBarCode($out_trade_no, $total_fee, $attach, $body, $auth_code);
  452. $result = $this->application->payment->pay($order);
  453. $paid = 0;
  454. if ($result->return_code === 'SUCCESS'&& $result->result_code === 'SUCCESS' && $result->trade_type === 'MICROPAY') {
  455. $paid = 1;
  456. $message = '支付成功';
  457. $transaction_id = $result->transaction_id;
  458. }else{
  459. $message = '支付失败:'.$result->err_code_des ?? $result->return_msg;
  460. }
  461. return [
  462. 'paid' => $paid,
  463. 'message' => $message,
  464. 'transaction_id' => $transaction_id ?? 0,
  465. 'payInfo' => $result
  466. ];
  467. }
  468. /**
  469. * @param $openid
  470. * @param $out_trade_no
  471. * @param $total_fee
  472. * @param $attach
  473. * @param $body
  474. * @param string $detail
  475. * @param string $trade_type
  476. * @param array $options
  477. * @return Order
  478. * @author xaboy
  479. * @day 2020-04-20
  480. */
  481. protected function paymentOrderBarCode($out_trade_no, $total_fee, $attach, $body, $auth_code, $detail = '', $options = [])
  482. {
  483. $total_fee = bcmul($total_fee, 100, 0);
  484. $order = array_merge(compact('out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'auth_code'), $options);
  485. if ($order['detail'] == '') unset($order['detail']);
  486. $order['spbill_create_ip'] = \request()->ip();
  487. $order['time_expire'] = date('YmdHis', strtotime("+14 minute"));
  488. return new Order($order);
  489. }
  490. /**
  491. * @param $openid
  492. * @param $out_trade_no
  493. * @param $total_fee
  494. * @param $attach
  495. * @param $body
  496. * @param string $detail
  497. * @param string $trade_type
  498. * @param array $options
  499. * @return array|string
  500. * @author xaboy
  501. * @day 2020-04-20
  502. */
  503. public function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
  504. {
  505. $paymentPrepare = $this->paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
  506. if ($this->isV3()) {
  507. return $paymentPrepare;
  508. }
  509. return $trade_type === 'APP'
  510. ? $this->application->payment->configForAppPayment($paymentPrepare->prepay_id)
  511. : $this->application->payment->configForJSSDKPayment($paymentPrepare->prepay_id);
  512. }
  513. /**
  514. * @param $orderNo
  515. * @param $refundNo
  516. * @param $totalFee
  517. * @param null $refundFee
  518. * @param null $opUserId
  519. * @param string $refundReason
  520. * @param string $type
  521. * @param string $refundAccount
  522. * @return Collection
  523. * @author xaboy
  524. * @day 2020-04-20
  525. */
  526. public function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
  527. {
  528. if (empty($this->config['payment']['pay_weixin_client_cert']) || empty($this->config['payment']['pay_weixin_client_key'])) {
  529. throw new \Exception('请配置微信支付证书');
  530. }
  531. $totalFee = floatval($totalFee);
  532. $refundFee = floatval($refundFee);
  533. if ($this->isV3()) {
  534. return $this->application->v3Pay->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  535. } else {
  536. return $this->application->payment->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
  537. }
  538. }
  539. /**
  540. * @param $orderNo
  541. * @param array $opt
  542. * @author xaboy
  543. * @day 2020-04-20
  544. */
  545. public function payOrderRefund($orderNo, array $opt)
  546. {
  547. if (!isset($opt['pay_price'])) throw new WechatException('缺少pay_price');
  548. $totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
  549. $refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
  550. $refundReason = isset($opt['refund_message']) ? $opt['refund_message'] : '无';
  551. $refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
  552. $opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
  553. $type = isset($opt['type']) ? $opt['type'] : 'out_trade_no';
  554. //若传递此参数则使用对应的资金账户退款,否则默认使用未结算资金退款(仅对老资金流商户适用)
  555. $refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
  556. try {
  557. $res = ($this->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
  558. if (isset($res->return_code) && $res->return_code== 'FAIL')
  559. throw new WechatException('退款失败:' . $res->return_msg);
  560. if (isset($res->err_code))
  561. throw new WechatException('退款失败:' . $res->err_code_des);
  562. } catch (Exception $e) {
  563. throw new WechatException($e->getMessage());
  564. }
  565. }
  566. /**
  567. * array (
  568. * 'appid' => '****',
  569. * 'attach' => 'user_recharge',
  570. * 'bank_type' => 'COMM_CREDIT',
  571. * 'cash_fee' => '1',
  572. * 'fee_type' => 'CNY',
  573. * 'is_subscribe' => 'Y',
  574. * 'mch_id' => ''*****'',
  575. * 'nonce_str' => '5ee9dac1bc302',
  576. * 'openid' => '*****',
  577. * 'out_trade_no' => ''*****'',
  578. * 'result_code' => 'SUCCESS',
  579. * 'return_code' => 'SUCCESS',
  580. * 'sign' => '51'*****'',
  581. * 'time_end' => '20200617165651',
  582. * 'total_fee' => '1',
  583. * 'trade_type' => 'JSAPI',
  584. * 'transaction_id' => ''*****'',
  585. * )
  586. *
  587. * @throws FaultException
  588. * @author xaboy
  589. * @day 2020-04-20
  590. */
  591. public function handleNotify()
  592. {
  593. $this->application->payment = new PaymentService($this->application->merchant);
  594. //TODO 微信支付
  595. return $this->application->payment->handleNotify(function ($notify, $successful) {
  596. Log::info('微信支付成功回调' . var_export($notify, 1));
  597. if (!$successful) return false;
  598. try {
  599. event('pay_success_' . $notify['attach'], ['order_sn' => $notify['out_trade_no'], 'data' => $notify, 'is_combine' => 0]);
  600. } catch (\Exception $e) {
  601. Log::info('微信支付回调失败:' . $e->getMessage());
  602. return false;
  603. }
  604. return true;
  605. });
  606. }
  607. public function handleNotifyV3()
  608. {
  609. return $this->application->v3Pay->handleNotify(function ($notify, $successful) {
  610. Log::info('微信支付成功回调' . var_export($notify, 1));
  611. if (!$successful) return false;
  612. try {
  613. event('pay_success_' . $notify['attach'], ['order_sn' => $notify['out_trade_no'], 'data' => $notify, 'is_combine' => 0]);
  614. } catch (\Exception $e) {
  615. Log::info('微信支付回调失败:' . $e->getMessage());
  616. return false;
  617. }
  618. return true;
  619. });
  620. }
  621. public function handleCombinePayNotify($type)
  622. {
  623. return $this->application->combinePay->handleNotify(function ($notify, $successful) use ($type) {
  624. Log::info('微信支付成功回调' . var_export($notify, 1));
  625. if (!$successful) return false;
  626. try {
  627. event('pay_success_' . $type, ['order_sn' => $notify['combine_out_trade_no'], 'data' => $notify, 'is_combine' => 1]);
  628. } catch (\Exception $e) {
  629. Log::info('微信支付回调失败:' . $e->getMessage());
  630. return false;
  631. }
  632. return true;
  633. });
  634. }
  635. /**
  636. * @param string $url
  637. * @return array|string
  638. * @author xaboy
  639. * @day 2020-04-20
  640. */
  641. public function jsSdk($url)
  642. {
  643. $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'];
  644. $jsService = $this->application->js;
  645. $jsService->setUrl($url);
  646. try {
  647. return $jsService->config($apiList, false, false, false);
  648. } catch (Exception $e) {
  649. Log::info('微信参数获取失败' . $e->getMessage());
  650. return [];
  651. }
  652. }
  653. /**
  654. * 回复文本消息
  655. * @param string $content 文本内容
  656. * @return Text
  657. * @author xaboy
  658. * @day 2020-04-20
  659. */
  660. public static function textMessage($content)
  661. {
  662. return new Text(compact('content'));
  663. }
  664. /**
  665. * 回复图片消息
  666. * @param string $media_id 媒体资源 ID
  667. * @return Image
  668. * @author xaboy
  669. * @day 2020-04-20
  670. */
  671. public static function imageMessage($media_id)
  672. {
  673. return new Image(compact('media_id'));
  674. }
  675. /**
  676. * 回复视频消息
  677. * @param string $media_id 媒体资源 ID
  678. * @param string $title 标题
  679. * @param string $description 描述
  680. * @param null $thumb_media_id 封面资源 ID
  681. * @return Video
  682. * @author xaboy
  683. * @day 2020-04-20
  684. */
  685. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  686. {
  687. return new Video(compact('media_id', 'title', 'description', 'thumb_media_id'));
  688. }
  689. /**
  690. * 回复声音消息
  691. * @param string $media_id 媒体资源 ID
  692. * @return Voice
  693. * @author xaboy
  694. * @day 2020-04-20
  695. */
  696. public static function voiceMessage($media_id)
  697. {
  698. return new Voice(compact('media_id'));
  699. }
  700. /**
  701. * 回复图文消息
  702. * @param string|array $title 标题
  703. * @param string $description 描述
  704. * @param string $url URL
  705. * @param string $image 图片链接
  706. * @return News|array<News>
  707. * @author xaboy
  708. * @day 2020-04-20
  709. */
  710. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  711. {
  712. if (is_array($title)) {
  713. if (isset($title[0]) && is_array($title[0])) {
  714. $newsList = [];
  715. foreach ($title as $news) {
  716. $newsList[] = self::newsMessage($news);
  717. }
  718. return $newsList;
  719. } else {
  720. $data = $title;
  721. }
  722. } else {
  723. $data = compact('title', 'description', 'url', 'image');
  724. }
  725. return new News($data);
  726. }
  727. /**
  728. * 回复文章消息
  729. * @param string|array $title 标题
  730. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  731. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  732. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  733. * @param string $author 作者
  734. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  735. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  736. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  737. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  738. * @return Article
  739. * @author xaboy
  740. * @day 2020-04-20
  741. */
  742. 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)
  743. {
  744. $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');
  745. return new Article($data);
  746. }
  747. /**
  748. * 回复素材消息
  749. * @param string $type [mpnews、 mpvideo、voice、image]
  750. * @param string $media_id 素材 ID
  751. * @return Material
  752. * @author xaboy
  753. * @day 2020-04-20
  754. */
  755. public static function materialMessage($type, $media_id)
  756. {
  757. return new Material($type, $media_id);
  758. }
  759. /**
  760. * @param $to
  761. * @param $message
  762. * @return bool
  763. * @throws InvalidArgumentException
  764. * @throws RuntimeException
  765. * @author xaboy
  766. * @day 2020-04-20
  767. */
  768. public function staffTo($to, $message)
  769. {
  770. $staff = $this->application->staff;
  771. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  772. $res = $staff->to($to)->send();
  773. return $res;
  774. }
  775. /**
  776. * @param $openid
  777. * @return array
  778. * @author xaboy
  779. * @day 2020-04-20
  780. */
  781. public function getUserInfo($openid)
  782. {
  783. $userService = $this->application->user;
  784. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  785. return $userInfo->toArray();
  786. }
  787. /**
  788. * 模板消息接口
  789. * @return \EasyWeChat\Notice\Notice
  790. */
  791. public function noticeService()
  792. {
  793. return $this->application->notice;
  794. }
  795. /**
  796. * 微信二维码生成接口
  797. * @return \EasyWeChat\QRCode\QRCode
  798. */
  799. public function qrcodeService()
  800. {
  801. return $this->application->qrcode;
  802. }
  803. public function storePay()
  804. {
  805. return $this->application->storePay;
  806. }
  807. /**
  808. * 商家到零钱回调
  809. *
  810. * @param string $type
  811. * @return void
  812. */
  813. public function handleCompanyPayNotify(string $type)
  814. {
  815. return $this->application->batches->handleNotify(function ($notify) use ($type) {
  816. Log::info('公众号转账回调' . var_export($notify, 1));
  817. try {
  818. event('company_extract_status', ['type' => $type, 'data' => $notify]);
  819. } catch (\Exception $e) {
  820. Log::info('公众号转账回调失败 handle:' . $e->getMessage());
  821. return false;
  822. }
  823. return true;
  824. });
  825. }
  826. /**
  827. * V3的商家到零钱
  828. * @author Qinii
  829. * @day 2023/3/13
  830. */
  831. public function companyPay($data, $user = null)
  832. {
  833. $outBatchNo = $data['sn'];
  834. $amount = $data['price'];
  835. $openid = $data['openid'];
  836. $userName = $data['realName'] ?? '';
  837. $remark = $data['mark'] ?? '';
  838. $transferSceneId = systemConfig('transfer_scene_id');
  839. $type = 'wechat';
  840. $transferDetailList = [
  841. [
  842. 'info_type' => '活动名称',
  843. 'info_content' => '奖金转入余额'
  844. ],
  845. [
  846. 'info_type' => '奖励说明',
  847. 'info_content' => '奖金转入余额'
  848. ]
  849. ];
  850. $result = $this->application->batches->transferBills(
  851. $outBatchNo,
  852. $amount,
  853. $openid,
  854. $userName,
  855. $remark,
  856. $transferDetailList,
  857. $transferSceneId,
  858. $type
  859. );
  860. Log::info('发起转账返回:' . json_encode($result));
  861. return $result;
  862. }
  863. /**
  864. * V2的企业到零钱
  865. * @param $data
  866. * @return mixed
  867. * @author Qinii
  868. * @day 2023/3/13
  869. */
  870. public function merchantPay($data, $user = null)
  871. {
  872. $ret = [
  873. 'partner_trade_no' => $data['sn'], //随机字符串作为订单号,跟红包和支付一个概念。
  874. 'openid' => $data['openid'], //收款人的openid
  875. 'check_name' => 'NO_CHECK', //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
  876. //'re_user_name'=>'张三', //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
  877. 'amount' => $data['price'] * 100, //单位为分
  878. 'desc' => $data['mark'] ?? '',
  879. 'spbill_create_ip' => request()->ip(), //发起交易的IP地址
  880. ];
  881. $result = $this->application->merchant_pay->send($ret);
  882. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  883. return $result;
  884. } else {
  885. if ($result->return_code == 'FAIL') {
  886. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  887. } else if (isset($result->err_code)) {
  888. throw new WechatException('微信支付错误返回:' . $result->err_code_des);
  889. } else {
  890. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  891. }
  892. }
  893. }
  894. /**
  895. * 分账商户
  896. * @return mixed
  897. * @author Qinii
  898. * @day 6/24/21
  899. */
  900. public function applyments()
  901. {
  902. return $this->application->sub_merchant;
  903. }
  904. /**
  905. * 上传图片
  906. * @param array $filed
  907. * @return mixed
  908. * @author Qinii
  909. * @day 6/21/21
  910. */
  911. public function uploadImages(array $filed)
  912. {
  913. if (empty($filed)) throw new InvalidArgumentException('图片为空');
  914. foreach ($filed as $file) {
  915. $item = $this->application->sub_merchant->upload($file['path'], $file['name']);
  916. $data[] = [
  917. 'dir' => $file['dir'],
  918. 'media_id' => $item['media_id'],
  919. ];
  920. }
  921. return $data;
  922. }
  923. public function qrKeyByMessage($key)
  924. {
  925. if (strpos($key, '_scan_url_') === 0) {
  926. $key = str_replace('_scan_url_', '', $key);
  927. $data = explode('_', $key);
  928. $siteUrl = rtrim(systemConfig('site_url'), '/');
  929. $make = app()->make(ProductRepository::class);
  930. if ($data[0] === 'home') {
  931. $share = systemConfig(['share_title', 'share_info', 'share_pic']);
  932. $share['url'] = $siteUrl . '?spid=' . $data[1];
  933. } else if ($data[0] === 'mer') {
  934. $ret = app()->make(MerchantRepository::class)->get($data[1]);
  935. if (!$ret) return;
  936. $share = [
  937. 'share_title' => $ret['mer_name'],
  938. 'share_info' => $ret['mer_info'],
  939. 'share_pic' => $ret['mer_avatar'],
  940. 'url' => $siteUrl . '/pages/store/home/index?id=' . $data[1],
  941. ];
  942. } else if ($data[0] === 'p0') {
  943. $ret = $make->get($data[1]);
  944. if (!$ret) return;
  945. $share = [
  946. 'share_title' => $ret['store_name'],
  947. 'share_info' => $ret['store_info'],
  948. 'share_pic' => $ret['image'],
  949. 'url' => $siteUrl . '/pages/goods_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  950. ];
  951. } else if ($data[0] === 'p1') {
  952. $ret = $make->get($data[1]);
  953. if (!$ret) return;
  954. $share = [
  955. 'share_title' => $ret['store_name'],
  956. 'share_info' => $ret['store_info'],
  957. 'share_pic' => $ret['image'],
  958. 'url' => $siteUrl . '/pages/activity/goods_seckill_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  959. ];
  960. } else if ($data[0] === 'p2') {
  961. $ret = app()->make(ProductPresellRepository::class)->search(['product_presell_id' => $data[1]])->find();
  962. $res = $make->get($ret['product_id']);
  963. if (!$ret) return;
  964. $share = [
  965. 'share_title' => $ret['store_name'],
  966. 'share_info' => $ret['store_info'],
  967. 'share_pic' => $res['image'],
  968. 'url' => $siteUrl . '/pages/activity/presell_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  969. ];
  970. } else if ($data[0] === 'p3') {
  971. $ret = app()->make(ProductAssistSetRepository::class)->getSearch(['product_assist_set_id' => $data[1]])->find();
  972. $res = $make->get($ret['product_id']);
  973. if (!$ret) return;
  974. $share = [
  975. 'share_title' => $res['store_name'],
  976. 'share_info' => $res['store_info'],
  977. 'share_pic' => $res['image'],
  978. 'url' => $siteUrl . '/pages/activity/assist_detail/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  979. ];
  980. } else if ($data[0] === 'p4') {
  981. $ret = app()->make(ProductGroupRepository::class)->get($data[1]);
  982. $res = $make->get($ret['product_id']);
  983. if (!$ret) return;
  984. $share = [
  985. 'share_title' => $res['store_name'],
  986. 'share_info' => $res['store_info'],
  987. 'share_pic' => $res['image'],
  988. 'url' => $siteUrl . '/pages/activity/combination_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  989. ];
  990. } else if ($data[0] === 'p40') {
  991. $res = app()->make(ProductGroupBuyingRepository::class)->getSearch(['group_buying_id' => $data[1]])->find();
  992. $ret = $make->get($res->productGroup['product_id']);
  993. if (!$ret) return;
  994. $share = [
  995. 'share_title' => $ret['store_name'],
  996. 'share_info' => $ret['store_info'],
  997. 'share_pic' => $ret['image'],
  998. 'url' => $siteUrl . '/pages/activity/combination_status/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  999. ];
  1000. } else if ($data[0] === 'form') {
  1001. $res = app()->make(StoreActivityRepository::class)->getSearch(['activity_id' => $data[1]])->find();
  1002. if (!$res) return;
  1003. $share = [
  1004. 'share_title' => $res['activity_name'],
  1005. 'share_info' => $res['info'],
  1006. 'share_pic' => $res['pic'],
  1007. 'url' => $siteUrl . '/pages/activity/registrate_activity/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  1008. ];
  1009. } else {
  1010. return;
  1011. }
  1012. return self::newsMessage($share['share_title'], $share['share_info'], $share['url'], $share['share_pic']);
  1013. }
  1014. }
  1015. /**
  1016. * @return easywechat\combinePay\Client
  1017. */
  1018. public function combinePay()
  1019. {
  1020. return $this->application->combinePay;
  1021. }
  1022. /**
  1023. * 获取模板列表
  1024. * @return \EasyWeChat\Support\Collection
  1025. */
  1026. public function getPrivateTemplates()
  1027. {
  1028. try {
  1029. return $this->application->new_notice->getPrivateTemplates();
  1030. } catch (\Exception $e) {
  1031. throw new ValidateException($this->getMessage($e->getMessage()));
  1032. }
  1033. }
  1034. /**
  1035. * 获得添加模版ID
  1036. * @param $template_id_short
  1037. */
  1038. public function addTemplateId($template_id_short,$keyword_name_list)
  1039. {
  1040. try {
  1041. return $this->application->new_notice->addTemplate($template_id_short,$keyword_name_list);
  1042. } catch (\Exception $e) {
  1043. throw new ValidateException($this->getMessage($e->getMessage()));
  1044. }
  1045. }
  1046. /*
  1047. * 根据模版ID删除模版
  1048. */
  1049. public function deleleTemplate($template_id)
  1050. {
  1051. try {
  1052. return $this->application->new_notice->deletePrivateTemplate($template_id);
  1053. } catch (\Exception $e) {
  1054. throw new ValidateException($this->getMessage($e->getMessage()));
  1055. }
  1056. }
  1057. /**
  1058. * 处理返回错误信息友好提示
  1059. * @param string $message
  1060. * @return array|mixed|string
  1061. */
  1062. public function getMessage(string $message)
  1063. {
  1064. if (strstr($message, 'Request AccessToken fail') !== false) {
  1065. $message = str_replace('Request AccessToken fail. response:', '', $message);
  1066. $message = json_decode($message, true) ?: [];
  1067. $errcode = $message['errcode'] ?? false;
  1068. if ($errcode) {
  1069. $message = ApiErrorCode::ERROR_WECHAT_MESSAGE[$errcode] ?? $message;
  1070. }
  1071. }
  1072. return $message;
  1073. }
  1074. /**
  1075. * 查询订单支付状态
  1076. *
  1077. * @param $orderNo
  1078. * @return void
  1079. */
  1080. public function query($orderNo)
  1081. {
  1082. return $this->application->payment->query($orderNo);
  1083. }
  1084. }