PaymentService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services;
  12. use App\Models\AccountLogModel;
  13. use App\Models\OrderModel;
  14. use App\Models\PaymentModel;
  15. use App\Services\Api\SettleService;
  16. use Illuminate\Support\Facades\DB;
  17. use Yansongda\Pay\Pay;
  18. use Yansongda\Pay\Plugin\Wechat\Fund\Profitsharing\AddReceiverPlugin;
  19. use Yansongda\Pay\Plugin\Wechat\Fund\Profitsharing\CreatePlugin;
  20. use Yansongda\Pay\Provider\Wechat;
  21. /**
  22. * 支付-服务类
  23. * @author laravel开发员
  24. * @since 2020/11/11
  25. * Class PaymentService
  26. * @package App\Services\Api
  27. */
  28. class PaymentService extends BaseService
  29. {
  30. protected static $instance = null;
  31. private $config = [];
  32. /**
  33. * 构造函数
  34. * @author laravel开发员
  35. * @since 2020/11/11
  36. * PaymentService constructor.
  37. */
  38. public function __construct()
  39. {
  40. $this->model = new PaymentModel();
  41. }
  42. /**
  43. * 静态入口
  44. * @return static|null
  45. */
  46. public static function make()
  47. {
  48. if (!self::$instance) {
  49. self::$instance = (new static());
  50. }
  51. return self::$instance;
  52. }
  53. /**
  54. * 创建支付
  55. * @param string $scene 场景,store-购物消费,pay-生活充值,refund-退款
  56. * @param int $payType
  57. * @param int $isMin 是否是小程序
  58. * @return false|\Yansongda\Pay\Provider\Alipay|Wechat
  59. */
  60. public function createPay($scene, $payType = 10, $payPt = '')
  61. {
  62. $config = ConfigService::make()->getConfigOptionByGroup(6);
  63. try {
  64. if ($payType == 10) {
  65. $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
  66. $mpAppid = isset($config['wxpay_mp_appid']) ? $config['wxpay_mp_appid'] : '';
  67. $minAppid = isset($config['wxpay_min_appid']) ? $config['wxpay_min_appid'] : '';
  68. $mchid = isset($config['wxpay_mchd']) ? $config['wxpay_mchd'] : '';
  69. $secretV3Key = isset($config['wxpay_key_v3']) ? $config['wxpay_key_v3'] : '';
  70. $secretV2Key = isset($config['wxpay_key_v2']) ? $config['wxpay_key_v2'] : '';
  71. $wxpaySecretCert = isset($config['wxpay_secret_cert']) ? $config['wxpay_secret_cert'] : '';
  72. $wxpayPublicCert = isset($config['wxpay_public_cert']) ? $config['wxpay_public_cert'] : '';
  73. if (empty($appid) || empty($mchid) || empty($secretV3Key)) {
  74. $this->error = 2616;
  75. return false;
  76. }
  77. // 支付参数
  78. $payConfig = config('payment.wechat');
  79. $payConfig['wechat']['default']['mch_id'] = $mchid;
  80. if ($payPt == 'min') {
  81. // 小程序支付
  82. $payConfig['wechat']['default']['mini_app_id'] = $minAppid ? $minAppid : $appid;
  83. } else if ($payPt == 'mp') {
  84. // 公众号
  85. $payConfig['wechat']['default']['mp_app_id'] = $mpAppid ? $mpAppid : $appid;
  86. } else {
  87. // APP支付
  88. $payConfig['wechat']['default']['app_id'] = $appid;
  89. }
  90. if ($secretV3Key) {
  91. $payConfig['wechat']['default']['mch_secret_key'] = $secretV3Key;
  92. } else if ($secretV2Key) {
  93. $payConfig['wechat']['default']['mch_secret_key_v2'] = $secretV2Key;
  94. }
  95. if ($wxpaySecretCert) {
  96. $payConfig['wechat']['default']['mch_secret_cert'] = $wxpaySecretCert;
  97. }
  98. if ($wxpayPublicCert) {
  99. $payConfig['wechat']['default']['mch_public_cert_path'] = $wxpayPublicCert;
  100. }
  101. //$payConfig['wechat']['default']['notify_url'] = url('/api/notify/' . $scene . '/10');
  102. $payConfig['wechat']['default']['notify_url'] = url(env('APP_URL') . 'api/notify/' . $scene . '/10');
  103. $this->config = $payConfig;
  104. //var_dump($payConfig);
  105. return Pay::wechat($payConfig);
  106. } else if ($payType == 20) {
  107. $appid = isset($config['alipay_appid']) ? $config['alipay_appid'] : '';
  108. $appSecretCert = isset($config['alipay_secret_cert']) ? $config['alipay_secret_cert'] : '';
  109. $appPublicCert = isset($config['alipay_app_public_cert_path']) ? $config['alipay_app_public_cert_path'] : '';
  110. $alipayPublicCert = isset($config['alipay_public_cert_path']) ? $config['alipay_public_cert_path'] : '';
  111. $alipayRootCert = isset($config['alipay_root_cert_path']) ? $config['alipay_root_cert_path'] : '';
  112. if (empty($appid) || empty($appSecretCert)) {
  113. $this->error = 2619;
  114. return false;
  115. }
  116. // 支付参数
  117. $payConfig = config('payment.alipay');
  118. $payConfig['alipay']['default']['app_id'] = $appid;
  119. $payConfig['alipay']['default']['app_secret_cert'] = $appSecretCert;
  120. if ($appPublicCert) {
  121. $payConfig['alipay']['default']['app_public_cert_path'] = $appPublicCert;
  122. }
  123. if ($alipayPublicCert) {
  124. $payConfig['alipay']['default']['alipay_public_cert_path'] = $alipayPublicCert;
  125. }
  126. if ($alipayRootCert) {
  127. $payConfig['alipay']['default']['alipay_root_cert_path'] = $alipayRootCert;
  128. }
  129. $payConfig['alipay']['default']['notify_url'] = url('/api/notify/' . $scene . '/20');
  130. $this->config = $payConfig;
  131. return Pay::alipay($payConfig);
  132. } else if ($payType == 30) {
  133. return true;
  134. }
  135. return false;
  136. } catch (\Exception $exception){
  137. $this->errorData = $this->config;
  138. $this->error = '请检查支付配置是否正常:'.$exception->getMessage();
  139. return false;
  140. }
  141. }
  142. /**
  143. * 微信小程序支付
  144. * @param $userInfo
  145. * @param $order
  146. * @param string $scene
  147. * @return false|\Yansongda\Supports\Collection
  148. */
  149. public function minPay($userInfo, $order, $scene = 'store')
  150. {
  151. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  152. $openid = isset($order['openid']) ? $order['openid'] : '';
  153. if ($amount < 0) {
  154. $this->error = 2615;
  155. return false;
  156. }
  157. if (empty($openid)) {
  158. $this->error = 2614;
  159. return false;
  160. }
  161. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  162. // 是否调用过支付,是则用新的支付单号
  163. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  164. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  165. }
  166. $body = isset($order['body']) ? $order['body'] : '';
  167. $payData = [
  168. 'out_trade_no' => $outTradeNo,
  169. 'description' => $body ? $body : '订单支付',
  170. 'amount' => [
  171. 'total' => intval($amount * 100),
  172. 'currency' => 'CNY'
  173. ],
  174. 'payer' => [
  175. 'openid' => $openid,
  176. ],
  177. ];
  178. // 创建支付
  179. try {
  180. $pay = $this->createPay($scene, 10, 'min');
  181. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  182. if (empty($pay)) {
  183. $this->error = 2616;
  184. return false;
  185. }
  186. $pay = $pay->mini($payData);
  187. } catch (\Exception $exception) {
  188. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  189. $this->error = $exception->getMessage();
  190. return false;
  191. }
  192. if ($pay->package) {
  193. $data = [
  194. 'user_id' => $userInfo['id'],
  195. 'out_trade_no' => $outTradeNo,
  196. 'order_no' => $order['order_no'],
  197. 'params' => json_encode($pay, 256),
  198. 'total_fee' => $amount,
  199. 'pay_type' => 10,
  200. 'create_time' => time(),
  201. 'status' => 2,
  202. 'mark' => 1,
  203. ];
  204. if ($this->model->insertGetId($data)) {
  205. $this->error = 2617;
  206. return $pay;
  207. }
  208. }
  209. $this->error = 2618;
  210. return false;
  211. }
  212. /**
  213. * 微信支付
  214. * @param $userInfo
  215. * @param $order
  216. * @param string $scene
  217. * @return false|\Yansongda\Supports\Collection
  218. */
  219. public function wechatPay($userInfo, $order, $scene = 'store')
  220. {
  221. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  222. if ($amount < 0) {
  223. $this->error = 2615;
  224. return false;
  225. }
  226. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  227. // 是否调用过支付,是则用新的支付单号
  228. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  229. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  230. }
  231. $body = isset($order['body']) ? $order['body'] : '';
  232. $type = isset($order['type']) ? $order['type'] : 0;
  233. $payData = [
  234. 'out_trade_no' => $outTradeNo,
  235. 'attach' => "order-{$type}",
  236. 'description' => $body ? $body : '订单支付',
  237. 'amount' => [
  238. 'total' => intval($amount * 100),
  239. 'currency' => 'CNY'
  240. ],
  241. ];
  242. // 创建支付
  243. try {
  244. $pay = $this->createPay($scene, 10);
  245. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  246. if (empty($pay)) {
  247. $this->error = 2616;
  248. return false;
  249. }
  250. $pay = $pay->app($payData);
  251. } catch (\Exception $exception) {
  252. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  253. $this->error = $exception->getMessage();
  254. return false;
  255. }
  256. if ($pay->prepayid) {
  257. $data = [
  258. 'user_id' => $userInfo['id'],
  259. 'out_trade_no' => $outTradeNo,
  260. 'order_no' => $order['order_no'],
  261. 'params' => json_encode($pay, 256),
  262. 'total_fee' => $amount,
  263. 'pay_type' => 10,
  264. 'create_time' => time(),
  265. 'status' => 2,
  266. 'mark' => 1,
  267. ];
  268. if ($this->model->insertGetId($data)) {
  269. $this->error = 2617;
  270. return $pay;
  271. }
  272. }
  273. $this->error = 2618;
  274. return false;
  275. }
  276. /**
  277. * 支付宝支付
  278. * @param $userInfo
  279. * @param $order
  280. * @return bool
  281. */
  282. public function aliPay($userInfo, $order, $scene = 'shop')
  283. {
  284. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  285. if ($amount < 0) {
  286. $this->error = 2615;
  287. return false;
  288. }
  289. // 是否调用过支付,是则用新的支付单号
  290. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  291. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  292. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  293. }
  294. $body = isset($order['body']) ? $order['body'] : '';
  295. $payData = [
  296. 'out_trade_no' => $outTradeNo,
  297. 'subject' => $body ? $body : '订单支付',
  298. 'total_amount' => $amount,
  299. ];
  300. // 创建支付
  301. $pay = $this->createPay($scene, 20);
  302. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  303. if (empty($pay)) {
  304. $this->error = 2619;
  305. return false;
  306. }
  307. $pay = $pay->app($payData);
  308. if ($pay->getStatusCode() == 200) {
  309. $data = [
  310. 'user_id' => $userInfo['id'],
  311. 'out_trade_no' => $outTradeNo,
  312. 'order_no' => $order['order_no'],
  313. 'params' => json_encode($pay, 256),
  314. 'total_fee' => $amount,
  315. 'pay_type' => 20,
  316. 'create_time' => time(),
  317. 'status' => 2,
  318. 'mark' => 1,
  319. ];
  320. if ($this->model->insertGetId($data)) {
  321. $this->error = 2620;
  322. return $pay->getBody()->getContents();
  323. }
  324. }
  325. $this->error = 2621;
  326. return false;
  327. }
  328. /**
  329. * 订单支付回调处理
  330. * @param string $scene 场景 store-购物消费,pay-充值,refund-退款
  331. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  332. * @param array $data 回调数据
  333. * @return bool
  334. */
  335. public function catchNotify($scene, $payType, $data)
  336. {
  337. $outTradeNo = '';
  338. $payTotal = 0;
  339. $transactionId = '';
  340. $payAt = '';
  341. $notifyData = [];
  342. try {
  343. // 微信支付
  344. if ($payType == 10) {
  345. $resource = isset($data['resource']) ? $data['resource'] : [];
  346. $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
  347. $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
  348. if ($tradeStatus != 'SUCCESS') {
  349. $this->error = 2622;
  350. return false;
  351. }
  352. $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
  353. $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
  354. if (empty($outTradeNo)) {
  355. $this->error = 2623;
  356. return false;
  357. }
  358. $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
  359. $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
  360. $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
  361. $notifyData = $ciphertext;
  362. if ($payTotal <= 0) {
  363. $this->error = 2624;
  364. return false;
  365. }
  366. } // 支付宝支付
  367. else if ($payType == 20) {
  368. // TRADE_SUCCESS
  369. $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
  370. if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
  371. $this->error = 2622;
  372. return false;
  373. }
  374. $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
  375. if (empty($outTradeNo)) {
  376. $this->error = 2623;
  377. return false;
  378. }
  379. $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
  380. $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
  381. $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
  382. $notifyData = $data;
  383. if ($payTotal <= 0) {
  384. $this->error = 2624;
  385. return false;
  386. }
  387. }
  388. // 支付信息
  389. $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
  390. ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
  391. ->first();
  392. $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
  393. $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
  394. $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
  395. $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
  396. $payUserId = isset($paymentInfo['user_id']) ? $paymentInfo['user_id'] : 0;
  397. if (empty($paymentInfo) || empty($orderNo) || $payUserId <= 0) {
  398. $this->error = 2625;
  399. return false;
  400. }
  401. // 验证支付状态
  402. if ($status == 1) {
  403. $this->error = 2626;
  404. return false;
  405. }
  406. // 验证支付方式
  407. if ($paymentPayType != $payType) {
  408. $this->error = 2627;
  409. return false;
  410. }
  411. if ($payTotal != $totalFee || $payTotal <= 0) {
  412. $this->error = 2628;
  413. return false;
  414. }
  415. // 删除久远旧记录
  416. $this->model->where(['mark' => 1])->where('create_time', '<=', time() - 60 * 86400)->delete();
  417. // 更新订单数据
  418. DB::beginTransaction();
  419. $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
  420. if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
  421. $this->error = 2632;
  422. DB::rollBack();
  423. return false;
  424. }
  425. /* TODO 订单验证和状态处理 */
  426. $orderInfo = [];
  427. // 商城订单支付
  428. if ($scene == 'store') {
  429. $orderInfo = OrderModel::with(['user','orderGoods'])->where(['order_no' => $orderNo, 'mark' => 1])
  430. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
  431. ->first();
  432. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  433. // 验证订单
  434. if (empty($orderInfo)) {
  435. DB::rollBack();
  436. $this->error = 2629;
  437. return false;
  438. }
  439. // 订单状态
  440. if ($orderStatus != 1) {
  441. DB::rollBack();
  442. $this->error = 2630;
  443. return false;
  444. }
  445. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  446. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  447. $this->error = 2633;
  448. DB::rollBack();
  449. return false;
  450. }
  451. }
  452. // 退款
  453. else if ($scene == 'refund') {
  454. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  455. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'remark', 'refund_remark', 'pay_at as pay_time', 'refund_status as status'])
  456. ->first();
  457. $refundRemark = isset($orderInfo['refund_remark']) ? $orderInfo['refund_remark'] : 'refund_remark';
  458. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  459. // 验证订单
  460. if (empty($orderInfo)) {
  461. DB::rollBack();
  462. $this->error = 2629;
  463. return false;
  464. }
  465. // 订单状态
  466. if ($orderStatus != 2) {
  467. DB::rollBack();
  468. $this->error = 2639;
  469. return false;
  470. }
  471. // 订单打款状态
  472. if ($orderStatus == 1) {
  473. DB::rollBack();
  474. $this->error = 2630;
  475. return false;
  476. }
  477. $updateData = ['refund_status' => 1, 'refund_remark' => $refundRemark ? $refundRemark . ' 已退款成功' : '已退款成功', 'update_time' => time()];
  478. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  479. $this->error = 2633;
  480. DB::rollBack();
  481. return false;
  482. }
  483. }
  484. // TODO 场景业务回调处理
  485. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  486. $this->saveLog("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data]);
  487. switch ($scene) {
  488. case 'store': //
  489. $userInfo = isset($orderInfo['user'])?$orderInfo['user']:[];
  490. $orderGoods = isset($orderInfo['orderGoods'])?$orderInfo['orderGoods']:[];
  491. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  492. $goodsName = isset($orderGoods[0]['goods_name'])?$orderGoods[0]['goods_name']:'';
  493. $data = [
  494. 'user_id'=>$orderUserId,
  495. 'source_order_no'=>$orderNo,
  496. 'type'=> 1,
  497. 'money'=> -$payTotal,
  498. 'after_money'=>$balance,
  499. 'date'=>date('Y-m-d'),
  500. 'create_time'=>time(),
  501. 'remark'=> '商品-'.$goodsName,
  502. 'status'=>1,
  503. 'mark'=>1
  504. ];
  505. if(!AccountLogModel::insertGetId($data)){
  506. Db::rollBack();
  507. $this->error = '付款处理失败';
  508. }
  509. break;
  510. default:
  511. break;
  512. }
  513. $this->error = '回调处理成功';
  514. DB::commit();
  515. return true;
  516. } catch (\Exception $exception) {
  517. $this->error = $exception->getMessage();
  518. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
  519. return false;
  520. }
  521. }
  522. /**
  523. * 日志
  524. * @param $key
  525. * @param $data
  526. */
  527. public function saveLog($key, $data)
  528. {
  529. if(env('APP_DEBUG')){
  530. RedisService::set($key,$data,7200);
  531. }
  532. }
  533. /**
  534. * 退款请求
  535. * @param $order
  536. * @param string $scene
  537. * @return bool
  538. * @throws \Yansongda\Pay\Exception\ContainerException
  539. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  540. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  541. */
  542. public function refund($order, $scene = 'store')
  543. {
  544. $money = isset($order['money']) ? $order['money'] : 0;
  545. $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
  546. $orderNo = isset($order['order_no']) ? $order['order_no'] : '';
  547. $outTradeNo = isset($order['out_trade_no']) ? $order['out_trade_no'] : '';
  548. $transactionId = isset($order['transaction_id']) ? $order['transaction_id'] : '';
  549. $remark = isset($order['remark']) && $order['remark'] ? $order['remark'] : '退款';
  550. $pay = PaymentService::make()->createPay($scene, $payType);
  551. if (empty($pay)) {
  552. DB::rollBack();
  553. $this->error = '创建退款支付失败';
  554. return false;
  555. }
  556. // 保证金退款处理
  557. $refundStatus = false;
  558. switch ($payType) {
  559. case 10: // 微信支付
  560. $data = [
  561. 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
  562. 'out_refund_no' => get_order_num('RF'),
  563. 'transaction_id' => $transactionId,
  564. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  565. 'reason' => $remark,
  566. 'amount' => [
  567. 'refund' => intval($money * 100),
  568. 'total' => intval($money * 100),
  569. 'currency' => 'CNY',
  570. ],
  571. ];
  572. // 请求退款
  573. $pay = $pay->refund($data);
  574. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data, 'pay' => $pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  575. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  576. $refundStatus = true;
  577. } else {
  578. DB::rollBack();
  579. $this->errorData = $data;
  580. $this->error = '微信退款处理失败:'.$pay->message;
  581. return false;
  582. }
  583. break;
  584. case 20: // 支付宝
  585. $data = [
  586. 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
  587. 'trade_no' => $transactionId,
  588. 'refund_amount' => $money,
  589. 'query_options' => ['deposit_back_info'],
  590. 'refund_reason' => $remark,
  591. ];
  592. $payResult = $pay->refund($data);
  593. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  594. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  595. $refundStatus = true;
  596. } else {
  597. $this->errorData = $data;
  598. $this->error = '支付宝退款处理失败:'.$payResult->code;
  599. return false;
  600. }
  601. break;
  602. default:
  603. $this->error = '退款支付类型错误';
  604. return false;
  605. }
  606. $this->error = '退款处理成功';
  607. return $refundStatus;
  608. }
  609. /**
  610. * 分账
  611. * @param $openid
  612. * @param $order
  613. * @param string $scene
  614. * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
  615. * @throws \Yansongda\Pay\Exception\ContainerException
  616. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  617. */
  618. public function profitsharing($openid, $order ,$scene='sharing')
  619. {
  620. $data = [
  621. 'type' => 'PERSONAL_OPENID',
  622. 'account' => $openid,
  623. 'relation_type' => 'SERVICE_PROVIDER'
  624. ];
  625. $pay = PaymentService::make()->createPay($scene, 10);
  626. $plugin = $pay->mergeCommonPlugins([
  627. AddReceiverPlugin::class
  628. ], $data);
  629. // 添加分账插件配置
  630. $pay->pay($plugin, $data);
  631. // 分账数据
  632. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : ''; // 支付交易单号
  633. $profitsharingOrderNo = isset($order['out_order_no'])? $order['out_order_no'] : ''; // 分账单号,非支付单号
  634. $body = isset($order['body'])? $order['body'] : ''; // 分账备注描述
  635. $amount = isset($order['amount'])? $order['amount'] : ''; // 分账金额
  636. $unsplit = isset($order['unsplit'])? $order['unsplit'] : true; // 是否限制只分账一次
  637. $postData = [
  638. 'transaction_id' => $transactionId,
  639. 'out_order_no' => $profitsharingOrderNo,
  640. 'receivers' => [
  641. [
  642. 'type' => 'PERSONAL_OPENID',
  643. 'account' => $openid,
  644. 'amount' => $amount, // 分账金额,单位:分
  645. 'description' => $body, //分账描述
  646. ],
  647. ],
  648. 'unfreeze_unsplit' => $unsplit,
  649. ];
  650. // 创建分账数据
  651. $createPlugin = $pay->mergeCommonPlugins([
  652. CreatePlugin::class
  653. ], $postData);
  654. // 发起分账
  655. $result = $pay->pay($createPlugin, $postData);
  656. var_dump($result);
  657. return $result;
  658. }
  659. }