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

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