WechatService.php 45 KB

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