海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

392 lines
12 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Common\PayType;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\Agent;
  6. use App\Models\AgentProduct;
  7. use App\Models\Coupon;
  8. use App\Models\Product;
  9. use App\Models\User;
  10. use App\Models\Order;
  11. use EasyWeChat\Factory;
  12. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  13. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  14. use GuzzleHttp\Exception\GuzzleException;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\DB;
  17. use App\Common\OrderStatus as Status;
  18. use Illuminate\Support\Facades\Storage;
  19. /**
  20. * 订单
  21. * Class OrderController
  22. * @package App\Http\Controllers\Api
  23. */
  24. class OrderController extends Controller
  25. {
  26. private $earnest = 200; //定金和首款默认金额 TODO 定金支付和首款支付暂定为200
  27. //订单列表
  28. public function index(Request $request)
  29. {
  30. $formData = $request->only(['page', 'status']);
  31. $request->validate([
  32. 'page' => 'regex:/^\d+$/',
  33. 'status' => 'nullable|integer'
  34. ], [
  35. 'page.regex' => '页码错误',
  36. 'status.integer' => '订单状态错误'
  37. ]);
  38. if (isset($formData['status'])) {
  39. $where['status'] = $formData['status'];
  40. }
  41. $where['user_id'] = $this->user_id;
  42. $order_list = Order::where($where)
  43. ->with('product:id,title,pictures')
  44. ->select('id', 'agent_product_id', 'product_id', 'price', 'num', 'status', 'created_at')
  45. ->orderBy('id', 'DESC')
  46. ->simplePaginate(15)
  47. ->toArray();
  48. $time = time();
  49. $timeout_ids = [];
  50. //10分钟内未付款订单提示付款
  51. foreach ($order_list['data'] as &$v) {
  52. if ($v['status'] == Status::UNPAID) {
  53. $minute = $time - strtotime($v['created_at']);
  54. //订单创建后10分钟内未付款则提示,否则取消订单
  55. if ($minute < 600) {
  56. $v['status_text'] = '请在' . ceil($minute / 60) . '分钟内付款';
  57. } else {
  58. $timeout_ids[] = $v['id'];
  59. $v['status'] = Status::CANCEL;
  60. $v['status_text'] = '已取消';
  61. //TODO 加回库存,未考虑到几天/几个月后再打开订单列表页的情况,需要定时任务处理
  62. Product::query()->find($v['product_id'])->increment('stock', $v['num']);
  63. }
  64. }
  65. }
  66. //超时订单设置为已取消 TODO 测试阶段暂时注释
  67. Order::query()->whereIn('id', $timeout_ids)->update(['status' => Status::CANCEL]);
  68. return $this->success($order_list);
  69. }
  70. //提交订单
  71. public function create(Request $request)
  72. {
  73. $formData = $request->only(['id', 'name', 'mobile', 'pay_type', 'num']);
  74. $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空
  75. //表单验证
  76. $pay_type_values = join(',', array_keys(PayType::array()));
  77. $request->validate([
  78. 'id' => ['required', 'regex:/^\d+$/'],
  79. 'name' => ['required', 'between:2,20'],
  80. 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
  81. 'pay_type' => ['required', 'in:' . $pay_type_values],
  82. 'num' => ['required', 'min:1'],
  83. ], [
  84. 'id.required' => '未指定产品ID',
  85. 'name.required' => '请输入联系人姓名',
  86. 'mobile.required' => '请输入联系手机号',
  87. 'id.regex' => '产品ID错误',
  88. 'name.between' => '联系人姓名在2~20字符之间',
  89. 'mobile.regex' => '请输入11位手机号',
  90. 'pay_type.required' => '请选择支付方式',
  91. 'pay_type.in' => '不存在此支付方式',
  92. 'num.required' => '请输入购买数量',
  93. 'num.min' => '购买数量输入错误',
  94. ]);
  95. $ap = AgentProduct::query()
  96. ->where('id', $formData['id'])
  97. ->with('coupon')
  98. ->with('product')
  99. ->first();
  100. if (!$ap || !$ap->product) {
  101. $this->error('产品不存在');
  102. }
  103. if ($ap->stock < $formData['num'] || $ap->product->stock < $formData['num']) {
  104. $this->error('对不起,库存不足');
  105. }
  106. $coupon_ids = [];
  107. if ($ap->coupon) {
  108. foreach ($ap->coupon as $v) {
  109. $coupon_ids[] = $v['id'];
  110. }
  111. }
  112. DB::beginTransaction();
  113. try {
  114. $price = $this->calc($ap->price, $ap->coupon, $formData['num'], $formData['pay_type']);
  115. $title = $ap->product->title; //产品标题
  116. //代理商产品表增加销量
  117. // $ap->increment('sale', $formData['num']); TODO 支付成功之后再增加销量
  118. //供应商产品表加销量、减库存
  119. // $ap->product->sale += $formData['num']; TODO 支付成功之后再增加销量
  120. $ap->product->decrement('stock', $formData['num']);
  121. //代理商产品表减库存
  122. $ap->decrement('stock', $formData['num']);
  123. // 存入订单表
  124. $order = Order::query()->create([
  125. 'user_id' => $this->user_id,
  126. 'agent_id' => $this->agent_id,
  127. 'order_no' => $this->getOrderNo(),
  128. 'num' => $formData['num'],
  129. 'price' => $price,
  130. 'name' => $formData['name'],
  131. 'mobile' => $formData['mobile'],
  132. 'title' => $title,
  133. 'picture' => $ap->product->picture,
  134. 'agent_product_id' => $ap->id,
  135. 'product_id' => $ap->product_id,
  136. 'product_ids' => $ap->product->product_ids ?? $ap->product_id,
  137. 'status' => $formData['pay_type'] == PayType::OFFLINE ? Status::OFFLINE_UNPAID : Status::UNPAID,
  138. 'pay_type' => $formData['pay_type'],
  139. 'coupon_id' => join(',', $coupon_ids),
  140. 'guide_id' => $ap->guide_id,
  141. ]);
  142. DB::commit();
  143. } catch (\Exception $e) {
  144. DB::rollBack();
  145. return $this->error($e->getMessage());
  146. }
  147. if ($formData['pay_type'] == PayType::OFFLINE) { //线下支付
  148. return $this->success('操作成功,请及时联系客服付款');
  149. } else { //在线支付或定金支付
  150. $config = $this->payConfig($order, $price);
  151. if (!empty($config['paySign'])) {
  152. return $this->success($config);
  153. } else {
  154. return $this->error($config['err_code_des'] ?? join(',', $config));
  155. }
  156. }
  157. }
  158. //申请退款
  159. public function refund(Request $request)
  160. {
  161. $formData = $request->only(['id', 'desc', 'pictures']);
  162. $request->validate([
  163. 'id' => 'required|integer',
  164. 'desc' => 'required|string',
  165. 'pictures' => 'nullable|array',
  166. ], [
  167. '*.required' => '内容输入不完整',
  168. 'pictures.array' => '图片必须是数组',
  169. ]);
  170. //去掉图片地址前的域名
  171. $prefix = Storage::disk('public')->url('');
  172. foreach ($formData['pictures'] as &$v) {
  173. $v = str_replace($prefix, '', $v);
  174. }
  175. //TODO 需要后台处理,然后向微信发起退款申请
  176. $order = Order::firstWhere(['id' => $formData['id'], 'user_id' => $this->user_id]);
  177. if (!$order) {
  178. return $this->error('订单不存在');
  179. }
  180. //订金/定金/首付款不允许退款,只有付全款才能申请退款
  181. if (!in_array($order->status, [Status::PAID, Status::PAID_RETAINAGE])) {
  182. return $this->error('当前订单状态不允许退款');
  183. }
  184. $order->refund_info = [
  185. 'desc' => strip_tags($formData['desc']),
  186. 'refund_no' => $this->getOrderNo(), //退款单号
  187. 'pictures' => $formData['pictures'] ?? [],
  188. 'old_status' => $order->status,
  189. ];
  190. $order->status = Status::REFUNDING;
  191. $order->save();
  192. return $this->success();
  193. }
  194. //获取应付金额及相关产品信息
  195. public function getPrice(Request $request)
  196. {
  197. $formData = $request->only(['id', 'num', 'pay_type']);
  198. $request->validate([
  199. 'id' => 'required|integer',
  200. 'num' => 'required|integer',
  201. 'pay_type' => 'required|integer',
  202. ], [
  203. '*.required' => '参数缺失',
  204. '*.integer' => '参数类型错误',
  205. ]);
  206. if (!$formData['num'] || $formData['num'] < 1) {
  207. return $this->error('未指定产品数量');
  208. }
  209. $ap = AgentProduct::query()
  210. ->with('product:id,title,pictures')
  211. ->with('coupon:agent_product_id,type,detail,agent_id,tag,start_at,end_at')
  212. ->find($formData['id'], ['id', 'price', 'original_price', 'product_id']);
  213. if (!$ap) {
  214. return $this->error('产品信息不存在');
  215. }
  216. //如果是线下支付,显示的价格跟在线全款支付价格一样
  217. if ($formData['pay_type'] == PayType::OFFLINE) {
  218. $formData['pay_type'] = PayType::ONLINE;
  219. }
  220. $ap->final_price = $this->calc($ap->price, $ap->coupon, $formData['num'], $formData['pay_type']);
  221. $ap->num = $formData['num'];
  222. return $this->success($ap);
  223. }
  224. //订单支付(在订单列表发起)
  225. public function pay(Request $request)
  226. {
  227. $id = (int)request()->input('id');
  228. //订单信息
  229. $order = Order::query()
  230. ->with('agentProduct')
  231. ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id])
  232. ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST])
  233. ->find($id);
  234. if (!$order) {
  235. return $this->error('订单不存在或已支付');
  236. }
  237. $coupon = Coupon::whereIn('id', $order['coupon_id'])->get();
  238. //如果已经付定金或首付款,则仅支付尾款
  239. if ($order->status == Status::PAY_EARNEST) {
  240. $price = $order->price - $order->paid_money;
  241. } else {
  242. $price = $this->calc($order->price, $coupon, $order->num, $order->pay_type);
  243. }
  244. $config = $this->payConfig($order, $price);
  245. if (!empty($config['paySign'])) {
  246. return $this->success($config);
  247. } else {
  248. return $this->error($config['err_code_des'] ?? join(',', $config));
  249. }
  250. }
  251. //获取支付配置信息
  252. private function payConfig($order, $price)
  253. {
  254. //用户openid
  255. $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG
  256. //代理商信息
  257. $agent = Agent::query()->find($this->agent_id);
  258. $config = config('wechat.payment.default');
  259. $config = array_merge($config, [
  260. 'app_id' => $agent->appid,
  261. 'mch_id' => $agent->mchid,
  262. 'key' => $agent->mchkey,
  263. ]);
  264. $app = Factory::payment($config);
  265. try {
  266. $result = $app->order->unify([
  267. 'body' => $order->title,
  268. 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付
  269. 'total_fee' => round($price * 100), //支付金额单位为分
  270. 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  271. 'trade_type' => 'JSAPI',
  272. 'openid' => $openid,
  273. ]);
  274. } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) {
  275. return ['error' => $e->getMessage(), 'line' => $e->getLine()];
  276. }
  277. if (empty($result['prepay_id'])) {
  278. return $result;
  279. }
  280. $jssdk = $app->jssdk;
  281. return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组
  282. }
  283. //订单详情
  284. public function show()
  285. {
  286. $id = (int)request()->input('id');
  287. $fields = ['id', 'order_no', 'agent_product_id', 'num', 'price', 'title', 'picture',
  288. 'status', 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'created_at'];
  289. $order = Order::query()
  290. ->where('user_id', $this->user_id)
  291. ->find($id, $fields);
  292. if (!$order) {
  293. return $this->error('订单不存在');
  294. }
  295. $order->coupon = Coupon::query()
  296. ->whereIn('id', $order->coupon_id)
  297. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  298. ->get(['tag']);
  299. return $this->success($order);
  300. }
  301. /**
  302. * 计算最终价格(扣除优惠券之后的价格)
  303. * $price:原价;$coupon:优惠券;$num:产品数量;$pay_type:支付方式
  304. * @param float $price
  305. * @param Coupon $coupon
  306. * @param int $num
  307. * @param int $pay_type
  308. * @return float
  309. */
  310. private function calc($price, $coupon, $num, $pay_type)
  311. {
  312. //根据支付方式计算价格
  313. if (in_array($pay_type, [PayType::SUBSCRIPTION, PayType::DEPOSIT, PayType::DOWN_PAYMENT])) {
  314. return $this->earnest;
  315. }
  316. //TODO 还要计算尾款支付金额
  317. $total_price = $price * $num;
  318. //没有任何优惠券时直接返回最终价
  319. if ($coupon && $coupon->isEmpty()) {
  320. return $total_price;
  321. }
  322. $coupon = $coupon->toArray();
  323. foreach ($coupon as $v) {
  324. // TODO 未判断优惠券有效期
  325. /*if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  326. if ($total_price >= $v['detail']['full']) {
  327. $total_price -= $v['detail']['reduction'];
  328. }
  329. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  330. $total_price *= $v['detail']['discount'];
  331. }*/
  332. }
  333. return round($total_price, 2);
  334. }
  335. // 生成订单号
  336. private function getOrderNo(): string
  337. {
  338. list($micro, $sec) = explode(' ', microtime());
  339. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  340. return date('YmdHis', $sec) . $micro . mt_rand(1000, 9999);
  341. }
  342. }