PaymentService.php 28 KB

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