海南旅游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.

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