RefundController.php 18 KB

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