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

480 lines
16 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\AgentSetting;
  8. use App\Models\Coupon;
  9. use App\Models\OrderProductItem;
  10. use App\Models\Product;
  11. use App\Models\User;
  12. use App\Models\Order;
  13. use EasyWeChat\Factory;
  14. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  15. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  16. use GuzzleHttp\Exception\GuzzleException;
  17. use Illuminate\Database\Eloquent\Model;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\DB;
  20. use App\Common\OrderStatus as Status;
  21. use Illuminate\Support\Facades\Storage;
  22. /**
  23. * 订单
  24. * Class OrderController
  25. * @package App\Http\Controllers\Api
  26. */
  27. class OrderController extends Controller
  28. {
  29. private $earnest = 200; //定金和首款默认金额 TODO 定金支付和首款支付暂定为200
  30. //订单列表
  31. public function index(Request $request)
  32. {
  33. $formData = $request->only(['page', 'status']);
  34. $request->validate([
  35. 'page' => 'regex:/^\d+$/',
  36. 'status' => 'nullable|regex:/^\d+(,\d+)*$/'
  37. ], [
  38. 'page.regex' => '页码错误',
  39. 'status.regex' => '订单状态错误'
  40. ]);
  41. $order_list = Order::where('user_id', $this->user_id);
  42. if (isset($formData['status'])) {
  43. if (preg_match('/^\d+$/', $formData['status'])) {
  44. $order_list = $order_list->where('status', $formData['status']);
  45. } else {
  46. $order_list = $order_list->whereIn('status', explode(',', $formData['status']));
  47. }
  48. }
  49. $order_list = $order_list->select('id', 'agent_product_id', 'product_id', 'title', 'picture', 'price', 'num', 'status', 'timeout', 'created_at')
  50. ->orderBy('id', 'DESC')
  51. ->simplePaginate(15)
  52. ->toArray();
  53. $time = time();
  54. $prefix = Storage::disk('public')->url('');
  55. foreach ($order_list['data'] as &$v) {
  56. //图片加上域名
  57. if (strpos($v['picture'], $prefix) === false) {
  58. $v['picture'] = $prefix . $v['picture'];
  59. }
  60. if (strpos($v['picture'], $prefix) === false) {
  61. $v['picture'] = $prefix . $v['picture'];
  62. }
  63. if (!empty($v['pictures']) && is_array($v['pictures'])) {
  64. $v['pictures'] = array_map(function($item) use ($prefix) {
  65. return strpos($item, $prefix) === false ? $prefix . $item : $item;
  66. }, $v['pictures']);
  67. }
  68. //未付款订单提示剩余付款时间
  69. if ($v['timeout'] !== null) {
  70. $second = strtotime($v['timeout']) - $time;
  71. if ($second > 0) {
  72. $v['status_text'] = '请在' . ceil($second / 60) . '分钟内付款';
  73. } else if ($second < 0 && $v['status'] == Status::PAY_EARNEST) {
  74. $v['status_text'] = '尾款支付已超时';
  75. } /*else { //此部分由定时处理
  76. $timeout_ids[] = $v['id'];
  77. $v['status'] = Status::CANCEL;
  78. $v['status_text'] = '已取消';
  79. //此部分已由定时任务处理
  80. Product::query()->find($v['product_id'])->increment('stock', $v['num']);
  81. }*/
  82. }
  83. }
  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. //TODO 供应商产品需要判断组合产品库存
  121. if ($ap->stock < $formData['num'] || $ap->product->stock < $formData['num']) {
  122. $this->error('对不起,库存不足');
  123. }
  124. $coupon_ids = [];
  125. if ($ap->coupon) {
  126. foreach ($ap->coupon as $v) {
  127. $coupon_ids[] = $v['id'];
  128. }
  129. }
  130. DB::beginTransaction();
  131. try {
  132. $price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap);
  133. $title = $ap->title; //产品标题
  134. //供应商产品表减库存
  135. $product_ids = explode(',', $ap->product_ids);
  136. $affect_row = Product::query()
  137. ->where('stock', '>=', $formData['num']) //乐观锁
  138. ->whereIn('id', $product_ids)
  139. ->decrement('stock', $formData['num']);
  140. if ($affect_row != count($product_ids)) {
  141. throw new \Exception('供应产品库存不足');
  142. }
  143. //代理商产品表减库存
  144. $affect_row = AgentProduct::query()
  145. ->where('stock', '>=', $formData['num']) //乐观锁
  146. ->where('id', $ap->id)
  147. ->decrement('stock', $formData['num']);
  148. if (!$affect_row) {
  149. throw new \Exception('商户产品库存不足');
  150. }
  151. if ($formData['pay_type'] == PayType::DEPOSIT_PAY && $ap->deposit_timeout > 0) {
  152. $timeout = date('Y-m-d H:i:s', time() + $ap->deposit_timeout * 60);
  153. } else if ($formData['pay_type'] == PayType::EARNEST_PAY && $ap->earnest_timeout > 0) {
  154. $timeout = date('Y-m-d H:i:s', time() + $ap->earnest_timeout * 60);
  155. } else {
  156. $order_timeout = AgentSetting::val($this->agent_id, 'order_timeout') ?? 60; //默认60分钟
  157. $timeout = date('Y-m-d H:i:s', time() + 60 * $order_timeout); //60 * 分钟转为秒
  158. }
  159. // 存入订单表
  160. $order = Order::query()->create([
  161. 'user_id' => $this->user_id,
  162. 'agent_id' => $this->agent_id,
  163. 'order_no' => $this->getOrderNo(),
  164. 'num' => $formData['num'],
  165. 'price' => $price,
  166. 'name' => $formData['name'],
  167. 'mobile' => $formData['mobile'],
  168. 'title' => $title,
  169. 'picture' => $ap->picture,
  170. 'agent_product_id' => $ap->id,
  171. 'product_id' => $ap->product_id,
  172. 'product_ids' => $ap->product->product_ids ?? $ap->product_id,
  173. 'status' => $formData['pay_type'] == PayType::OFFLINE ? Status::OFFLINE_UNPAID : Status::UNPAID,
  174. 'pay_type' => $formData['pay_type'],
  175. 'coupon_id' => join(',', $coupon_ids),
  176. 'guide_id' => $ap->guide_id,
  177. 'timeout' => $timeout,
  178. ]);
  179. //存入订单产品表
  180. $supplier_product_info = Product::whereIn('id', $product_ids)
  181. ->orderBy('id')->get(['id AS product_id', 'supplier_id', 'price'])->toArray();
  182. $order_id = $order->id;
  183. $agent_id = $this->agent_id;
  184. $agent_product_id = $ap->id;
  185. foreach ($supplier_product_info as &$v) {
  186. $v['order_id'] = $order_id;
  187. $v['agent_id'] = $agent_id;
  188. $v['agent_product_id'] = $agent_product_id;
  189. $v['num'] = $formData['num'];
  190. }
  191. OrderProductItem::insert($supplier_product_info);
  192. DB::commit();
  193. } catch (\Exception $e) {
  194. DB::rollBack();
  195. return $this->error($e->getMessage());
  196. }
  197. if ($formData['pay_type'] == PayType::OFFLINE) { //线下支付
  198. return $this->success(['id' => $order_id], '操作成功,请及时联系客服付款');
  199. } else { //在线支付或定金支付
  200. $config = $this->payConfig($order, $price);
  201. if (!empty($config['paySign'])) {
  202. return $this->success($config);
  203. } else {
  204. return $this->error($config['err_code_des'] ?? join(',', $config));
  205. }
  206. }
  207. }
  208. //申请退款
  209. public function refund(Request $request)
  210. {
  211. $formData = $request->only(['id', 'desc', 'pictures']);
  212. $request->validate([
  213. 'id' => 'required|integer',
  214. 'desc' => 'required|string',
  215. 'pictures' => 'nullable|array',
  216. ], [
  217. '*.required' => '内容输入不完整',
  218. 'pictures.array' => '图片必须是数组',
  219. ]);
  220. //去掉图片地址前的域名
  221. $prefix = Storage::disk('public')->url('');
  222. foreach ($formData['pictures'] as &$v) {
  223. $v = str_replace($prefix, '', $v);
  224. }
  225. //TODO 需要后台处理,然后向微信发起退款申请
  226. $order = Order::firstWhere(['id' => $formData['id'], 'user_id' => $this->user_id]);
  227. if (!$order) {
  228. return $this->error('订单不存在');
  229. }
  230. //订金/定金/首付款不允许退款,只有付全款才能申请退款
  231. if (!in_array($order->status, [Status::PAID, Status::PAID_RETAINAGE])) {
  232. return $this->error('当前订单状态不允许退款');
  233. }
  234. $order->refund_info = [
  235. 'desc' => strip_tags($formData['desc']),
  236. 'refund_no' => $this->getOrderNo(), //退款单号
  237. 'pictures' => $formData['pictures'] ?? [],
  238. 'old_status' => $order->status,
  239. ];
  240. $order->status = Status::REFUNDING;
  241. $order->save();
  242. return $this->success();
  243. }
  244. //获取应付金额及相关产品信息
  245. public function getPrice(Request $request)
  246. {
  247. $formData = $request->only(['id', 'num', 'pay_type']);
  248. $request->validate([
  249. 'id' => 'required|integer',
  250. 'num' => 'required|integer',
  251. 'pay_type' => 'required|integer',
  252. ], [
  253. '*.required' => '参数缺失',
  254. '*.integer' => '参数类型错误',
  255. ]);
  256. if (!$formData['num'] || $formData['num'] < 1) {
  257. return $this->error('未指定产品数量');
  258. }
  259. $ap = AgentProduct::query()
  260. ->has('product')
  261. ->with('coupon:agent_product_id,type,detail,agent_id,tag,start_at,end_at')
  262. ->find($formData['id'], ['id', 'price', 'original_price', 'product_id', 'title', 'pictures', 'earnest', 'earnest_timeout', 'deposit', 'deposit_timeout']);
  263. if (!$ap) {
  264. return $this->error('产品信息不存在');
  265. }
  266. $prefix = Storage::disk('public')->url('');
  267. $ap->pictures = array_map(fn($v) => $prefix . $v, $ap->pictures);
  268. //如果是线下支付,显示的价格跟在线全款支付价格一样
  269. if ($formData['pay_type'] == PayType::OFFLINE) {
  270. $formData['pay_type'] = PayType::ONLINE;
  271. }
  272. $ap->final_price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap);
  273. $ap->num = $formData['num'];
  274. return $this->success($ap);
  275. }
  276. //订单支付(在订单列表发起)
  277. public function pay(Request $request)
  278. {
  279. $id = (int)request()->input('id');
  280. //订单信息
  281. $order = Order::query()
  282. ->with('agentProduct')
  283. ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id])
  284. ->whereRaw('`timeout` >= NOW()')
  285. ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST])
  286. ->find($id);
  287. if (!$order) {
  288. return $this->error('订单已支付或已超时');
  289. }
  290. $ap = AgentProduct::with('coupon')->find($order->agent_product_id);
  291. //如果已经付定金或首付款,则仅支付尾款
  292. if ($order->status == Status::PAY_EARNEST) {
  293. $price = $order->price - $order->paid_money;
  294. } else {
  295. $price = $this->calc($order->price, $order->num, $order->pay_type, $ap);
  296. }
  297. $config = $this->payConfig($order, $price);
  298. if (!empty($config['paySign'])) {
  299. return $this->success($config);
  300. } else {
  301. return $this->error($config['err_code_des'] ?? join(',', $config));
  302. }
  303. }
  304. //获取支付配置信息
  305. private function payConfig($order, $price)
  306. {
  307. //用户openid
  308. $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG
  309. //代理商信息
  310. $agent = Agent::query()->find($this->agent_id);
  311. $config = config('wechat.payment.default');
  312. $config = array_merge($config, [
  313. 'app_id' => $agent->appid,
  314. 'mch_id' => $agent->mchid,
  315. 'key' => $agent->mchkey,
  316. ]);
  317. $app = Factory::payment($config);
  318. try {
  319. $result = $app->order->unify([
  320. 'body' => $order->title,
  321. 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付
  322. 'total_fee' => 1, //TODO 测试暂时注释 round($price * 100), //支付金额单位为分
  323. 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  324. 'trade_type' => 'JSAPI',
  325. 'openid' => $openid,
  326. 'profit_sharing' => 'Y', //Y分账,N不分账,默认不分账,Y大写
  327. ]);
  328. } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) {
  329. return ['error' => $e->getMessage(), 'line' => $e->getLine()];
  330. }
  331. if (empty($result['prepay_id'])) {
  332. return $result;
  333. }
  334. $jssdk = $app->jssdk;
  335. return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组
  336. }
  337. //订单详情
  338. public function show()
  339. {
  340. $id = (int)request()->input('id');
  341. $fields = ['id', 'agent_id', 'order_no', 'agent_product_id', 'num', 'price', 'title', 'picture', 'status',
  342. 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'verify_code', 'created_at'];
  343. $order = Order::with('agent:id,appid,appsecret')
  344. ->where('user_id', $this->user_id)
  345. ->find($id, $fields);
  346. if (!$order) {
  347. return $this->error('订单不存在');
  348. }
  349. //订单ID和核销码拼接,查询时通过订单ID和核销码来查询,这样核销码不用建索引
  350. $order->verify_code = $order->verify_code ? $order->id . '-' . $order->verify_code : '';
  351. //如果有核销码,生成核销二维码
  352. if ($order->verify_code) {
  353. $config = [
  354. 'app_id' => $order->agent->appid,
  355. 'secret' => $order->agent->appsecret,
  356. ];
  357. $app = Factory::miniProgram($config);
  358. $response = $app->app_code->getUnlimit($order->verify_code, ['page' => 'pages/verification/index']);
  359. if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
  360. $filename = $response->saveAs(storage_path('app/public/verify_code'), $order->verify_code);
  361. $order->verify_qrcode = Storage::disk('public')->url('verify_code/' . $filename);
  362. }
  363. }
  364. unset($order->agent, $order->agent_id); //必须unset掉$order->agent,否则会造成appsecret泄漏
  365. $order->coupon = Coupon::query()
  366. ->whereIn('id', $order->coupon_id)
  367. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  368. ->get(['tag']);
  369. return $this->success($order);
  370. }
  371. /**
  372. * 计算最终价格(扣除优惠券之后的价格)
  373. * $price:原价;$coupon:优惠券;$num:产品数量;$pay_type:支付方式
  374. * @param float $price
  375. * @param int $num
  376. * @param int $pay_type
  377. * @param Model $agent_product
  378. * @return float
  379. */
  380. private function calc($price, $num, $pay_type, $agent_product)
  381. {
  382. //根据支付方式计算价格
  383. if (in_array($pay_type, [PayType::DEPOSIT_PAY, PayType::EARNEST_PAY, PayType::DOWN_PAYMENT])) {
  384. if ($pay_type == PayType::DEPOSIT_PAY && $agent_product->deposit && $agent_product->deposit_timeout) {
  385. return $agent_product->deposit;
  386. }
  387. if ($pay_type == PayType::EARNEST_PAY && $agent_product->earnest && $agent_product->earnest_timeout) {
  388. return $agent_product->earnest;
  389. }
  390. }
  391. $total_price = $price * $num;
  392. /*//没有任何优惠券时直接返回最终价
  393. if ($coupon && $coupon->isEmpty()) {
  394. return $total_price;
  395. }
  396. $coupon = $coupon->toArray();
  397. foreach ($coupon as $v) {
  398. // TODO 未判断优惠券有效期
  399. if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  400. if ($total_price >= $v['detail']['full']) {
  401. $total_price -= $v['detail']['reduction'];
  402. }
  403. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  404. $total_price *= $v['detail']['discount'];
  405. }
  406. }*/
  407. return round($total_price, 2);
  408. }
  409. // 生成订单号
  410. private function getOrderNo(): string
  411. {
  412. list($micro, $sec) = explode(' ', microtime());
  413. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  414. return date('ymdHis', $sec) . $micro . mt_rand(1000, 9999);
  415. }
  416. }