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

473 lines
15 KiB

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