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

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