WechatService.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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. @file_put_contents('quanju3.txt',json_encode($jsService->config($apiList, false, false, false))."-微信测试3\r\n",8);
  648. return $jsService->config($apiList, false, false, false);
  649. } catch (Exception $e) {
  650. @file_put_contents('quanju3.txt',$e->getMessage()."-微信测试4\r\n",8);
  651. Log::info('微信参数获取失败' . $e->getMessage());
  652. return [];
  653. }
  654. }
  655. /**
  656. * 回复文本消息
  657. * @param string $content 文本内容
  658. * @return Text
  659. * @author xaboy
  660. * @day 2020-04-20
  661. */
  662. public static function textMessage($content)
  663. {
  664. return new Text(compact('content'));
  665. }
  666. /**
  667. * 回复图片消息
  668. * @param string $media_id 媒体资源 ID
  669. * @return Image
  670. * @author xaboy
  671. * @day 2020-04-20
  672. */
  673. public static function imageMessage($media_id)
  674. {
  675. return new Image(compact('media_id'));
  676. }
  677. /**
  678. * 回复视频消息
  679. * @param string $media_id 媒体资源 ID
  680. * @param string $title 标题
  681. * @param string $description 描述
  682. * @param null $thumb_media_id 封面资源 ID
  683. * @return Video
  684. * @author xaboy
  685. * @day 2020-04-20
  686. */
  687. public static function videoMessage($media_id, $title = '', $description = '...', $thumb_media_id = null)
  688. {
  689. return new Video(compact('media_id', 'title', 'description', 'thumb_media_id'));
  690. }
  691. /**
  692. * 回复声音消息
  693. * @param string $media_id 媒体资源 ID
  694. * @return Voice
  695. * @author xaboy
  696. * @day 2020-04-20
  697. */
  698. public static function voiceMessage($media_id)
  699. {
  700. return new Voice(compact('media_id'));
  701. }
  702. /**
  703. * 回复图文消息
  704. * @param string|array $title 标题
  705. * @param string $description 描述
  706. * @param string $url URL
  707. * @param string $image 图片链接
  708. * @return News|array<News>
  709. * @author xaboy
  710. * @day 2020-04-20
  711. */
  712. public static function newsMessage($title, $description = '...', $url = '', $image = '')
  713. {
  714. if (is_array($title)) {
  715. if (isset($title[0]) && is_array($title[0])) {
  716. $newsList = [];
  717. foreach ($title as $news) {
  718. $newsList[] = self::newsMessage($news);
  719. }
  720. return $newsList;
  721. } else {
  722. $data = $title;
  723. }
  724. } else {
  725. $data = compact('title', 'description', 'url', 'image');
  726. }
  727. return new News($data);
  728. }
  729. /**
  730. * 回复文章消息
  731. * @param string|array $title 标题
  732. * @param string $thumb_media_id 图文消息的封面图片素材id(必须是永久 media_ID)
  733. * @param string $source_url 图文消息的原文地址,即点击“阅读原文”后的URL
  734. * @param string $content 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
  735. * @param string $author 作者
  736. * @param string $digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
  737. * @param int $show_cover_pic 是否显示封面,0为false,即不显示,1为true,即显示
  738. * @param int $need_open_comment 是否打开评论,0不打开,1打开
  739. * @param int $only_fans_can_comment 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
  740. * @return Article
  741. * @author xaboy
  742. * @day 2020-04-20
  743. */
  744. 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)
  745. {
  746. $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');
  747. return new Article($data);
  748. }
  749. /**
  750. * 回复素材消息
  751. * @param string $type [mpnews、 mpvideo、voice、image]
  752. * @param string $media_id 素材 ID
  753. * @return Material
  754. * @author xaboy
  755. * @day 2020-04-20
  756. */
  757. public static function materialMessage($type, $media_id)
  758. {
  759. return new Material($type, $media_id);
  760. }
  761. /**
  762. * @param $to
  763. * @param $message
  764. * @return bool
  765. * @throws InvalidArgumentException
  766. * @throws RuntimeException
  767. * @author xaboy
  768. * @day 2020-04-20
  769. */
  770. public function staffTo($to, $message)
  771. {
  772. $staff = $this->application->staff;
  773. $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
  774. $res = $staff->to($to)->send();
  775. return $res;
  776. }
  777. /**
  778. * @param $openid
  779. * @return array
  780. * @author xaboy
  781. * @day 2020-04-20
  782. */
  783. public function getUserInfo($openid)
  784. {
  785. $userService = $this->application->user;
  786. $userInfo = is_array($openid) ? $userService->batchGet($openid) : $userService->get($openid);
  787. return $userInfo->toArray();
  788. }
  789. /**
  790. * 模板消息接口
  791. * @return \EasyWeChat\Notice\Notice
  792. */
  793. public function noticeService()
  794. {
  795. return $this->application->notice;
  796. }
  797. /**
  798. * 微信二维码生成接口
  799. * @return \EasyWeChat\QRCode\QRCode
  800. */
  801. public function qrcodeService()
  802. {
  803. return $this->application->qrcode;
  804. }
  805. public function storePay()
  806. {
  807. return $this->application->storePay;
  808. }
  809. /**
  810. * 商家到零钱回调
  811. *
  812. * @param string $type
  813. * @return void
  814. */
  815. public function handleCompanyPayNotify(string $type)
  816. {
  817. return $this->application->batches->handleNotify(function ($notify) use ($type) {
  818. Log::info('公众号转账回调' . var_export($notify, 1));
  819. try {
  820. event('company_extract_status', ['type' => $type, 'data' => $notify]);
  821. } catch (\Exception $e) {
  822. Log::info('公众号转账回调失败 handle:' . $e->getMessage());
  823. return false;
  824. }
  825. return true;
  826. });
  827. }
  828. /**
  829. * V3的商家到零钱
  830. * @author Qinii
  831. * @day 2023/3/13
  832. */
  833. public function companyPay($data, $user = null)
  834. {
  835. $outBatchNo = $data['sn'];
  836. $amount = $data['price'];
  837. $openid = $data['openid'];
  838. $userName = $data['realName'] ?? '';
  839. $remark = $data['mark'] ?? '';
  840. $transferSceneId = systemConfig('transfer_scene_id');
  841. $type = 'wechat';
  842. $transferDetailList = [
  843. [
  844. 'info_type' => '活动名称',
  845. 'info_content' => '奖金转入余额'
  846. ],
  847. [
  848. 'info_type' => '奖励说明',
  849. 'info_content' => '奖金转入余额'
  850. ]
  851. ];
  852. $result = $this->application->batches->transferBills(
  853. $outBatchNo,
  854. $amount,
  855. $openid,
  856. $userName,
  857. $remark,
  858. $transferDetailList,
  859. $transferSceneId,
  860. $type
  861. );
  862. Log::info('发起转账返回:' . json_encode($result));
  863. return $result;
  864. }
  865. /**
  866. * V2的企业到零钱
  867. * @param $data
  868. * @return mixed
  869. * @author Qinii
  870. * @day 2023/3/13
  871. */
  872. public function merchantPay($data, $user = null)
  873. {
  874. $ret = [
  875. 'partner_trade_no' => $data['sn'], //随机字符串作为订单号,跟红包和支付一个概念。
  876. 'openid' => $data['openid'], //收款人的openid
  877. 'check_name' => 'NO_CHECK', //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
  878. //'re_user_name'=>'张三', //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
  879. 'amount' => $data['price'] * 100, //单位为分
  880. 'desc' => $data['mark'] ?? '',
  881. 'spbill_create_ip' => request()->ip(), //发起交易的IP地址
  882. ];
  883. $result = $this->application->merchant_pay->send($ret);
  884. if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
  885. return $result;
  886. } else {
  887. if ($result->return_code == 'FAIL') {
  888. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  889. } else if (isset($result->err_code)) {
  890. throw new WechatException('微信支付错误返回:' . $result->err_code_des);
  891. } else {
  892. throw new WechatException('微信支付错误返回:' . $result->return_msg);
  893. }
  894. }
  895. }
  896. /**
  897. * 分账商户
  898. * @return mixed
  899. * @author Qinii
  900. * @day 6/24/21
  901. */
  902. public function applyments()
  903. {
  904. return $this->application->sub_merchant;
  905. }
  906. /**
  907. * 上传图片
  908. * @param array $filed
  909. * @return mixed
  910. * @author Qinii
  911. * @day 6/21/21
  912. */
  913. public function uploadImages(array $filed)
  914. {
  915. if (empty($filed)) throw new InvalidArgumentException('图片为空');
  916. foreach ($filed as $file) {
  917. $item = $this->application->sub_merchant->upload($file['path'], $file['name']);
  918. $data[] = [
  919. 'dir' => $file['dir'],
  920. 'media_id' => $item['media_id'],
  921. ];
  922. }
  923. return $data;
  924. }
  925. public function qrKeyByMessage($key)
  926. {
  927. if (strpos($key, '_scan_url_') === 0) {
  928. $key = str_replace('_scan_url_', '', $key);
  929. $data = explode('_', $key);
  930. $siteUrl = rtrim(systemConfig('site_url'), '/');
  931. $make = app()->make(ProductRepository::class);
  932. if ($data[0] === 'home') {
  933. $share = systemConfig(['share_title', 'share_info', 'share_pic']);
  934. $share['url'] = $siteUrl . '?spid=' . $data[1];
  935. } else if ($data[0] === 'mer') {
  936. $ret = app()->make(MerchantRepository::class)->get($data[1]);
  937. if (!$ret) return;
  938. $share = [
  939. 'share_title' => $ret['mer_name'],
  940. 'share_info' => $ret['mer_info'],
  941. 'share_pic' => $ret['mer_avatar'],
  942. 'url' => $siteUrl . '/pages/store/home/index?id=' . $data[1],
  943. ];
  944. } else if ($data[0] === 'p0') {
  945. $ret = $make->get($data[1]);
  946. if (!$ret) return;
  947. $share = [
  948. 'share_title' => $ret['store_name'],
  949. 'share_info' => $ret['store_info'],
  950. 'share_pic' => $ret['image'],
  951. 'url' => $siteUrl . '/pages/goods_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  952. ];
  953. } else if ($data[0] === 'p1') {
  954. $ret = $make->get($data[1]);
  955. if (!$ret) return;
  956. $share = [
  957. 'share_title' => $ret['store_name'],
  958. 'share_info' => $ret['store_info'],
  959. 'share_pic' => $ret['image'],
  960. 'url' => $siteUrl . '/pages/activity/goods_seckill_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  961. ];
  962. } else if ($data[0] === 'p2') {
  963. $ret = app()->make(ProductPresellRepository::class)->search(['product_presell_id' => $data[1]])->find();
  964. $res = $make->get($ret['product_id']);
  965. if (!$ret) return;
  966. $share = [
  967. 'share_title' => $ret['store_name'],
  968. 'share_info' => $ret['store_info'],
  969. 'share_pic' => $res['image'],
  970. 'url' => $siteUrl . '/pages/activity/presell_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  971. ];
  972. } else if ($data[0] === 'p3') {
  973. $ret = app()->make(ProductAssistSetRepository::class)->getSearch(['product_assist_set_id' => $data[1]])->find();
  974. $res = $make->get($ret['product_id']);
  975. if (!$ret) return;
  976. $share = [
  977. 'share_title' => $res['store_name'],
  978. 'share_info' => $res['store_info'],
  979. 'share_pic' => $res['image'],
  980. 'url' => $siteUrl . '/pages/activity/assist_detail/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  981. ];
  982. } else if ($data[0] === 'p4') {
  983. $ret = app()->make(ProductGroupRepository::class)->get($data[1]);
  984. $res = $make->get($ret['product_id']);
  985. if (!$ret) return;
  986. $share = [
  987. 'share_title' => $res['store_name'],
  988. 'share_info' => $res['store_info'],
  989. 'share_pic' => $res['image'],
  990. 'url' => $siteUrl . '/pages/activity/combination_details/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  991. ];
  992. } else if ($data[0] === 'p40') {
  993. $res = app()->make(ProductGroupBuyingRepository::class)->getSearch(['group_buying_id' => $data[1]])->find();
  994. $ret = $make->get($res->productGroup['product_id']);
  995. if (!$ret) return;
  996. $share = [
  997. 'share_title' => $ret['store_name'],
  998. 'share_info' => $ret['store_info'],
  999. 'share_pic' => $ret['image'],
  1000. 'url' => $siteUrl . '/pages/activity/combination_status/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  1001. ];
  1002. } else if ($data[0] === 'form') {
  1003. $res = app()->make(StoreActivityRepository::class)->getSearch(['activity_id' => $data[1]])->find();
  1004. if (!$res) return;
  1005. $share = [
  1006. 'share_title' => $res['activity_name'],
  1007. 'share_info' => $res['info'],
  1008. 'share_pic' => $res['pic'],
  1009. 'url' => $siteUrl . '/pages/activity/registrate_activity/index?id=' . $data[1] . '&spid=' . ($data[2] ?? 0),
  1010. ];
  1011. } else {
  1012. return;
  1013. }
  1014. return self::newsMessage($share['share_title'], $share['share_info'], $share['url'], $share['share_pic']);
  1015. }
  1016. }
  1017. /**
  1018. * @return easywechat\combinePay\Client
  1019. */
  1020. public function combinePay()
  1021. {
  1022. return $this->application->combinePay;
  1023. }
  1024. /**
  1025. * 获取模板列表
  1026. * @return \EasyWeChat\Support\Collection
  1027. */
  1028. public function getPrivateTemplates()
  1029. {
  1030. try {
  1031. return $this->application->new_notice->getPrivateTemplates();
  1032. } catch (\Exception $e) {
  1033. throw new ValidateException($this->getMessage($e->getMessage()));
  1034. }
  1035. }
  1036. /**
  1037. * 获得添加模版ID
  1038. * @param $template_id_short
  1039. */
  1040. public function addTemplateId($template_id_short,$keyword_name_list)
  1041. {
  1042. try {
  1043. return $this->application->new_notice->addTemplate($template_id_short,$keyword_name_list);
  1044. } catch (\Exception $e) {
  1045. throw new ValidateException($this->getMessage($e->getMessage()));
  1046. }
  1047. }
  1048. /*
  1049. * 根据模版ID删除模版
  1050. */
  1051. public function deleleTemplate($template_id)
  1052. {
  1053. try {
  1054. return $this->application->new_notice->deletePrivateTemplate($template_id);
  1055. } catch (\Exception $e) {
  1056. throw new ValidateException($this->getMessage($e->getMessage()));
  1057. }
  1058. }
  1059. /**
  1060. * 处理返回错误信息友好提示
  1061. * @param string $message
  1062. * @return array|mixed|string
  1063. */
  1064. public function getMessage(string $message)
  1065. {
  1066. if (strstr($message, 'Request AccessToken fail') !== false) {
  1067. $message = str_replace('Request AccessToken fail. response:', '', $message);
  1068. $message = json_decode($message, true) ?: [];
  1069. $errcode = $message['errcode'] ?? false;
  1070. if ($errcode) {
  1071. $message = ApiErrorCode::ERROR_WECHAT_MESSAGE[$errcode] ?? $message;
  1072. }
  1073. }
  1074. return $message;
  1075. }
  1076. /**
  1077. * 查询订单支付状态
  1078. *
  1079. * @param $orderNo
  1080. * @return void
  1081. */
  1082. public function query($orderNo)
  1083. {
  1084. return $this->application->payment->query($orderNo);
  1085. }
  1086. }