RefundController.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\member\MemberService;
  4. use app\admin\validate\order\ReturnValidate;
  5. use app\controller\Curd;
  6. use app\model\CouponDetail;
  7. use app\model\GoodsComponent;
  8. use app\model\MemberAccount;
  9. use app\model\Order;
  10. use app\model\OrderExpress;
  11. use app\model\OrderReturn;
  12. use app\model\OrderSheet;
  13. use app\model\PayDetail;
  14. use app\model\SysUser;
  15. use Payment\Common\PayException;
  16. use support\Db;
  17. use support\exception\BusinessException;
  18. use support\Log;
  19. use support\Request;
  20. use support\Response;
  21. use Tinywan\Jwt\JwtToken;
  22. use Webman\Event\Event;
  23. use Yansongda\Pay\Pay;
  24. class RefundController extends Curd
  25. {
  26. public function __construct()
  27. {
  28. $this->model = new OrderReturn();
  29. $this->validate = true;
  30. $this->validateClass = new ReturnValidate();
  31. }
  32. public function select(Request $request): Response
  33. {
  34. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  35. $order = $request->get('order', 'desc');
  36. $type = $request->get('type', '');
  37. $field = $field ?? 'order_return_addtimes';
  38. $where['order_return_category'] = '退款';
  39. if (!empty($where['order_return_addtimes'])) {
  40. $where['order_return_addtimes'][0] = strtotime($where['order_return_addtimes'][0]);
  41. $where['order_return_addtimes'][1] = strtotime($where['order_return_addtimes'][1]);
  42. }
  43. if ($type == 'today') {
  44. $where['order_return_addtimes'] = [
  45. strtotime(date('Y-m-d') . ' 00:00:00'),
  46. strtotime(date('Y-m-d') . ' 23:59:59')
  47. ];
  48. }
  49. $query = $this->doSelect($where, $field, $order);
  50. return $this->doFormat($query, $format, $limit);
  51. }
  52. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  53. {
  54. $model = $this->model->with([
  55. 'member' => function ($query) {
  56. $query->select('member_id', 'member_mobile');
  57. },
  58. 'cert' => function ($query) {
  59. $query->select('join_cert_member_id', 'member_cert_name');
  60. },
  61. 'order' => function ($query) {
  62. $query->select('order_id', 'order_name');
  63. }
  64. ]);
  65. foreach ($where as $column => $value) {
  66. if (is_array($value)) {
  67. if ($value[0] === 'like' || $value[0] === 'not like') {
  68. $model = $model->where($column, $value[0], "%$value[1]%");
  69. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  70. $model = $model->where($column, $value[0], $value[1]);
  71. } elseif ($value[0] == 'in' && !empty($value[1])) {
  72. $valArr = $value[1];
  73. if (is_string($value[1])) {
  74. $valArr = explode(",", trim($value[1]));
  75. }
  76. $model = $model->whereIn($column, $valArr);
  77. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  78. $valArr = $value[1];
  79. if (is_string($value[1])) {
  80. $valArr = explode(",", trim($value[1]));
  81. }
  82. $model = $model->whereNotIn($column, $valArr);
  83. } elseif ($value[0] == 'null') {
  84. $model = $model->whereNull($column);
  85. } elseif ($value[0] == 'not null') {
  86. $model = $model->whereNotNull($column);
  87. } elseif ($value[0] !== '' || $value[1] !== '') {
  88. $model = $model->whereBetween($column, $value);
  89. }
  90. } else {
  91. $model = $model->where($column, $value);
  92. }
  93. }
  94. if ($field) {
  95. $model = $model->orderBy($field, $order);
  96. }
  97. return $model;
  98. }
  99. public function afterQuery($items)
  100. {
  101. foreach ($items as &$item) {
  102. if (!empty($item['order'])) {
  103. $orderSheet = OrderSheet::with([
  104. 'goods' => function ($query) {
  105. $query->select('goods_id', 'goods_name');
  106. }
  107. ])->select('join_sheet_order_id', 'join_sheet_goods_id')
  108. ->where('join_sheet_order_id', $item['order']->order_id)
  109. ->get()
  110. ->toArray();
  111. $goodsName = !empty($orderSheet) ? $orderSheet[0]['goods']['goods_name'] : '';
  112. if (count($orderSheet) > 1) {
  113. $goodsName .= ' 等';
  114. }
  115. $item['goods_name'] = $goodsName;
  116. }
  117. if (!empty($item['order_return_apply_json']) && is_json($item['order_return_apply_json'])) {
  118. $json = json_decode($item['order_return_apply_json'], true);
  119. $item['order_return_apply_json'] = $json['apply'] ?? '';
  120. }
  121. if (!empty($item['order_return_recharge_json']) && is_json($item['order_return_recharge_json'])) {
  122. $json = json_decode($item['order_return_recharge_json'], true);
  123. $item['order_return_recharge_json'] = $json['change'] ?? '';
  124. }
  125. if (!empty($item['order_return_refund_json']) && is_json($item['order_return_refund_json'])) {
  126. $returnRefundJson = json_decode($item['order_return_refund_json'], true);
  127. if (!empty($returnRefundJson['user_id'])) {
  128. $item['userName'] = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  129. }
  130. }
  131. }
  132. return $items;
  133. }
  134. protected function updateInput(Request $request): array
  135. {
  136. $primary_key = $this->model->getKeyName();
  137. $id = $request->post($primary_key);
  138. $data = $this->inputFilter($request->post());
  139. $model = $this->model->find($id);
  140. if (!$model) {
  141. throw new BusinessException('记录不存在', 2);
  142. }
  143. if (empty($model->order_return_accept_datetimes) && $model->order_return_status == 'PENDING' && $data['order_return_status'] == 'DOING') {
  144. $data['order_return_accept_datetimes'] = date('Y-m-d H:i:s');
  145. }
  146. if (!empty($data['order_return_apply_json'])) {
  147. $data['order_return_apply_json'] = json_encode(['apply' => $data['order_return_apply_json']]);
  148. }
  149. if (!empty($data['order_return_recharge_json'])) {
  150. $data['order_return_recharge_json'] = json_encode(['change' => $data['order_return_recharge_json']]);
  151. }
  152. unset($data[$primary_key]);
  153. return [$id, $data];
  154. }
  155. /**
  156. * @Desc 订单商品详情
  157. * @Author Gorden
  158. * @Date 2024/3/29 8:50
  159. *
  160. * @param Request $request
  161. * @return Response
  162. */
  163. public function sheet(Request $request)
  164. {
  165. $orderId = $request->get('order_id');
  166. $orderSheet = OrderSheet::with([
  167. 'member' => function ($query) {
  168. $query->select('member_id', 'member_mobile','join_member_role_id','member_is_owner','member_is_vip','member_is_partner','member_is_referrer');
  169. },
  170. 'goods' => function ($query) {
  171. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify');
  172. },
  173. 'sku' => function ($query) {
  174. $query->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  175. },
  176. 'memberInfo',
  177. 'cert',
  178. 'refund'
  179. ])->where('join_sheet_order_id', $orderId)
  180. ->get()
  181. ->toArray();
  182. $member = [];
  183. $cert = [];
  184. $memberInfo = [];
  185. foreach ($orderSheet as &$item) {
  186. if (isset($item['member']) && empty($member)) {
  187. $member = $item['member'];
  188. $member['level'] = MemberService::getRoleName($member['join_member_role_id'] ?? '');
  189. }
  190. if (isset($item['cert']) && empty($cert)) {
  191. $cert = $item['cert'];
  192. }
  193. if (isset($item['member_info']) && empty($memberInfo)) {
  194. $memberInfo = $item['member_info'];
  195. $memberInfo['member_info_nickname'] = $memberInfo['member_info_nickname'] ?? MemberService::getMemberNickname($member['member_mobile'] ?? '');
  196. $memberInfo['member_info_headimg'] = MemberService::getAvatarUrl($memberInfo['member_info_headimg'] ?? '');
  197. }
  198. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  199. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  200. $components = GoodsComponent::with('goods')
  201. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  202. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  203. 'goods_component_price')
  204. ->get()
  205. ->toArray();
  206. $goodsArr = [];
  207. foreach ($components as $component) {
  208. $configJson = !empty($component['goods_component_config_json']) ? json_decode($component['goods_component_config_json'], true) : [];
  209. if (!empty($component['goods'])) {
  210. $goodsArr[] = [
  211. 'goods_name' => $component['goods']['goods_name'],
  212. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  213. 'nbr' => $configJson['nbr'] ?? 0,
  214. ];
  215. }
  216. }
  217. $item['goods']['components'] = $goodsArr;
  218. }
  219. if (!empty($item['sku'])) {
  220. if (!empty($item['sku']['goods_sku_specs_json'])) {
  221. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  222. $skuName = '';
  223. foreach ($specsJson as $specsKey => $skuSpecs) {
  224. if (is_array($skuSpecs)) {
  225. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  226. } else {
  227. $skuName = $skuName . ' ' . $skuSpecs . ';';
  228. }
  229. }
  230. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  231. }
  232. }
  233. if (!empty($item['refund'])) {
  234. if (!empty($item['refund']['order_return_apply_json']) && is_json($item['refund']['order_return_apply_json'])) {
  235. $json = json_decode($item['refund']['order_return_apply_json'], true);
  236. $item['refund']['order_return_apply_json'] = $json['reason'] ?? '';
  237. }
  238. if (!empty($item['refund']['order_return_recharge_json']) && is_json($item['refund']['order_return_recharge_json'])) {
  239. $json = json_decode($item['refund']['order_return_recharge_json'], true);
  240. $item['refund']['order_return_recharge_json'] = $json['change'] ?? '';
  241. }
  242. }
  243. }
  244. $order = Order::where('order_id', $orderId)->first();
  245. $return = OrderReturn::where('join_return_order_id', $orderId)->first();
  246. if (!empty($return->order_return_refund_json)) {
  247. $returnRefundJson = json_decode($return->order_return_refund_json, true);
  248. if (!empty($returnRefundJson['user_id'])) {
  249. $return->userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  250. }
  251. }
  252. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  253. $payDetails = PayDetail::where('join_pay_order_id',$order->order_groupby)
  254. ->whereJsonContains('join_pay_object_json->order_id',$orderId)
  255. ->where('pay_status','SUCCESS')
  256. ->where('pay_category', '<>', 'REFUND')
  257. ->get()
  258. ->toArray();
  259. if (count($payDetails) > 1){
  260. $order->pay_category = 'CONSTITUTE';
  261. }
  262. $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : [];
  263. if (!empty($payDetail) && !empty($payDetail['pay_prepayid'])) {
  264. $categoryArray = explode('-', $payDetail['pay_prepayid']);
  265. if (isset($categoryArray[1])) {
  266. $payDetail['pay_category'] = $categoryArray[1];
  267. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  268. $payDetail['pay_category'] = $categoryArray[0];
  269. }
  270. }
  271. $data = [
  272. 'member' => $member,
  273. 'cert' => $cert,
  274. 'member_info' => $memberInfo,
  275. 'order' => $order,
  276. 'refund' => $return,
  277. 'sheet' => $orderSheet,
  278. 'express' => $express,
  279. 'payDetail' => json_decode(json_encode($payDetail)),
  280. 'payDetails' => json_decode(json_encode($payDetails))
  281. ];
  282. return json_success('', $data);
  283. }
  284. public function customRefund(Request $request)
  285. {
  286. $orderId = $request->post('order_id', '');
  287. $amount = $request->post('refund_amount', 0);
  288. $password = $request->post('refund_password', '');
  289. $remark = $request->post('refund_remark', '');
  290. if (!$orderId || !$amount || !$password) {
  291. return json_fail('参数异常');
  292. }
  293. if ($password != '123456') {
  294. return json_fail('支付密码错误');
  295. }
  296. $order = Order::where('order_id', $orderId)->where('order_status_payment', 'SUCCESS')->first();
  297. if (!$order) {
  298. return json_fail("订单异常");
  299. }
  300. if ($amount > $order->order_amount_pay) {
  301. return json_fail("退款金额不能超过支付金额");
  302. }
  303. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)
  304. ->where('pay_status', 'SUCCESS')
  305. ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DISHES', 'VIP', 'PACKAGE'])
  306. ->get()
  307. ->toArray();
  308. if (empty($payDetail)) {
  309. return json_fail("支付状态异常");
  310. }
  311. $refundPayIds = array_column($payDetail, 'pay_id');
  312. $response = [];
  313. Db::beginTransaction();
  314. try {
  315. // 全额退款,检查优惠券,恢复可使用
  316. if (sprintf("%.2f", $amount) == sprintf("%.2f", $order->order_amount_pay)) {
  317. if (!empty($order->order_discount_json)) {
  318. $discountJson = json_decode($order->order_discount_json, true);
  319. foreach ($discountJson as $item) {
  320. if (empty($item['coupon_id'])) {
  321. continue;
  322. }
  323. // 是否有其他订单一起使用优惠券
  324. if (!Order::where('order_groupby', $order->order_groupby)->where('order_id', '<>', $order->order_id)->where('order_is_complete', '<>', 'R')->exists()) {
  325. foreach ($item['coupon_detail_id'] as $detailId) {
  326. CouponDetail::where('coupon_detail_id', $detailId)->update([
  327. 'coupon_detail_status' => 'ACTIVED',
  328. 'coupon_detail_used_datetime' => ''
  329. ]);
  330. }
  331. }
  332. }
  333. }
  334. }
  335. // 主订单,退款作为优惠入库
  336. $this->updateMainOrderByRefund($order, $amount, $remark);
  337. // return 表记录
  338. $return = OrderReturn::where('join_return_order_id', $orderId)->first();
  339. if (empty($return)) {
  340. $returnId = $this->createReturnRecord($order, $amount, $remark);
  341. } else {
  342. $returnId = $return->orders_return_id;
  343. //['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']
  344. OrderReturn::where('join_return_order_id', $orderId)->update([
  345. 'order_return_status' => 'DONE',
  346. 'order_return_refund_json' => json_encode([
  347. 'amount' => $amount,
  348. 'user_id' => JwtToken::getCurrentId(),
  349. 'datetime' => date('Y-m-d H:i:s'),
  350. 'remark' => $remark ?? ''
  351. ])
  352. ]);
  353. }
  354. // 组合支付,退到余额账户
  355. $prepayid = '';
  356. if (count($payDetail) > 1) {
  357. $prepayid = $order->join_order_member_id . '-CASH';
  358. $this->refundToCash($order->join_order_member_id, $amount);
  359. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  360. } else if (count($payDetail) == 1) {
  361. $payDetail0 = $payDetail[0];
  362. $payWay = explode('-', $payDetail0['pay_prepayid']);
  363. if ($payWay[0] == 'WXPAY') {
  364. $prepayid = 'WXPAY';
  365. $response = $this->refundToWx($payDetail0, $returnId, $amount);
  366. } elseif ($payWay[0] == 'ALIPAY') {
  367. $prepayid = 'ALIPAY';
  368. $payDetail0['order_id'] = $order->order_id;
  369. $response = $this->refundToAlipay($payDetail0, $amount);
  370. } elseif ($payWay[0] == 'MONEY') {
  371. $prepayid = 'MONEY';
  372. $response = $this->refundToCash($payDetail0, $amount);
  373. } elseif (isset($payWay[1]) && $payWay[1] == 'CASH') {
  374. $prepayid = $order->join_order_member_id . '-CASH';
  375. $this->refundToCash($order->join_order_member_id, $amount);
  376. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  377. } elseif (isset($payWay[1]) && $payWay[1] == 'WELFARE') {
  378. $prepayid = $order->join_order_member_id . '-WELFARE';
  379. $this->refundToWelfare($order->join_order_member_id, $amount);
  380. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  381. } elseif (isset($payWay[1]) && $payWay[1] == 'VIP') {
  382. $prepayid = $order->join_order_member_id . '-VIP';
  383. $this->refundToVIP($order->join_order_member_id, $amount);
  384. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  385. } elseif (isset($payWay['1']) && $payWay[1] == 'CARD') {
  386. $prepayid = $order->join_order_member_id . '-CARD';
  387. $this->refundToCard($order->join_order_member_id, $amount);
  388. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  389. } elseif ($payWay[0] == 'OFFLINE') {
  390. $prepayid = 'OFFLINE';
  391. $response = [];
  392. } elseif ($payWay[0] == 'OFFLINE_ALIPAY') {
  393. $prepayid = 'OFFLINE_ALIPAY';
  394. $response = [];
  395. } elseif ($payWay[0] == 'OFFLINE_WXPAY') {
  396. $prepayid = 'OFFLINE_WXPAY';
  397. $response = [];
  398. }
  399. }
  400. // payDetail 表记录
  401. $this->createReturnPayDetail($order, $refundPayIds, $prepayid, $amount, $response);
  402. Db::commit();
  403. // 退款入收支
  404. $params['orderId'] = $orderId;
  405. $params['type'] = 'refund';
  406. Event::dispatch('statistics.inout.out',$params);
  407. return json_success('success');
  408. } catch (BusinessException $e) {
  409. Db::rollBack();
  410. Log::info("退款失败", ['msg' => $e->getMessage()]);
  411. return json_fail($e->getMessage());
  412. } catch (\Exception $e) {
  413. Db::rollBack();
  414. Log::info("退款失败", ['msg' => $e->getMessage()]);
  415. return json_fail("退款失败");
  416. }
  417. }
  418. /**
  419. * @Desc 退款到余额
  420. * @Author Gorden
  421. * @Date 2024/8/20 11:54
  422. *
  423. * @param $memberId
  424. * @param $amount
  425. * @return void
  426. * @throws BusinessException
  427. */
  428. private function refundToCash($memberId, $amount)
  429. {
  430. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'CASH')->first();
  431. if (!$account) {
  432. throw new BusinessException("余额账户异常");
  433. }
  434. $account->member_account_surplus = $account->member_account_surplus + $amount;
  435. $account->save();
  436. }
  437. /**
  438. * @Desc 退款到福利账户
  439. * @Author Gorden
  440. * @Date 2024/9/20 17:09
  441. *
  442. * @param $memberId
  443. * @param $amount
  444. * @return void
  445. * @throws BusinessException
  446. */
  447. private function refundToWelfare($memberId, $amount)
  448. {
  449. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'WELFARE')->first();
  450. if (!$account) {
  451. throw new BusinessException("余额账户异常");
  452. }
  453. $account->member_account_surplus = $account->member_account_surplus + $amount;
  454. $account->save();
  455. }
  456. /**
  457. * @Desc 退款到VIP账户
  458. * @Author Gorden
  459. * @Date 2024/9/20 17:12
  460. *
  461. * @param $memberId
  462. * @param $amount
  463. * @return void
  464. * @throws BusinessException
  465. */
  466. private function refundToVIP($memberId, $amount)
  467. {
  468. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'VIP')->first();
  469. if (!$account) {
  470. throw new BusinessException("余额账户异常");
  471. }
  472. $account->member_account_surplus = $account->member_account_surplus + $amount;
  473. $account->save();
  474. }
  475. /**
  476. * @Desc 退款到储蓄卡
  477. * @Author Gorden
  478. * @Date 2024/8/20 14:47
  479. *
  480. * @param $memberId
  481. * @param $amount
  482. * @return void
  483. * @throws BusinessException
  484. */
  485. private function refundToCard($cardNbr, $amount)
  486. {
  487. $account = MemberAccount::where('member_account_nbr', $cardNbr)->where('member_account_classify', 'CARD')->first();
  488. if (!$account) {
  489. throw new BusinessException("储值卡账户异常");
  490. }
  491. $account->member_account_surplus = $account->member_account_surplus + $amount;
  492. $account->save();
  493. }
  494. /**
  495. * @Desc
  496. * @Author Gorden
  497. * @Date 2024/8/20 14:17
  498. *
  499. * @param $params
  500. * @param $returnId
  501. * @param $amount
  502. * @return mixed
  503. * @throws BusinessException
  504. * @throws \Yansongda\Pay\Exceptions\GatewayException
  505. * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
  506. * @throws \Yansongda\Pay\Exceptions\InvalidSignException
  507. */
  508. private function refundToWx($params, $returnId, $amount)
  509. {
  510. try {
  511. $data = [
  512. 'type' => 'app',
  513. 'out_trade_no' => $params['join_pay_order_id'],
  514. 'out_refund_no' => $returnId,
  515. 'total_fee' => $params['pay_amount'] * 100,
  516. 'refund_fee' => $amount * 100,
  517. 'refund_desc' => '退款',
  518. ];
  519. $res = Pay::wechat(config('payment.wxpay'))->refund($data);
  520. $resArray = json_decode($res, true);
  521. if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') {
  522. Log::channel('pay')->error('WXPAY_REFUND_FAIL', $resArray);
  523. throw new BusinessException("退款失败");
  524. }
  525. return $resArray;
  526. } catch (\Exception $e) {
  527. throw new BusinessException("退款失败");
  528. }
  529. }
  530. /**
  531. * @Desc 支付宝退款
  532. * @Author Gorden
  533. * @Date 2024/8/20 14:40
  534. *
  535. * @param $params
  536. * @param $amount
  537. * @return mixed
  538. * @throws BusinessException
  539. */
  540. private function refundToAlipay($params, $amount)
  541. {
  542. $data = [
  543. 'out_trade_no' => $params['join_pay_order_id'],
  544. 'refund_amount' => $amount,
  545. 'out_request_no' => $params['order_id']
  546. ];
  547. Log::error("支付宝退款参数", $data);
  548. try {
  549. $res = Pay::alipay(config('payment.alipay'))->refund($data);
  550. $resArray = json_decode($res, true);
  551. if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
  552. Log::channel('pay')->error('ALIPAY_REFUND_FAIL', $resArray);
  553. throw new BusinessException("退款失败");
  554. }
  555. return $resArray;
  556. } catch (\Exception $e) {
  557. Log::error("支付宝退款失败", ['msg' => $e->getMessage()]);
  558. throw new BusinessException("退款失败");
  559. }
  560. }
  561. /**
  562. * @Desc 更新主订单
  563. * @Author Gorden
  564. * @Date 2024/8/20 14:56
  565. *
  566. * @param $order
  567. * @param $amount
  568. * @param $remark
  569. * @return void
  570. * @throws BusinessException
  571. */
  572. private function updateMainOrderByRefund($order, $amount, $remark)
  573. {
  574. $orderDiscountJson = [];
  575. if (!empty($order->order_discount_json)) {
  576. $orderDiscountJson = json_decode($order->order_discount_json, true);
  577. }
  578. try {
  579. $orderDiscountJson[date('Y-m-d H:i:s')] = [
  580. 'coupon_id' => null,
  581. 'coupon_value' => $amount,
  582. 'coupon_classify' => '退款',
  583. 'coupon_detail_id' => [$remark]
  584. ];
  585. $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
  586. $order->order_is_complete = 'R';
  587. $order->order_category = 'RETURN';
  588. // $order->order_amount_pay = $order->order_amount_pay - $amount;
  589. $order->save();
  590. } catch (\Exception $e) {
  591. throw new BusinessException("退款失败");
  592. }
  593. }
  594. /**
  595. * @Desc
  596. * @Author Gorden
  597. * @Date 2024/8/20 13:51
  598. *
  599. * @param $order
  600. * @return int
  601. * @throws BusinessException
  602. */
  603. private function createReturnRecord($order, $amount, $remark)
  604. {
  605. try {
  606. return OrderReturn::insertGetId([
  607. 'join_order_return_user_id' => JwtToken::getCurrentId(),
  608. 'join_return_member_id' => $order->join_order_member_id,
  609. 'join_return_order_id' => $order->order_id,
  610. 'order_return_status' => 'DONE',
  611. 'order_return_category' => '退款',
  612. 'order_return_apply_datetime' => date('Y-m-d H:i:s'),
  613. 'order_return_apply_json' => json_encode(['reason' => '后台自定义退款']),
  614. 'order_return_accept_datetime' => date('Y-m-d H:i:s'),
  615. 'order_return_refund_json' => json_encode(['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']),
  616. 'order_return_addtimes' => time()
  617. ]);
  618. } catch (\Exception $e) {
  619. throw new BusinessException("创建退款信息失败");
  620. }
  621. }
  622. private function createReturnPayDetail($order, $refundPayIds, $prepayid, $amount, $response = [])
  623. {
  624. try {
  625. return PayDetail::insert([
  626. 'join_pay_member_id' => $order->join_order_member_id,
  627. 'join_pay_order_id' => $order->order_groupby,
  628. 'pay_status' => 'SUCCESS',
  629. 'pay_category' => 'REFUND',
  630. 'pay_amount' => $amount,
  631. 'pay_paytimes' => date('Y-m-d H:i:s'),
  632. 'pay_prepayid' => $prepayid,
  633. 'join_pay_object_json' => json_encode(['order_id' => $order->order_id, 'refund_pay_ids' => $refundPayIds]),
  634. 'pay_json_request' => json_encode(['order_id' => $order->order_id]),
  635. 'pay_json_response' => json_encode($response),
  636. 'pay_addtimes' => time()
  637. ]);
  638. } catch (\Exception $e) {
  639. }
  640. }
  641. }