PaymentService.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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' || $scene == 'sharing') {
  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. $isRevenue = isset($order['is_revenue']) ? $order['is_revenue'] : 0;
  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 * 1000/10),
  172. 'currency' => 'CNY'
  173. ],
  174. 'payer' => [
  175. 'openid' => $openid,
  176. ],
  177. ];
  178. // 订单分账
  179. if($isRevenue==1){
  180. $payData['settle_info'] = [
  181. 'profit_sharing'=> true,
  182. ];
  183. }
  184. // 创建支付
  185. try {
  186. $pay = $this->createPay($scene, 10, 'min');
  187. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  188. if (empty($pay)) {
  189. $this->error = 2616;
  190. return false;
  191. }
  192. $pay = $pay->mini($payData);
  193. } catch (\Exception $exception) {
  194. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  195. $this->error = $exception->getMessage();
  196. return false;
  197. }
  198. if ($pay->package) {
  199. $data = [
  200. 'user_id' => $userInfo['id'],
  201. 'out_trade_no' => $outTradeNo,
  202. 'order_no' => $order['order_no'],
  203. 'params' => json_encode($pay, 256),
  204. 'total_fee' => $amount,
  205. 'pay_type' => 10,
  206. 'create_time' => time(),
  207. 'status' => 2,
  208. 'mark' => 1,
  209. ];
  210. if ($this->model->insertGetId($data)) {
  211. $this->error = 2617;
  212. return $pay;
  213. }
  214. }
  215. $this->error = 2618;
  216. return false;
  217. }
  218. /**
  219. * 微信支付
  220. * @param $userInfo
  221. * @param $order
  222. * @param string $scene
  223. * @return false|\Yansongda\Supports\Collection
  224. */
  225. public function wechatPay($userInfo, $order, $scene = 'store')
  226. {
  227. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  228. if ($amount < 0) {
  229. $this->error = 2615;
  230. return false;
  231. }
  232. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
  233. // 是否调用过支付,是则用新的支付单号
  234. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  235. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  236. }
  237. $body = isset($order['body']) ? $order['body'] : '';
  238. $type = isset($order['type']) ? $order['type'] : 0;
  239. $payData = [
  240. 'out_trade_no' => $outTradeNo,
  241. 'attach' => "order-{$type}",
  242. 'description' => $body ? $body : '订单支付',
  243. 'amount' => [
  244. 'total' => intval($amount * 1000/10),
  245. 'currency' => 'CNY'
  246. ],
  247. ];
  248. // 创建支付
  249. try {
  250. $pay = $this->createPay($scene, 10);
  251. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  252. if (empty($pay)) {
  253. $this->error = 2616;
  254. return false;
  255. }
  256. $pay = $pay->app($payData);
  257. } catch (\Exception $exception) {
  258. RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
  259. $this->error = $exception->getMessage();
  260. return false;
  261. }
  262. if ($pay->prepayid) {
  263. $data = [
  264. 'user_id' => $userInfo['id'],
  265. 'out_trade_no' => $outTradeNo,
  266. 'order_no' => $order['order_no'],
  267. 'params' => json_encode($pay, 256),
  268. 'total_fee' => $amount,
  269. 'pay_type' => 10,
  270. 'create_time' => time(),
  271. 'status' => 2,
  272. 'mark' => 1,
  273. ];
  274. if ($this->model->insertGetId($data)) {
  275. $this->error = 2617;
  276. return $pay;
  277. }
  278. }
  279. $this->error = 2618;
  280. return false;
  281. }
  282. /**
  283. * 支付宝支付
  284. * @param $userInfo
  285. * @param $order
  286. * @return bool
  287. */
  288. public function aliPay($userInfo, $order, $scene = 'shop')
  289. {
  290. $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
  291. if ($amount < 0) {
  292. $this->error = 2615;
  293. return false;
  294. }
  295. // 是否调用过支付,是则用新的支付单号
  296. $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
  297. if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
  298. $outTradeNo = $outTradeNo . date('s') . rand(1, 9);
  299. }
  300. $body = isset($order['body']) ? $order['body'] : '';
  301. $payData = [
  302. 'out_trade_no' => $outTradeNo,
  303. 'subject' => $body ? $body : '订单支付',
  304. 'total_amount' => $amount,
  305. ];
  306. // 创建支付
  307. $pay = $this->createPay($scene, 20);
  308. RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
  309. if (empty($pay)) {
  310. $this->error = 2619;
  311. return false;
  312. }
  313. $pay = $pay->app($payData);
  314. if ($pay->getStatusCode() == 200) {
  315. $data = [
  316. 'user_id' => $userInfo['id'],
  317. 'out_trade_no' => $outTradeNo,
  318. 'order_no' => $order['order_no'],
  319. 'params' => json_encode($pay, 256),
  320. 'total_fee' => $amount,
  321. 'pay_type' => 20,
  322. 'create_time' => time(),
  323. 'status' => 2,
  324. 'mark' => 1,
  325. ];
  326. if ($this->model->insertGetId($data)) {
  327. $this->error = 2620;
  328. return $pay->getBody()->getContents();
  329. }
  330. }
  331. $this->error = 2621;
  332. return false;
  333. }
  334. /**
  335. * 订单支付回调处理
  336. * @param string $scene 场景 store-购物消费,pay-充值,refund-退款
  337. * @param int $payType 支付方式,10-微信支付,20-支付宝支付
  338. * @param array $data 回调数据
  339. * @return bool
  340. */
  341. public function catchNotify($scene, $payType, $data)
  342. {
  343. $outTradeNo = '';
  344. $payTotal = 0;
  345. $transactionId = '';
  346. $payAt = '';
  347. $notifyData = [];
  348. try {
  349. // 微信支付
  350. if ($payType == 10) {
  351. $resource = isset($data['resource']) ? $data['resource'] : [];
  352. $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
  353. $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
  354. if ($tradeStatus != 'SUCCESS') {
  355. $this->error = 2622;
  356. return false;
  357. }
  358. $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
  359. $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
  360. if (empty($outTradeNo)) {
  361. $this->error = 2623;
  362. return false;
  363. }
  364. $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
  365. $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
  366. $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
  367. $notifyData = $ciphertext;
  368. if ($payTotal <= 0) {
  369. $this->error = 2624;
  370. return false;
  371. }
  372. } // 支付宝支付
  373. else if ($payType == 20) {
  374. // TRADE_SUCCESS
  375. $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
  376. if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
  377. $this->error = 2622;
  378. return false;
  379. }
  380. $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
  381. if (empty($outTradeNo)) {
  382. $this->error = 2623;
  383. return false;
  384. }
  385. $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
  386. $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
  387. $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
  388. $notifyData = $data;
  389. if ($payTotal <= 0) {
  390. $this->error = 2624;
  391. return false;
  392. }
  393. }
  394. // 支付信息
  395. $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
  396. ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
  397. ->first();
  398. $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
  399. $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
  400. $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
  401. $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
  402. $payUserId = isset($paymentInfo['user_id']) ? $paymentInfo['user_id'] : 0;
  403. if (empty($paymentInfo) || empty($orderNo) || $payUserId <= 0) {
  404. $this->error = 2625;
  405. return false;
  406. }
  407. // 验证支付状态
  408. if ($status == 1) {
  409. $this->error = 2626;
  410. return false;
  411. }
  412. // 验证支付方式
  413. if ($paymentPayType != $payType) {
  414. $this->error = 2627;
  415. return false;
  416. }
  417. if ($payTotal != $totalFee || $payTotal <= 0) {
  418. $this->error = 2628;
  419. return false;
  420. }
  421. // 删除久远旧记录
  422. $this->model->where(['mark' => 1])->where('create_time', '<=', time() - 60 * 86400)->delete();
  423. // 更新订单数据
  424. DB::beginTransaction();
  425. $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
  426. if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
  427. $this->error = 2632;
  428. DB::rollBack();
  429. return false;
  430. }
  431. /* TODO 订单验证和状态处理 */
  432. $orderInfo = [];
  433. // 商城订单支付
  434. if ($scene == 'store') {
  435. $orderInfo = OrderModel::with(['user','orderGoods'])->where(['order_no' => $orderNo, 'mark' => 1])
  436. ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
  437. ->first();
  438. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  439. // 验证订单
  440. if (empty($orderInfo)) {
  441. DB::rollBack();
  442. $this->error = 2629;
  443. return false;
  444. }
  445. // 订单状态
  446. if ($orderStatus != 1) {
  447. DB::rollBack();
  448. $this->error = 2630;
  449. return false;
  450. }
  451. $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
  452. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  453. $this->error = 2633;
  454. DB::rollBack();
  455. return false;
  456. }
  457. }
  458. // 退款
  459. else if ($scene == 'refund') {
  460. $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
  461. ->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'])
  462. ->first();
  463. $refundRemark = isset($orderInfo['refund_remark']) ? $orderInfo['refund_remark'] : 'refund_remark';
  464. $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
  465. // 验证订单
  466. if (empty($orderInfo)) {
  467. DB::rollBack();
  468. $this->error = 2629;
  469. return false;
  470. }
  471. // 订单状态
  472. if ($orderStatus != 2) {
  473. DB::rollBack();
  474. $this->error = 2639;
  475. return false;
  476. }
  477. // 订单打款状态
  478. if ($orderStatus == 1) {
  479. DB::rollBack();
  480. $this->error = 2630;
  481. return false;
  482. }
  483. $updateData = ['refund_status' => 1, 'refund_remark' => $refundRemark ? $refundRemark . ' 已退款成功' : '已退款成功', 'update_time' => time()];
  484. if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
  485. $this->error = 2633;
  486. DB::rollBack();
  487. return false;
  488. }
  489. }
  490. // TODO 场景业务回调处理
  491. $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
  492. $this->saveLog("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data]);
  493. switch ($scene) {
  494. case 'store': //
  495. $userInfo = isset($orderInfo['user'])?$orderInfo['user']:[];
  496. $orderGoods = isset($orderInfo['orderGoods'])?$orderInfo['orderGoods']:[];
  497. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  498. $goodsName = isset($orderGoods[0]['goods_name'])?$orderGoods[0]['goods_name']:'';
  499. $data = [
  500. 'user_id'=>$orderUserId,
  501. 'source_order_no'=>$orderNo,
  502. 'type'=> 1,
  503. 'money'=> -$payTotal,
  504. 'after_money'=>$balance,
  505. 'date'=>date('Y-m-d'),
  506. 'create_time'=>time(),
  507. 'remark'=> '商品-'.$goodsName,
  508. 'status'=>1,
  509. 'mark'=>1
  510. ];
  511. if(!AccountLogModel::insertGetId($data)){
  512. Db::rollBack();
  513. $this->error = '付款处理失败';
  514. }
  515. break;
  516. default:
  517. break;
  518. }
  519. $this->error = '回调处理成功';
  520. DB::commit();
  521. return true;
  522. } catch (\Exception $exception) {
  523. $this->error = $exception->getMessage();
  524. RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
  525. return false;
  526. }
  527. }
  528. /**
  529. * 日志
  530. * @param $key
  531. * @param $data
  532. */
  533. public function saveLog($key, $data)
  534. {
  535. if(env('APP_DEBUG')){
  536. RedisService::set($key,$data,7200);
  537. }
  538. }
  539. /**
  540. * 退款请求
  541. * @param $order
  542. * @param string $scene
  543. * @return bool
  544. * @throws \Yansongda\Pay\Exception\ContainerException
  545. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  546. * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
  547. */
  548. public function refund($order, $scene = 'store')
  549. {
  550. $money = isset($order['money']) ? $order['money'] : 0;
  551. $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
  552. $orderNo = isset($order['order_no']) ? $order['order_no'] : '';
  553. $outTradeNo = isset($order['out_trade_no']) ? $order['out_trade_no'] : '';
  554. $transactionId = isset($order['transaction_id']) ? $order['transaction_id'] : '';
  555. $remark = isset($order['remark']) && $order['remark'] ? $order['remark'] : '退款';
  556. $pay = PaymentService::make()->createPay($scene, $payType);
  557. if (empty($pay)) {
  558. DB::rollBack();
  559. $this->error = '创建退款支付失败';
  560. return false;
  561. }
  562. // 保证金退款处理
  563. $refundStatus = false;
  564. switch ($payType) {
  565. case 10: // 微信支付
  566. $data = [
  567. 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
  568. 'out_refund_no' => get_order_num('RF'),
  569. 'transaction_id' => $transactionId,
  570. 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
  571. 'reason' => $remark,
  572. 'amount' => [
  573. 'refund' => intval($money * 100),
  574. 'total' => intval($money * 100),
  575. 'currency' => 'CNY',
  576. ],
  577. ];
  578. // 请求退款
  579. $pay = $pay->refund($data);
  580. RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data, 'pay' => $pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  581. if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
  582. $refundStatus = true;
  583. } else {
  584. DB::rollBack();
  585. $this->errorData = $data;
  586. $this->error = '微信退款处理失败:'.$pay->message;
  587. return false;
  588. }
  589. break;
  590. case 20: // 支付宝
  591. $data = [
  592. 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
  593. 'trade_no' => $transactionId,
  594. 'refund_amount' => $money,
  595. 'query_options' => ['deposit_back_info'],
  596. 'refund_reason' => $remark,
  597. ];
  598. $payResult = $pay->refund($data);
  599. RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
  600. if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
  601. $refundStatus = true;
  602. } else {
  603. $this->errorData = $data;
  604. $this->error = '支付宝退款处理失败:'.$payResult->code;
  605. return false;
  606. }
  607. break;
  608. default:
  609. $this->error = '退款支付类型错误';
  610. return false;
  611. }
  612. $this->error = '退款处理成功';
  613. return $refundStatus;
  614. }
  615. /**
  616. * 分账
  617. * @param $openid
  618. * @param $order
  619. * @param string $scene
  620. * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
  621. * @throws \Yansongda\Pay\Exception\ContainerException
  622. * @throws \Yansongda\Pay\Exception\InvalidParamsException
  623. */
  624. public function profitsharing($openid, $order ,$scene='sharing')
  625. {
  626. $data = [
  627. 'type' => 'PERSONAL_OPENID',
  628. 'account' => $openid,
  629. 'relation_type' => 'SERVICE_PROVIDER'
  630. ];
  631. $pay = PaymentService::make()->createPay($scene, 10);
  632. $plugin = $pay->mergeCommonPlugins([
  633. AddReceiverPlugin::class
  634. ], $data);
  635. // 添加分账插件配置
  636. $pay->pay($plugin, $data);
  637. // 分账数据
  638. $transactionId = isset($order['transaction_id'])? $order['transaction_id'] : ''; // 支付交易单号
  639. $profitsharingOrderNo = isset($order['out_order_no'])? $order['out_order_no'] : ''; // 分账单号,非支付单号
  640. $body = isset($order['body'])? $order['body'] : ''; // 分账备注描述
  641. $amount = isset($order['amount'])? $order['amount'] : ''; // 分账金额
  642. $unsplit = isset($order['unsplit'])? $order['unsplit'] : true; // 是否限制只分账一次
  643. $postData = [
  644. 'transaction_id' => $transactionId,
  645. 'out_order_no' => $profitsharingOrderNo,
  646. 'receivers' => [
  647. [
  648. 'type' => 'PERSONAL_OPENID',
  649. 'account' => $openid,
  650. 'amount' => intval($amount*100), // 分账金额,单位:分
  651. 'description' => $body, //分账描述
  652. ],
  653. ],
  654. 'unfreeze_unsplit' => $unsplit,
  655. ];
  656. // 创建分账数据
  657. $createPlugin = $pay->mergeCommonPlugins([
  658. CreatePlugin::class
  659. ], $postData);
  660. // 发起分账
  661. $result = $pay->pay($createPlugin, $postData);
  662. return $result;
  663. }
  664. }