RefundController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. OrderReturn::where('join_return_order_id', $orderId)->update([
  229. 'order_return_status' => 'DONE',
  230. 'order_return_refund_json'=>json_encode([
  231. 'amount' => $amount,
  232. 'user_id' => JwtToken::getCurrentId(),
  233. 'datetime' => date('Y-m-d H:i:s')
  234. ])
  235. ]);
  236. }
  237. // 组合支付,退到余额账户
  238. $prepayid = '';
  239. if (count($payDetail) > 1) {
  240. $prepayid = $order->join_order_member_id . '-CASH';
  241. $this->refundToCash($order->join_order_member_id, $amount);
  242. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  243. } else if (count($payDetail) == 1) {
  244. $payDetail0 = $payDetail[0];
  245. $payWay = explode('-', $payDetail0['pay_prepayid']);
  246. if ($payWay[0] == 'WXPAY') {
  247. $prepayid = 'WXPAY';
  248. $response = $this->refundToWx($payDetail0, $returnId, $amount);
  249. } elseif ($payWay[0] == 'ALIPAY') {
  250. $prepayid = 'WXPAY';
  251. $response = $this->refundToAlipay($payDetail0, $amount);
  252. } elseif (isset($payWay[1]) && $payWay[1] == 'CASH') {
  253. $prepayid = $order->join_order_member_id . '-CASH';
  254. $this->refundToCash($order->join_order_member_id, $amount);
  255. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  256. } elseif (isset($payWay['1']) && $payWay[1] == 'CARD') {
  257. $prepayid = $order->join_order_member_id . '-CASH';
  258. $this->refundToCard($order->join_order_member_id, $amount);
  259. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  260. }
  261. }
  262. // payDetail 表记录
  263. $this->createReturnPayDetail($order, $prepayid, $amount, $response);
  264. Db::commit();
  265. return json_success('success');
  266. } catch (BusinessException $e) {
  267. Db::rollBack();
  268. return json_fail($e->getMessage());
  269. } catch (\Exception $e) {
  270. Db::rollBack();
  271. return json_fail("退款失败");
  272. }
  273. }
  274. /**
  275. * @Desc 退款到余额
  276. * @Author Gorden
  277. * @Date 2024/8/20 11:54
  278. *
  279. * @param $memberId
  280. * @param $amount
  281. * @return void
  282. * @throws BusinessException
  283. */
  284. private function refundToCash($memberId, $amount)
  285. {
  286. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'CASH')->first();
  287. if (!$account) {
  288. throw new BusinessException("余额账户异常");
  289. }
  290. $account->member_account_surplus = $account->member_account_surplus + $amount;
  291. $account->save();
  292. }
  293. /**
  294. * @Desc 退款到储蓄卡
  295. * @Author Gorden
  296. * @Date 2024/8/20 14:47
  297. *
  298. * @param $memberId
  299. * @param $amount
  300. * @return void
  301. * @throws BusinessException
  302. */
  303. private function refundToCard($cardNbr, $amount)
  304. {
  305. $account = MemberAccount::where('member_account_nbr', $cardNbr)->where('member_account_classify', 'CARD')->first();
  306. if (!$account) {
  307. throw new BusinessException("储值卡账户异常");
  308. }
  309. $account->member_account_surplus = $account->member_account_surplus + $amount;
  310. $account->save();
  311. }
  312. /**
  313. * @Desc
  314. * @Author Gorden
  315. * @Date 2024/8/20 14:17
  316. *
  317. * @param $params
  318. * @param $returnId
  319. * @param $amount
  320. * @return mixed
  321. * @throws BusinessException
  322. * @throws \Yansongda\Pay\Exceptions\GatewayException
  323. * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
  324. * @throws \Yansongda\Pay\Exceptions\InvalidSignException
  325. */
  326. private function refundToWx($params, $returnId, $amount)
  327. {
  328. try {
  329. $data = [
  330. 'type' => 'app',
  331. 'out_trade_no' => $params['join_pay_order_id'],
  332. 'out_refund_no' => $returnId,
  333. 'total_fee' => $params['pay_amount'] * 100,
  334. 'refund_fee' => $amount * 100,
  335. 'refund_desc' => '退款',
  336. ];
  337. $res = Pay::wechat(config('payment.wxpay'))->refund($data);
  338. $resArray = json_decode($res, true);
  339. if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') {
  340. Log::channel('pay')->error('WXPAY_REFUND_FAIL', $resArray);
  341. throw new BusinessException("退款失败");
  342. }
  343. return $resArray;
  344. } catch (\Exception $e) {
  345. throw new BusinessException("退款失败");
  346. }
  347. }
  348. /**
  349. * @Desc 支付宝退款
  350. * @Author Gorden
  351. * @Date 2024/8/20 14:40
  352. *
  353. * @param $params
  354. * @param $amount
  355. * @return mixed
  356. * @throws BusinessException
  357. */
  358. private function refundToAlipay($params, $amount)
  359. {
  360. $data = [
  361. 'out_trade_no' => $params['join_pay_order_id'],
  362. 'refund_amount' => $amount,
  363. ];
  364. try {
  365. $res = Pay::alipay(config('payment.alipay'))->refund($data);
  366. $resArray = json_decode($res, true);
  367. if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
  368. Log::channel('pay')->error('ALIPAY_REFUND_FAIL', $resArray);
  369. throw new BusinessException("退款失败");
  370. }
  371. return $resArray;
  372. } catch (\Exception $e) {
  373. throw new BusinessException("退款失败");
  374. }
  375. }
  376. /**
  377. * @Desc 更新主订单
  378. * @Author Gorden
  379. * @Date 2024/8/20 14:56
  380. *
  381. * @param $order
  382. * @param $amount
  383. * @param $remark
  384. * @return void
  385. * @throws BusinessException
  386. */
  387. private function updateMainOrderByRefund($order, $amount, $remark)
  388. {
  389. $orderDiscountJson = [];
  390. if (!empty($order->order_discount_json)) {
  391. $orderDiscountJson = json_decode($order->order_discount_json, true);
  392. }
  393. try {
  394. $orderDiscountJson[date('YH:i:s H:i:s')] = [
  395. 'coupon_id' => null,
  396. 'coupon_value' => $amount,
  397. 'coupon_classify' => '退款',
  398. 'coupon_detail_id' => $remark
  399. ];
  400. $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
  401. $order->order_amount_pay = $order->order_amount_pay - $amount;
  402. $order->save();
  403. } catch (\Exception $e) {
  404. throw new BusinessException("退款失败");
  405. }
  406. }
  407. /**
  408. * @Desc
  409. * @Author Gorden
  410. * @Date 2024/8/20 13:51
  411. *
  412. * @param $order
  413. * @return int
  414. * @throws BusinessException
  415. */
  416. private function createReturnRecord($order, $amount, $remark)
  417. {
  418. try {
  419. return OrderReturn::insertGetId([
  420. 'join_order_return_user_id' => JwtToken::getCurrentId(),
  421. 'join_return_member_id' => $order->join_order_member_id,
  422. 'join_return_order_id' => $order->order_id,
  423. 'order_return_status' => 'DONE',
  424. 'order_return_category' => '退款',
  425. 'order_return_apply_datetime' => date('Y-m-d H:i:s'),
  426. 'order_return_apply_json' => json_encode(['reason' => '后台自定义退款']),
  427. 'order_return_accept_datetime' => date('Y-m-d H:i:s'),
  428. 'order_return_refund_json' => json_encode(['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']),
  429. 'order_return_addtimes' => time()
  430. ]);
  431. } catch (\Exception $e) {
  432. throw new BusinessException("创建退款信息失败");
  433. }
  434. }
  435. private function createReturnPayDetail($order, $prepayid, $amount, $response = [])
  436. {
  437. try {
  438. return PayDetail::insert([
  439. 'join_pay_member_id' => $order->join_order_member_id,
  440. 'join_pay_order_id' => $order->order_groupby,
  441. 'pay_status' => 'SUCCESS',
  442. 'pay_category' => 'REFUND',
  443. 'pay_amount' => $amount,
  444. 'pay_paytimes' => date('Y-m-d H:i:s'),
  445. 'pay_prepayid' => $prepayid,
  446. 'pay_json_request' => json_encode(['order_id' => $order->order_id]),
  447. 'pay_json_response' => json_encode($response),
  448. 'pay_addtimes' => time()
  449. ]);
  450. } catch (\Exception $e) {
  451. }
  452. }
  453. }