WechatService.php 44 KB

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