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

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