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

411 lines
13 KiB

4 years ago
  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', 'title', 'pictures']);
  223. if (!$ap) {
  224. return $this->error('产品信息不存在');
  225. }
  226. $prefix = Storage::disk('public')->url('');
  227. $ap->pictures = array_map(fn($v) => $prefix . $v, $ap->pictures);
  228. //如果是线下支付,显示的价格跟在线全款支付价格一样
  229. if ($formData['pay_type'] == PayType::OFFLINE) {
  230. $formData['pay_type'] = PayType::ONLINE;
  231. }
  232. $ap->final_price = $this->calc($ap->price, $ap->coupon, $formData['num'], $formData['pay_type']);
  233. $ap->num = $formData['num'];
  234. return $this->success($ap);
  235. }
  236. //订单支付(在订单列表发起)
  237. public function pay(Request $request)
  238. {
  239. $id = (int)request()->input('id');
  240. //订单信息
  241. $order = Order::query()
  242. ->with('agentProduct')
  243. ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id])
  244. ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST])
  245. ->find($id);
  246. if (!$order) {
  247. return $this->error('订单不存在或已支付');
  248. }
  249. $coupon = Coupon::whereIn('id', $order['coupon_id'])->get();
  250. //如果已经付定金或首付款,则仅支付尾款
  251. if ($order->status == Status::PAY_EARNEST) {
  252. $price = $order->price - $order->paid_money;
  253. } else {
  254. $price = $this->calc($order->price, $coupon, $order->num, $order->pay_type);
  255. }
  256. $config = $this->payConfig($order, $price);
  257. if (!empty($config['paySign'])) {
  258. return $this->success($config);
  259. } else {
  260. return $this->error($config['err_code_des'] ?? join(',', $config));
  261. }
  262. }
  263. //获取支付配置信息
  264. private function payConfig($order, $price)
  265. {
  266. //用户openid
  267. $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG
  268. //代理商信息
  269. $agent = Agent::query()->find($this->agent_id);
  270. $config = config('wechat.payment.default');
  271. $config = array_merge($config, [
  272. 'app_id' => $agent->appid,
  273. 'mch_id' => $agent->mchid,
  274. 'key' => $agent->mchkey,
  275. ]);
  276. $app = Factory::payment($config);
  277. try {
  278. $result = $app->order->unify([
  279. 'body' => $order->title,
  280. 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付
  281. 'total_fee' => 1, //TODO 测试暂时注释 round($price * 100), //支付金额单位为分
  282. 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  283. 'trade_type' => 'JSAPI',
  284. 'openid' => $openid,
  285. ]);
  286. } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) {
  287. return ['error' => $e->getMessage(), 'line' => $e->getLine()];
  288. }
  289. if (empty($result['prepay_id'])) {
  290. return $result;
  291. }
  292. $jssdk = $app->jssdk;
  293. return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组
  294. }
  295. //订单详情
  296. public function show()
  297. {
  298. $id = (int)request()->input('id');
  299. $fields = ['id', 'order_no', 'agent_product_id', 'num', 'price', 'title', 'picture', 'status',
  300. 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'verify_code', 'created_at'];
  301. $order = Order::query()
  302. ->where('user_id', $this->user_id)
  303. ->find($id, $fields);
  304. if (!$order) {
  305. return $this->error('订单不存在');
  306. }
  307. //订单ID和核销码拼接,查询时通过订单ID和核销码来查询,这样核销码不用建索引
  308. $order->verify_code = $order->verify_code ? $order->id . '-' . $order->verify_code : '';
  309. $order->coupon = Coupon::query()
  310. ->whereIn('id', $order->coupon_id)
  311. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  312. ->get(['tag']);
  313. return $this->success($order);
  314. }
  315. /**
  316. * 计算最终价格(扣除优惠券之后的价格)
  317. * $price:原价;$coupon:优惠券;$num:产品数量;$pay_type:支付方式
  318. * @param float $price
  319. * @param Coupon $coupon
  320. * @param int $num
  321. * @param int $pay_type
  322. * @return float
  323. */
  324. private function calc($price, $coupon, $num, $pay_type)
  325. {
  326. //根据支付方式计算价格
  327. if (in_array($pay_type, [PayType::SUBSCRIPTION, PayType::DEPOSIT, PayType::DOWN_PAYMENT])) {
  328. return $this->earnest;
  329. }
  330. //TODO 还要计算尾款支付金额
  331. $total_price = $price * $num;
  332. //没有任何优惠券时直接返回最终价
  333. if ($coupon && $coupon->isEmpty()) {
  334. return $total_price;
  335. }
  336. $coupon = $coupon->toArray();
  337. foreach ($coupon as $v) {
  338. // TODO 未判断优惠券有效期
  339. /*if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  340. if ($total_price >= $v['detail']['full']) {
  341. $total_price -= $v['detail']['reduction'];
  342. }
  343. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  344. $total_price *= $v['detail']['discount'];
  345. }*/
  346. }
  347. return round($total_price, 2);
  348. }
  349. // 生成订单号
  350. private function getOrderNo(): string
  351. {
  352. list($micro, $sec) = explode(' ', microtime());
  353. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  354. return date('ymdHis', $sec) . $micro . mt_rand(1000, 9999);
  355. }
  356. }