RefundController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\validate\order\ReturnValidate;
  4. use app\controller\Curd;
  5. use app\model\GoodsComponent;
  6. use app\model\MemberAccount;
  7. use app\model\Order;
  8. use app\model\OrderExpress;
  9. use app\model\OrderReturn;
  10. use app\model\OrderSheet;
  11. use app\model\PayDetail;
  12. use Payment\Common\PayException;
  13. use support\Db;
  14. use support\exception\BusinessException;
  15. use support\Log;
  16. use support\Request;
  17. use support\Response;
  18. use Tinywan\Jwt\JwtToken;
  19. use Yansongda\Pay\Pay;
  20. class RefundController extends Curd
  21. {
  22. public function __construct()
  23. {
  24. $this->model = new OrderReturn();
  25. $this->validate = true;
  26. $this->validateClass = new ReturnValidate();
  27. }
  28. public function select(Request $request): Response
  29. {
  30. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  31. $order = $request->get('order', 'desc');
  32. $type = $request->get('type', '');
  33. $field = $field ?? 'order_return_addtimes';
  34. $where['order_return_category'] = '退款';
  35. if ($type == 'today') {
  36. $where['order_return_addtimes'] = [
  37. strtotime(date('Y-m-d') . ' 00:00:00'),
  38. strtotime(date('Y-m-d') . ' 23:59:59')
  39. ];
  40. }
  41. $query = $this->doSelect($where, $field, $order);
  42. return $this->doFormat($query, $format, $limit);
  43. }
  44. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  45. {
  46. $model = $this->model->with([
  47. 'member' => function ($query) {
  48. $query->select('member_id', 'member_mobile');
  49. },
  50. 'cert' => function ($query) {
  51. $query->select('join_cert_member_id', 'member_cert_name');
  52. },
  53. 'order' => function ($query) {
  54. $query->select('order_id', 'order_name');
  55. }
  56. ]);
  57. foreach ($where as $column => $value) {
  58. if (is_array($value)) {
  59. if ($value[0] === 'like' || $value[0] === 'not like') {
  60. $model = $model->where($column, $value[0], "%$value[1]%");
  61. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  62. $model = $model->where($column, $value[0], $value[1]);
  63. } elseif ($value[0] == 'in' && !empty($value[1])) {
  64. $valArr = $value[1];
  65. if (is_string($value[1])) {
  66. $valArr = explode(",", trim($value[1]));
  67. }
  68. $model = $model->whereIn($column, $valArr);
  69. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  70. $valArr = $value[1];
  71. if (is_string($value[1])) {
  72. $valArr = explode(",", trim($value[1]));
  73. }
  74. $model = $model->whereNotIn($column, $valArr);
  75. } elseif ($value[0] == 'null') {
  76. $model = $model->whereNull($column);
  77. } elseif ($value[0] == 'not null') {
  78. $model = $model->whereNotNull($column);
  79. } elseif ($value[0] !== '' || $value[1] !== '') {
  80. $model = $model->whereBetween($column, $value);
  81. }
  82. } else {
  83. $model = $model->where($column, $value);
  84. }
  85. }
  86. if ($field) {
  87. $model = $model->orderBy($field, $order);
  88. }
  89. return $model;
  90. }
  91. public function afterQuery($items)
  92. {
  93. foreach ($items as &$item) {
  94. if (!empty($item['order_return_apply_json']) && is_json($item['order_return_apply_json'])) {
  95. $json = json_decode($item['order_return_apply_json'], true);
  96. $item['order_return_apply_json'] = $json['apply'] ?? '';
  97. }
  98. if (!empty($item['order_return_recharge_json']) && is_json($item['order_return_recharge_json'])) {
  99. $json = json_decode($item['order_return_recharge_json'], true);
  100. $item['order_return_recharge_json'] = $json['change'] ?? '';
  101. }
  102. }
  103. return $items;
  104. }
  105. protected function updateInput(Request $request): array
  106. {
  107. $primary_key = $this->model->getKeyName();
  108. $id = $request->post($primary_key);
  109. $data = $this->inputFilter($request->post());
  110. $model = $this->model->find($id);
  111. if (!$model) {
  112. throw new BusinessException('记录不存在', 2);
  113. }
  114. if (empty($model->order_return_accept_datetimes) && $model->order_return_status == 'PENDING' && $data['order_return_status'] == 'DOING') {
  115. $data['order_return_accept_datetimes'] = date('Y-m-d H:i:s');
  116. }
  117. if (!empty($data['order_return_apply_json'])) {
  118. $data['order_return_apply_json'] = json_encode(['apply' => $data['order_return_apply_json']]);
  119. }
  120. if (!empty($data['order_return_recharge_json'])) {
  121. $data['order_return_recharge_json'] = json_encode(['change' => $data['order_return_recharge_json']]);
  122. }
  123. unset($data[$primary_key]);
  124. return [$id, $data];
  125. }
  126. /**
  127. * @Desc 订单商品详情
  128. * @Author Gorden
  129. * @Date 2024/3/29 8:50
  130. *
  131. * @param Request $request
  132. * @return Response
  133. */
  134. public function sheet(Request $request)
  135. {
  136. $orderId = $request->get('order_id');
  137. $orderSheet = OrderSheet::with([
  138. 'member' => function ($query) {
  139. $query->select('member_id', 'member_mobile');
  140. },
  141. 'goods' => function ($query) {
  142. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify');
  143. },
  144. 'memberInfo',
  145. 'cert',
  146. 'refund'
  147. ])->where('join_sheet_order_id', $orderId)
  148. ->get()
  149. ->toArray();
  150. foreach ($orderSheet as &$item) {
  151. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  152. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  153. $components = GoodsComponent::with('goods')
  154. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  155. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  156. 'goods_component_price', 'goods_component_config_json')
  157. ->get()
  158. ->toArray();
  159. $goodsArr = [];
  160. foreach ($components as $component) {
  161. $configJson = !empty($component['goods_component_config_json']) ? json_decode($component['goods_component_config_json'], true) : [];
  162. if (!empty($component['goods'])) {
  163. $goodsArr[] = [
  164. 'goods_name' => $component['goods']['goods_name'],
  165. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  166. 'nbr' => $configJson['nbr'] ?? 0,
  167. ];
  168. }
  169. }
  170. $item['goods']['components'] = $goodsArr;
  171. }
  172. if (!empty($item['refund'])) {
  173. if (!empty($item['refund']['order_return_apply_json']) && is_json($item['refund']['order_return_apply_json'])) {
  174. $json = json_decode($item['refund']['order_return_apply_json'], true);
  175. $item['refund']['order_return_apply_json'] = $json['reason'] ?? '';
  176. }
  177. if (!empty($item['refund']['order_return_recharge_json']) && is_json($item['refund']['order_return_recharge_json'])) {
  178. $json = json_decode($item['refund']['order_return_recharge_json'], true);
  179. $item['refund']['order_return_recharge_json'] = $json['change'] ?? '';
  180. }
  181. }
  182. }
  183. $order = Order::where('order_id', $orderId)->first();
  184. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  185. $data = [
  186. 'order' => $order,
  187. 'sheet' => $orderSheet,
  188. 'express' => $express
  189. ];
  190. return json_success('', $data);
  191. }
  192. public function customRefund(Request $request)
  193. {
  194. $orderId = $request->post('order_id', '');
  195. $amount = $request->post('refund_amount', 0);
  196. $password = $request->post('refund_password', '');
  197. $remark = $request->post('refund_remark', '');
  198. if (!$orderId || !$amount || !$password) {
  199. return json_fail('参数异常');
  200. }
  201. if ($password != '123456') {
  202. return json_fail('支付密码错误');
  203. }
  204. $order = Order::where('order_id', $orderId)->where('order_status_payment', 'SUCCESS')->first();
  205. if (!$order) {
  206. return json_fail("订单异常");
  207. }
  208. if ($amount > $order->order_amount_pay) {
  209. return json_fail("退款金额不能超过支付金额");
  210. }
  211. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)
  212. ->where('pay_status', 'SUCCESS')
  213. ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DISHES', 'VIP', 'PACKAGE'])
  214. ->get()
  215. ->toArray();
  216. if (empty($payDetail)) {
  217. return json_fail("支付状态异常");
  218. }
  219. $response = [];
  220. Db::beginTransaction();
  221. try {
  222. // 主订单,退款作为优惠入库
  223. $this->updateMainOrderByRefund($order, $amount, $remark);
  224. // return 表记录
  225. if (!OrderReturn::where('join_return_order_id', $orderId)->exists()) {
  226. $returnId = $this->createReturnRecord($order, $amount, $remark);
  227. }else{
  228. //['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']
  229. OrderReturn::where('join_return_order_id', $orderId)->update([
  230. 'order_return_status' => 'DONE',
  231. 'order_return_refund_json'=>json_encode([
  232. 'amount' => $amount,
  233. 'user_id' => JwtToken::getCurrentId(),
  234. 'datetime' => date('Y-m-d H:i:s'),
  235. 'remark' => $remark ?? ''
  236. ])
  237. ]);
  238. }
  239. // 组合支付,退到余额账户
  240. $prepayid = '';
  241. if (count($payDetail) > 1) {
  242. $prepayid = $order->join_order_member_id . '-CASH';
  243. $this->refundToCash($order->join_order_member_id, $amount);
  244. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  245. } else if (count($payDetail) == 1) {
  246. $payDetail0 = $payDetail[0];
  247. $payWay = explode('-', $payDetail0['pay_prepayid']);
  248. if ($payWay[0] == 'WXPAY') {
  249. $prepayid = 'WXPAY';
  250. $response = $this->refundToWx($payDetail0, $returnId, $amount);
  251. } elseif ($payWay[0] == 'ALIPAY') {
  252. $prepayid = 'WXPAY';
  253. $response = $this->refundToAlipay($payDetail0, $amount);
  254. } elseif ($payWay[0] == 'MONEY') {
  255. $prepayid = 'MONEY';
  256. $response = $this->refundToCash($payDetail0, $amount);
  257. } elseif (isset($payWay[1]) && $payWay[1] == 'CASH') {
  258. $prepayid = $order->join_order_member_id . '-CASH';
  259. $this->refundToCash($order->join_order_member_id, $amount);
  260. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  261. } elseif (isset($payWay['1']) && $payWay[1] == 'CARD') {
  262. $prepayid = $order->join_order_member_id . '-CASH';
  263. $this->refundToCard($order->join_order_member_id, $amount);
  264. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  265. }
  266. }
  267. // payDetail 表记录
  268. $this->createReturnPayDetail($order, $prepayid, $amount, $response);
  269. Db::commit();
  270. return json_success('success');
  271. } catch (BusinessException $e) {
  272. Db::rollBack();
  273. return json_fail($e->getMessage());
  274. } catch (\Exception $e) {
  275. Db::rollBack();
  276. return json_fail("退款失败");
  277. }
  278. }
  279. /**
  280. * @Desc 退款到余额
  281. * @Author Gorden
  282. * @Date 2024/8/20 11:54
  283. *
  284. * @param $memberId
  285. * @param $amount
  286. * @return void
  287. * @throws BusinessException
  288. */
  289. private function refundToCash($memberId, $amount)
  290. {
  291. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'CASH')->first();
  292. if (!$account) {
  293. throw new BusinessException("余额账户异常");
  294. }
  295. $account->member_account_surplus = $account->member_account_surplus + $amount;
  296. $account->save();
  297. }
  298. /**
  299. * @Desc 退款到储蓄卡
  300. * @Author Gorden
  301. * @Date 2024/8/20 14:47
  302. *
  303. * @param $memberId
  304. * @param $amount
  305. * @return void
  306. * @throws BusinessException
  307. */
  308. private function refundToCard($cardNbr, $amount)
  309. {
  310. $account = MemberAccount::where('member_account_nbr', $cardNbr)->where('member_account_classify', 'CARD')->first();
  311. if (!$account) {
  312. throw new BusinessException("储值卡账户异常");
  313. }
  314. $account->member_account_surplus = $account->member_account_surplus + $amount;
  315. $account->save();
  316. }
  317. /**
  318. * @Desc
  319. * @Author Gorden
  320. * @Date 2024/8/20 14:17
  321. *
  322. * @param $params
  323. * @param $returnId
  324. * @param $amount
  325. * @return mixed
  326. * @throws BusinessException
  327. * @throws \Yansongda\Pay\Exceptions\GatewayException
  328. * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
  329. * @throws \Yansongda\Pay\Exceptions\InvalidSignException
  330. */
  331. private function refundToWx($params, $returnId, $amount)
  332. {
  333. try {
  334. $data = [
  335. 'type' => 'app',
  336. 'out_trade_no' => $params['join_pay_order_id'],
  337. 'out_refund_no' => $returnId,
  338. 'total_fee' => $params['pay_amount'] * 100,
  339. 'refund_fee' => $amount * 100,
  340. 'refund_desc' => '退款',
  341. ];
  342. $res = Pay::wechat(config('payment.wxpay'))->refund($data);
  343. $resArray = json_decode($res, true);
  344. if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') {
  345. Log::channel('pay')->error('WXPAY_REFUND_FAIL', $resArray);
  346. throw new BusinessException("退款失败");
  347. }
  348. return $resArray;
  349. } catch (\Exception $e) {
  350. throw new BusinessException("退款失败");
  351. }
  352. }
  353. /**
  354. * @Desc 支付宝退款
  355. * @Author Gorden
  356. * @Date 2024/8/20 14:40
  357. *
  358. * @param $params
  359. * @param $amount
  360. * @return mixed
  361. * @throws BusinessException
  362. */
  363. private function refundToAlipay($params, $amount)
  364. {
  365. $data = [
  366. 'out_trade_no' => $params['join_pay_order_id'],
  367. 'refund_amount' => $amount,
  368. ];
  369. try {
  370. $res = Pay::alipay(config('payment.alipay'))->refund($data);
  371. $resArray = json_decode($res, true);
  372. if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
  373. Log::channel('pay')->error('ALIPAY_REFUND_FAIL', $resArray);
  374. throw new BusinessException("退款失败");
  375. }
  376. return $resArray;
  377. } catch (\Exception $e) {
  378. throw new BusinessException("退款失败");
  379. }
  380. }
  381. /**
  382. * @Desc 更新主订单
  383. * @Author Gorden
  384. * @Date 2024/8/20 14:56
  385. *
  386. * @param $order
  387. * @param $amount
  388. * @param $remark
  389. * @return void
  390. * @throws BusinessException
  391. */
  392. private function updateMainOrderByRefund($order, $amount, $remark)
  393. {
  394. $orderDiscountJson = [];
  395. if (!empty($order->order_discount_json)) {
  396. $orderDiscountJson = json_decode($order->order_discount_json, true);
  397. }
  398. try {
  399. $orderDiscountJson[date('YH:i:s H:i:s')] = [
  400. 'coupon_id' => null,
  401. 'coupon_value' => $amount,
  402. 'coupon_classify' => '退款',
  403. 'coupon_detail_id' => [$remark]
  404. ];
  405. $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
  406. $order->order_amount_pay = $order->order_amount_pay - $amount;
  407. $order->save();
  408. } catch (\Exception $e) {
  409. throw new BusinessException("退款失败");
  410. }
  411. }
  412. /**
  413. * @Desc
  414. * @Author Gorden
  415. * @Date 2024/8/20 13:51
  416. *
  417. * @param $order
  418. * @return int
  419. * @throws BusinessException
  420. */
  421. private function createReturnRecord($order, $amount, $remark)
  422. {
  423. try {
  424. return OrderReturn::insertGetId([
  425. 'join_order_return_user_id' => JwtToken::getCurrentId(),
  426. 'join_return_member_id' => $order->join_order_member_id,
  427. 'join_return_order_id' => $order->order_id,
  428. 'order_return_status' => 'DONE',
  429. 'order_return_category' => '退款',
  430. 'order_return_apply_datetime' => date('Y-m-d H:i:s'),
  431. 'order_return_apply_json' => json_encode(['reason' => '后台自定义退款']),
  432. 'order_return_accept_datetime' => date('Y-m-d H:i:s'),
  433. 'order_return_refund_json' => json_encode(['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']),
  434. 'order_return_addtimes' => time()
  435. ]);
  436. } catch (\Exception $e) {
  437. throw new BusinessException("创建退款信息失败");
  438. }
  439. }
  440. private function createReturnPayDetail($order, $prepayid, $amount, $response = [])
  441. {
  442. try {
  443. return PayDetail::insert([
  444. 'join_pay_member_id' => $order->join_order_member_id,
  445. 'join_pay_order_id' => $order->order_groupby,
  446. 'pay_status' => 'SUCCESS',
  447. 'pay_category' => 'REFUND',
  448. 'pay_amount' => $amount,
  449. 'pay_paytimes' => date('Y-m-d H:i:s'),
  450. 'pay_prepayid' => $prepayid,
  451. 'pay_json_request' => json_encode(['order_id' => $order->order_id]),
  452. 'pay_json_response' => json_encode($response),
  453. 'pay_addtimes' => time()
  454. ]);
  455. } catch (\Exception $e) {
  456. }
  457. }
  458. }