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

578 lines
20 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Common\PayType;
  4. use App\Common\ProductStatus;
  5. use App\Http\Controllers\Controller;
  6. use App\Models\AdminSetting;
  7. use App\Models\Agent;
  8. use App\Models\AgentProduct;
  9. use App\Models\AgentProductSpec;
  10. use App\Models\AgentSetting;
  11. use App\Models\Coupon;
  12. use App\Models\OrderProductItem;
  13. use App\Models\Product;
  14. use App\Models\ProductSpec;
  15. use App\Models\SystemSetting;
  16. use App\Models\User;
  17. use App\Models\Order;
  18. use App\Service\OpenPlatform;
  19. use EasyWeChat\Factory;
  20. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  21. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  22. use EasyWeChat\Kernel\Http\StreamResponse;
  23. use GuzzleHttp\Exception\GuzzleException;
  24. use Illuminate\Http\Request;
  25. use Illuminate\Support\Facades\DB;
  26. use App\Common\OrderStatus as Status;
  27. use Illuminate\Support\Facades\Storage;
  28. /**
  29. * 订单
  30. * Class OrderController
  31. * @package App\Http\Controllers\Api
  32. */
  33. class OrderController extends Controller
  34. {
  35. //订单列表
  36. public function index(Request $request)
  37. {
  38. $formData = $request->only(['page', 'status']);
  39. $request->validate([
  40. 'page' => 'regex:/^\d+$/',
  41. 'status' => 'nullable|regex:/^\d+(,\d+)*$/'
  42. ], [
  43. 'page.regex' => '页码错误',
  44. 'status.regex' => '订单状态错误'
  45. ]);
  46. $order_list = Order::where('user_id', $this->user_id);
  47. if (isset($formData['status'])) {
  48. if (preg_match('/^\d+$/', $formData['status'])) {
  49. $order_list = $order_list->where('status', $formData['status']);
  50. } else {
  51. $order_list = $order_list->whereIn('status', explode(',', $formData['status']));
  52. }
  53. }
  54. $order_list = $order_list->select('id', 'agent_product_id', 'product_id', 'title', 'picture', 'price', 'num', 'status', 'timeout', 'created_at')
  55. ->orderBy('id', 'DESC')
  56. ->simplePaginate(15)
  57. ->toArray();
  58. $time = time();
  59. $prefix = Storage::disk('public')->url('');
  60. foreach ($order_list['data'] as &$v) {
  61. //图片加上域名
  62. if (strpos($v['picture'], $prefix) === false) {
  63. $v['picture'] = $prefix . $v['picture'];
  64. }
  65. if (strpos($v['picture'], $prefix) === false) {
  66. $v['picture'] = $prefix . $v['picture'];
  67. }
  68. if (!empty($v['pictures']) && is_array($v['pictures'])) {
  69. $v['pictures'] = array_map(function($item) use ($prefix) {
  70. return strpos($item, $prefix) === false ? $prefix . $item : $item;
  71. }, $v['pictures']);
  72. }
  73. //未付款订单提示剩余付款时间
  74. if ($v['timeout'] !== null) {
  75. $second = strtotime($v['timeout']) - $time;
  76. if ($second > 0) {
  77. $text_arr = [
  78. Status::UNPAID => '付款',
  79. Status::OFFLINE_UNPAID => '线下付款',
  80. Status::PAY_EARNEST => '付尾款',
  81. ];
  82. if (isset($text_arr[$v['status']])) {
  83. $v['status_text'] = '请在' . ceil($second / 60) . "分钟内" . ($text_arr[$v['status']] ?? '付款');
  84. }
  85. } else if ($second < 0 && $v['status'] == Status::PAY_EARNEST) {
  86. $v['status_text'] = '尾款支付已超时';
  87. } /*else { //此部分由定时处理
  88. $timeout_ids[] = $v['id'];
  89. $v['status'] = Status::CANCEL;
  90. $v['status_text'] = '已取消';
  91. //此部分已由定时任务处理
  92. Product::query()->find($v['product_id'])->increment('stock', $v['num']);
  93. }*/
  94. }
  95. }
  96. return $this->success($order_list);
  97. }
  98. //提交订单
  99. public function create(Request $request)
  100. {
  101. $formData = $request->input();
  102. $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空
  103. //表单验证
  104. $pay_type_values = join(',', array_keys(PayType::array()));
  105. $request->validate([
  106. 'id' => ['required', 'regex:/^\d+$/'],
  107. 'name' => ['required', 'between:2,20'],
  108. 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
  109. 'pay_type' => ['required', 'in:' . $pay_type_values],
  110. 'num' => ['required', 'min:1'],
  111. 'spec_id' => ['required', 'min:1', 'integer'],
  112. 'id_card' => ['regex:/^\d{17}[\dXx]$/'],
  113. ], [
  114. 'id.required' => '未指定产品ID',
  115. 'name.required' => '请输入联系人姓名',
  116. 'mobile.required' => '请输入联系手机号',
  117. 'id.regex' => '产品ID错误',
  118. 'name.between' => '联系人姓名在2~20字符之间',
  119. 'mobile.regex' => '请输入11位手机号',
  120. 'pay_type.required' => '请选择支付方式',
  121. 'pay_type.in' => '不存在此支付方式',
  122. 'num.required' => '请输入购买数量',
  123. 'num.min' => '购买数量输入错误',
  124. 'spec_id.*' => '请选择产品规格',
  125. 'id_card.regex' => '身份证号输入不正确',
  126. ]);
  127. $ap = AgentProduct::with(['coupon', 'product', 'agentCloudProduct:id,price'])
  128. ->where('stock', '>=', $formData['num'])
  129. ->where(['id' => $formData['id'], 'status' => ProductStatus::ON_SALE, 'agent_id' => $this->agent_id]) //判断agent_id,防止新入驻小程序的演示产品被下单
  130. ->whereDoesntHave('agentProductItem', function ($query) {
  131. return $query->whereHas('product', function ($query) {
  132. return $query->where('stock', '<=', 0)->orWhere('status', '<>', ProductStatus::ON_SALE);
  133. });
  134. })
  135. ->first();
  136. if (!$ap || !$ap->product) {
  137. return $this->error('产品已下架或库存不足');
  138. }
  139. $order_info = [];
  140. //0:单品销售;1:组合销售
  141. if ($ap->type == 0) {
  142. $spec = AgentProductSpec::where('agent_product_id', $formData['id'])->find($formData['spec_id']);
  143. if (!$spec) {
  144. return $this->error('你选择的产品规格不存在');
  145. }
  146. $order_price = $spec->price * $formData['num']; //订单总价
  147. //0:旅游线路、1:酒店、2:景区、3:餐厅、4:车队、5:单项 => admin_trans('product.options.publish_type')
  148. switch ($ap->product->type) {
  149. case 0:
  150. case 3:
  151. case 4:
  152. case 5:
  153. if (empty($formData['departure_time']) || !strtotime($formData['departure_time'])) {
  154. return $this->error('请选择出发时间');
  155. }
  156. /*if (empty($formData['return_time']) || !strtotime($formData['return_time'])) {
  157. return $this->error('请选择回程时间');
  158. }*/
  159. if (empty($formData['id_card'])) {
  160. return $this->error('请输入身份证号');
  161. }
  162. $order_info['departure_time'] = $formData['departure_time']; //出发时间
  163. // $order_info['return_time'] = $formData['return_time']; //回程时间
  164. $order_info['id_card'] = $formData['id_card']; //身份证号
  165. $order_info['sex'] = $formData['sex'] ?? 0; //性别
  166. $order_info['age'] = $formData['age'] ?? 0; //年龄
  167. break;
  168. case 1:
  169. if (empty($formData['check_in_time']) || !strtotime($formData['check_in_time'])) {
  170. return $this->error('请选择入住时间');
  171. }
  172. if (empty($formData['check_out_time']) || !strtotime($formData['check_out_time'])) {
  173. return $this->error('请选择离店时间');
  174. }
  175. if (empty($formData['arrival_time']) || !strtotime($formData['arrival_time'])) {
  176. return $this->error('请选择到店时间');
  177. }
  178. if (empty($formData['id_card'])) {
  179. return $this->error('请输入身份证号');
  180. }
  181. $order_info['check_in_time'] = $formData['departure_time']; //入住时间
  182. $order_info['check_out_time'] = $formData['return_time']; //离店时间
  183. $order_info['arrival_time'] = $formData['arrival_time']; //到店时间
  184. $order_info['id_card'] = $formData['id_card']; //身份证号
  185. $order_info['sex'] = $formData['sex'] ?? 0; //性别
  186. $order_info['age'] = $formData['age'] ?? 0; //年龄
  187. break;
  188. case 2:
  189. if (empty($formData['enter_time']) || !strtotime($formData['enter_time'])) {
  190. return $this->error('请选择入园时间');
  191. }
  192. if (empty($formData['id_card'])) {
  193. return $this->error('请输入身份证号');
  194. }
  195. $order_info['enter_time'] = $formData['enter_time']; //到店时间
  196. $order_info['id_card'] = $formData['id_card']; //身份证号
  197. $order_info['sex'] = $formData['sex'] ?? 0; //性别
  198. $order_info['age'] = $formData['age'] ?? 0; //年龄
  199. break;
  200. }
  201. } else {
  202. return $this->error('不存在此类型产品');
  203. }
  204. //支付小程序的产品不允许购买
  205. if (AdminSetting::val('payee_appid') == Agent::where('id', $this->agent_id)->value('appid')) {
  206. return $this->error('系统出错了,购买失败~~');
  207. }
  208. $coupon_ids = [];
  209. if ($ap->coupon) {
  210. foreach ($ap->coupon as $v) {
  211. $coupon_ids[] = $v['id'];
  212. }
  213. }
  214. DB::beginTransaction();
  215. try {
  216. //供应商产品表减库存
  217. $product_ids = explode(',', $ap->product_ids);
  218. $affect_row = Product::query()
  219. ->where('stock', '>=', $formData['num']) //乐观锁
  220. ->whereIn('id', $product_ids)
  221. ->decrement('stock', $formData['num']);
  222. if ($affect_row != count($product_ids)) {
  223. throw new \Exception('供应产品库存不足');
  224. }
  225. //供应商产品规格减表减库存
  226. $affect_row = ProductSpec::query()
  227. ->where('stock', '>=', $formData['num']) //乐观锁
  228. ->where('id', $spec['product_spec_id'])
  229. ->decrement('stock', $formData['num']);
  230. if (!$affect_row) {
  231. throw new \Exception('你选择的供应产品规格库存不足');
  232. }
  233. //代理商产品表减库存
  234. $affect_row = AgentProduct::query()
  235. ->where('stock', '>=', $formData['num']) //乐观锁
  236. ->where('id', $formData['id'])
  237. ->decrement('stock', $formData['num']);
  238. if (!$affect_row) {
  239. throw new \Exception('商户产品库存不足');
  240. }
  241. //代理商产品规格表减库存
  242. $affect_row = AgentProductSpec::query()
  243. ->where('stock', '>=', $formData['num']) //乐观锁
  244. ->where('id', $spec['id'])
  245. ->decrement('stock', $formData['num']);
  246. if (!$affect_row) {
  247. throw new \Exception('你选择的商户产品规格库存不足');
  248. }
  249. //未付款时定金/订金的超时时间依然使用默认的订单超时时间,付定金/订金之后才使用定金超时时间
  250. $order_timeout = AgentSetting::val($this->agent_id, 'order_timeout') ?? 60; //默认60分钟
  251. $timeout = date('Y-m-d H:i:s', time() + $order_timeout * 60); //60 * 分钟转为秒
  252. //处理预付金额
  253. if ($formData['pay_type'] == PayType::DEPOSIT_PAY) {
  254. //订金支付
  255. $prepayPrice = $ap->deposit * $formData['num'];
  256. $prepayTimeout = $ap->deposit_timeout;
  257. } else if($formData['pay_type'] == PayType::EARNEST_PAY) {
  258. //定金支付
  259. $prepayPrice = $ap->earnest * $formData['num'];
  260. $prepayTimeout = $ap->earnest_timeout;
  261. }
  262. // 存入订单表
  263. $order = Order::query()->create([
  264. 'user_id' => $this->user_id,
  265. 'agent_id' => $this->agent_id,
  266. 'order_no' => $this->getOrderNo(),
  267. 'num' => $formData['num'],
  268. 'price' => $order_price,
  269. 'name' => $formData['name'],
  270. 'mobile' => $formData['mobile'],
  271. 'title' => $ap->title,
  272. 'picture' => $ap->picture,
  273. 'agent_product_id' => $ap->id,
  274. 'product_id' => $ap->product_id,
  275. 'product_ids' => $ap->product->product_ids ?? $ap->product_id,
  276. 'status' => $formData['pay_type'] == PayType::OFFLINE ? Status::OFFLINE_UNPAID : Status::UNPAID,
  277. 'pay_type' => $formData['pay_type'],
  278. 'coupon_id' => join(',', $coupon_ids),
  279. 'guide_id' => $ap->guide_id,
  280. 'guide_price' => $ap->guide_price,
  281. 'timeout' => $timeout,
  282. 'agent_cloud_pid' => $ap->agent_cloud_pid,
  283. 'agent_cloud_price' => $ap->agentCloudProduct->price ?? 0,
  284. 'prepay_price' => $prepayPrice ?? 0,
  285. 'prepay_timeout' => $prepayTimeout ?? 0,
  286. 'service_persons' => SystemSetting::val('single', 'price'),
  287. 'info' => $order_info,
  288. ]);
  289. //存入订单产品表
  290. $supplier_product_info = Product::whereIn('id', $product_ids)
  291. ->orderBy('id')->get(['type', 'id AS product_id', 'supplier_id', 'price', 'service_persons'])->toArray();
  292. $order_id = $order->id;
  293. $agent_id = $this->agent_id;
  294. $agent_product_id = $ap->id;
  295. foreach ($supplier_product_info as &$v) {
  296. $v['order_id'] = $order_id;
  297. $v['agent_id'] = $agent_id;
  298. $v['agent_product_id'] = $agent_product_id;
  299. $v['num'] = $formData['num'];
  300. if ($v['type'] == 0) { //TODO 此处未处理组合产品
  301. $v['product_spec_id'] = $formData['spec_id'];
  302. }
  303. unset($v['type']);
  304. }
  305. OrderProductItem::insert($supplier_product_info);
  306. DB::commit();
  307. } catch (\Exception $e) {
  308. DB::rollBack();
  309. return $this->error($e->getMessage());
  310. }
  311. if ($formData['pay_type'] == PayType::OFFLINE) { //线下支付
  312. return $this->success(['id' => $order_id], '操作成功,请及时联系客服付款');
  313. } else { //在线支付或定金支付
  314. /*$config = $this->payConfig($order, $price);
  315. if (!empty($config['paySign'])) {
  316. return $this->success($config);
  317. } else {
  318. return $this->error($config['err_code_des'] ?? join(',', $config));
  319. }*/
  320. // 跳转支付专用
  321. return $this->success(['id' => $order->id, 'jump' => true, 'jump_appid' => AdminSetting::val('payee_appid')]);
  322. }
  323. }
  324. //申请退款
  325. public function refund(Request $request)
  326. {
  327. $formData = $request->only(['id', 'desc', 'pictures']);
  328. $request->validate([
  329. 'id' => 'required|integer',
  330. 'desc' => 'required|string',
  331. 'pictures' => 'nullable|array',
  332. ], [
  333. '*.required' => '内容输入不完整',
  334. 'pictures.array' => '图片必须是数组',
  335. ]);
  336. //去掉图片地址前的域名
  337. $prefix = Storage::disk('public')->url('');
  338. foreach ($formData['pictures'] as &$v) {
  339. $v = str_replace($prefix, '', $v);
  340. }
  341. $order = Order::firstWhere(['id' => $formData['id'], 'user_id' => $this->user_id]);
  342. if (!$order) {
  343. return $this->error('订单不存在');
  344. }
  345. //订金/定金/首付款不允许退款,只有付全款才能申请退款
  346. if (!in_array($order->status, [Status::PAID, Status::PAID_RETAINAGE])) {
  347. return $this->error('当前订单状态不允许退款');
  348. }
  349. $order->refund_info = [
  350. 'desc' => strip_tags($formData['desc']),
  351. 'refund_no' => $this->getOrderNo(), //退款单号
  352. 'pictures' => $formData['pictures'] ?? [],
  353. 'old_status' => $order->status,
  354. ];
  355. $order->status = Status::REFUNDING;
  356. $order->save();
  357. return $this->success();
  358. }
  359. //获取应付金额及相关产品信息
  360. public function getPrice(Request $request)
  361. {
  362. $formData = $request->only(['id', 'num', 'pay_type', 'spec_id']);
  363. $request->validate([
  364. 'id' => 'required|integer',
  365. 'num' => 'required|integer',
  366. 'pay_type' => 'required|integer',
  367. 'spec_id' => 'required|integer',
  368. ], [
  369. '*.required' => '参数缺失',
  370. '*.integer' => '参数类型错误',
  371. ]);
  372. if (!$formData['num'] || $formData['num'] < 1) {
  373. return $this->error('未指定产品数量');
  374. }
  375. $ap = AgentProduct::with(['coupon:agent_product_id,type,detail,agent_id,tag,start_at,end_at'])
  376. ->has('product')
  377. ->find($formData['id'], ['id', 'price', 'original_price', 'product_id', 'title', 'pictures', 'earnest', 'earnest_timeout', 'deposit', 'deposit_timeout']);
  378. if (!$ap) {
  379. return $this->error('产品信息不存在');
  380. }
  381. $prefix = Storage::disk('public')->url('');
  382. $ap->pictures = array_map(fn($v) => $prefix . $v, $ap->pictures);
  383. //如果是线下支付,显示的价格跟在线全款支付价格一样
  384. //订金支付
  385. if ($formData['pay_type'] == PayType::DEPOSIT_PAY) {
  386. $ap->final_price = $ap->deposit * $formData['num'];
  387. }
  388. //定金支付
  389. else if($formData['pay_type'] == PayType::EARNEST_PAY) {
  390. $ap->final_price = $ap->earnest * $formData['num'];
  391. } else {
  392. $spec = AgentProductSpec::where('product_id', $formData['id'])->find($formData['spec_id']);
  393. if (!$spec) {
  394. return $this->error('你选择的产品规格不存在');
  395. }
  396. $ap->final_price = $spec->price * $formData['num'];
  397. }
  398. $ap->num = $formData['num'];
  399. return $this->success($ap);
  400. }
  401. //订单支付(在订单列表发起)
  402. public function pay(Request $request)
  403. {
  404. $id = (int)request()->input('id');
  405. //订单信息
  406. $order = Order::query()
  407. ->with('agentProduct')
  408. ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id])
  409. ->whereRaw('`timeout` >= NOW()')
  410. ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST])
  411. ->find($id);
  412. if (!$order) {
  413. return $this->error('订单已支付或已超时');
  414. }
  415. // 跳转支付专用
  416. return $this->success(['id' => $id, 'jump' => true, 'jump_appid' => AdminSetting::val('payee_appid')]);
  417. /*$ap = AgentProduct::with('coupon')->find($order->agent_product_id);
  418. //如果已经付定金或首付款,则仅支付尾款
  419. if ($order->status == Status::PAY_EARNEST) {
  420. $price = $order->price - $order->paid_money;
  421. } else {
  422. $price = $this->calc($order->price, $order->num, $order->pay_type, $ap);
  423. }
  424. $config = $this->payConfig($order, $price);
  425. if (!empty($config['paySign'])) {
  426. return $this->success($config);
  427. } else {
  428. return $this->error($config['err_code_des'] ?? join(',', $config));
  429. }*/
  430. }
  431. //获取支付配置信息
  432. private function payConfig($order, $price)
  433. {
  434. //用户openid
  435. $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG
  436. //代理商信息
  437. $agent = Agent::query()->find($this->agent_id);
  438. $config = config('wechat.payment.default');
  439. $config = array_merge($config, [
  440. 'app_id' => $agent->appid,
  441. 'mch_id' => $agent->mchid,
  442. 'key' => $agent->mchkey,
  443. ]);
  444. $app = Factory::payment($config);
  445. try {
  446. $result = $app->order->unify([
  447. 'body' => mb_strcut($order->title, 0, 127),
  448. 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付
  449. 'total_fee' => round($price * 100), //支付金额单位为分
  450. 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  451. 'trade_type' => 'JSAPI',
  452. 'openid' => $openid,
  453. 'profit_sharing' => 'Y', //Y分账,N不分账,默认不分账,Y大写
  454. ]);
  455. } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) {
  456. return ['error' => $e->getMessage(), 'file' => basename($e->getFile()), 'line' => $e->getLine()];
  457. }
  458. if (empty($result['prepay_id'])) {
  459. return $result;
  460. }
  461. $jssdk = $app->jssdk;
  462. return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组
  463. }
  464. //订单详情
  465. public function show()
  466. {
  467. $id = (int)request()->input('id');
  468. $fields = ['id', 'agent_id', 'order_no', 'agent_product_id', 'num', 'price', 'name', 'mobile', 'title', 'picture', 'status',
  469. 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'verify_code', 'created_at'];
  470. $order = Order::with('agent:id,appid,appsecret')
  471. ->where('user_id', $this->user_id)
  472. ->find($id, $fields);
  473. if (!$order) {
  474. return $this->error('订单不存在');
  475. }
  476. //订单ID和核销码拼接,查询时通过订单ID和核销码来查询,这样核销码不用建索引
  477. $order->verify_code = $order->verify_code ? $order->id . '-' . $order->verify_code : '';
  478. //如果有核销码,生成核销二维码
  479. if ($order->verify_code) {
  480. $app = new OpenPlatform();
  481. $refreshToken = $app->refreshToken($order->agent->appid);
  482. if (!$refreshToken) {
  483. return $this->error('获取refresh_token失败');
  484. }
  485. $app = $app->miniProgram($order->agent->appid, $refreshToken);
  486. //由于参数最多只能32个字符,故通过下面这种方式传参
  487. //pt表示使用普通订单,使用api/verification/verify接口核销;
  488. //hy表示行业产品订单,使用api/verification/industry_verify接口核销
  489. $response = $app->app_code->getUnlimit('pt' . $order->verify_code, ['page' => 'pages/verification/index']);
  490. if ($response instanceof StreamResponse) {
  491. $filename = $response->saveAs(storage_path('app/public/verify_code'), $order->verify_code);
  492. $order->verify_qrcode = Storage::disk('public')->url('verify_code/' . $filename);
  493. }
  494. }
  495. unset($order->agent, $order->agent_id); //必须unset掉$order->agent,否则会造成appsecret泄漏
  496. $order->coupon = Coupon::query()
  497. ->whereIn('id', $order->coupon_id)
  498. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  499. ->get(['tag']);
  500. return $this->success($order);
  501. }
  502. // 生成订单号
  503. private function getOrderNo(): string
  504. {
  505. list($micro, $sec) = explode(' ', microtime());
  506. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  507. return date('ymdHis', $sec) . $micro . mt_rand(1000, 9999);
  508. }
  509. }