海南旅游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\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) {
  72. $text_arr = [
  73. Status::UNPAID => '付款',
  74. Status::OFFLINE_UNPAID => '线下付款',
  75. Status::PAY_EARNEST => '付尾款',
  76. ];
  77. $v['status_text'] = '请在' . ceil($second / 60) . "分钟内" . ($text_arr[$v['status']] ?? '付款');
  78. } else if ($second < 0 && $v['status'] == Status::PAY_EARNEST) {
  79. $v['status_text'] = '尾款支付已超时';
  80. } /*else { //此部分由定时处理
  81. $timeout_ids[] = $v['id'];
  82. $v['status'] = Status::CANCEL;
  83. $v['status_text'] = '已取消';
  84. //此部分已由定时任务处理
  85. Product::query()->find($v['product_id'])->increment('stock', $v['num']);
  86. }*/
  87. }
  88. }
  89. return $this->success($order_list);
  90. }
  91. //提交订单
  92. public function create(Request $request)
  93. {
  94. $formData = $request->only(['id', 'name', 'mobile', 'pay_type', 'num']);
  95. $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空
  96. //表单验证
  97. $pay_type_values = join(',', array_keys(PayType::array()));
  98. $request->validate([
  99. 'id' => ['required', 'regex:/^\d+$/'],
  100. 'name' => ['required', 'between:2,20'],
  101. 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
  102. 'pay_type' => ['required', 'in:' . $pay_type_values],
  103. 'num' => ['required', 'min:1'],
  104. ], [
  105. 'id.required' => '未指定产品ID',
  106. 'name.required' => '请输入联系人姓名',
  107. 'mobile.required' => '请输入联系手机号',
  108. 'id.regex' => '产品ID错误',
  109. 'name.between' => '联系人姓名在2~20字符之间',
  110. 'mobile.regex' => '请输入11位手机号',
  111. 'pay_type.required' => '请选择支付方式',
  112. 'pay_type.in' => '不存在此支付方式',
  113. 'num.required' => '请输入购买数量',
  114. 'num.min' => '购买数量输入错误',
  115. ]);
  116. $ap = AgentProduct::query()
  117. ->where(['id' => $formData['id'], 'status' => ProductStatus::ON_SALE])
  118. ->where('stock', '>=', $formData['num'])
  119. ->with(['coupon', 'product', 'agentCloudProduct:id,price'])
  120. ->has('product')
  121. ->first();
  122. if (!$ap || !$ap->product) {
  123. return $this->error('产品已下架或库存不足');
  124. }
  125. $coupon_ids = [];
  126. if ($ap->coupon) {
  127. foreach ($ap->coupon as $v) {
  128. $coupon_ids[] = $v['id'];
  129. }
  130. }
  131. DB::beginTransaction();
  132. try {
  133. $price = $this->calc($ap->price, $formData['num'], $formData['pay_type'], $ap);
  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. //未付款时定金/订金的超时时间依然使用默认的订单超时时间,付定金/订金之后才使用定金超时时间
  152. $order_timeout = AgentSetting::val($this->agent_id, 'order_timeout') ?? 60; //默认60分钟
  153. $timeout = date('Y-m-d H:i:s', time() + $order_timeout * 60); //60 * 分钟转为秒
  154. // 存入订单表
  155. $order = Order::query()->create([
  156. 'user_id' => $this->user_id,
  157. 'agent_id' => $this->agent_id,
  158. 'order_no' => $this->getOrderNo(),
  159. 'num' => $formData['num'],
  160. 'price' => $price,
  161. 'name' => $formData['name'],
  162. 'mobile' => $formData['mobile'],
  163. 'title' => $ap->title,
  164. 'picture' => $ap->picture,
  165. 'agent_product_id' => $ap->id,
  166. 'product_id' => $ap->product_id,
  167. 'product_ids' => $ap->product->product_ids ?? $ap->product_id,
  168. 'status' => $formData['pay_type'] == PayType::OFFLINE ? Status::OFFLINE_UNPAID : Status::UNPAID,
  169. 'pay_type' => $formData['pay_type'],
  170. 'coupon_id' => join(',', $coupon_ids),
  171. 'guide_id' => $ap->guide_id,
  172. 'timeout' => $timeout,
  173. 'agent_cloud_pid' => $ap->agent_cloud_pid,
  174. 'agent_cloud_price' => $ap->agentCloudProduct->price ?? 0,
  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. //是否跳转到外部小程序支付(分账测试)
  272. $ap->jump = true;
  273. return $this->success($ap);
  274. }
  275. //订单支付(在订单列表发起)
  276. public function pay(Request $request)
  277. {
  278. $id = (int)request()->input('id');
  279. //订单信息
  280. $order = Order::query()
  281. ->with('agentProduct')
  282. ->where(['user_id' => $this->user_id, 'agent_id' => $this->agent_id])
  283. ->whereRaw('`timeout` >= NOW()')
  284. ->whereIn('status', [Status::UNPAID, Status::PAY_EARNEST])
  285. ->find($id);
  286. if (!$order) {
  287. return $this->error('订单已支付或已超时');
  288. }
  289. $ap = AgentProduct::with('coupon')->find($order->agent_product_id);
  290. //如果已经付定金或首付款,则仅支付尾款
  291. if ($order->status == Status::PAY_EARNEST) {
  292. $price = $order->price - $order->paid_money;
  293. } else {
  294. $price = $this->calc($order->price, $order->num, $order->pay_type, $ap);
  295. }
  296. $config = $this->payConfig($order, $price);
  297. if (!empty($config['paySign'])) {
  298. return $this->success($config);
  299. } else {
  300. return $this->error($config['err_code_des'] ?? join(',', $config));
  301. }
  302. }
  303. //获取支付配置信息
  304. private function payConfig($order, $price)
  305. {
  306. //用户openid
  307. $openid = User::query()->where('id', $this->user_id)->value('openid'); //此处要用where,value()用find有BUG
  308. //代理商信息
  309. $agent = Agent::query()->find($this->agent_id);
  310. $config = config('wechat.payment.default');
  311. $config = array_merge($config, [
  312. 'app_id' => $agent->appid,
  313. 'mch_id' => $agent->mchid,
  314. 'key' => $agent->mchkey,
  315. ]);
  316. $app = Factory::payment($config);
  317. try {
  318. $result = $app->order->unify([
  319. 'body' => $order->title,
  320. 'out_trade_no' => $order->order_no . '-' . $order->status, //后面加status,主要是为了方便微信支付回调时区分定金(首付款)和尾款支付
  321. 'total_fee' => 1, //TODO 测试暂时注释 round($price * 100), //支付金额单位为分
  322. 'notify_url' => route('wxpay_notify', ['agent_id' => $this->agent_id]), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  323. 'trade_type' => 'JSAPI',
  324. 'openid' => $openid,
  325. 'profit_sharing' => 'Y', //Y分账,N不分账,默认不分账,Y大写
  326. ]);
  327. } catch (InvalidArgumentException | InvalidConfigException | GuzzleException $e) {
  328. return ['error' => $e->getMessage(), 'line' => $e->getLine()];
  329. }
  330. if (empty($result['prepay_id'])) {
  331. return $result;
  332. }
  333. $jssdk = $app->jssdk;
  334. return $jssdk->bridgeConfig($result['prepay_id'], false) + ['id' => $order->id, 'order_no' => $order->order_no]; // 返回数组
  335. }
  336. //订单详情
  337. public function show()
  338. {
  339. $id = (int)request()->input('id');
  340. $fields = ['id', 'agent_id', 'order_no', 'agent_product_id', 'num', 'price', 'name', 'mobile', 'title', 'picture', 'status',
  341. 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'verify_code', 'created_at'];
  342. $order = Order::with('agent:id,appid,appsecret')
  343. ->where('user_id', $this->user_id)
  344. ->find($id, $fields);
  345. if (!$order) {
  346. return $this->error('订单不存在');
  347. }
  348. //订单ID和核销码拼接,查询时通过订单ID和核销码来查询,这样核销码不用建索引
  349. $order->verify_code = $order->verify_code ? $order->id . '-' . $order->verify_code : '';
  350. //如果有核销码,生成核销二维码
  351. if ($order->verify_code) {
  352. $config = [
  353. 'app_id' => $order->agent->appid,
  354. 'secret' => $order->agent->appsecret,
  355. ];
  356. $app = Factory::miniProgram($config);
  357. $response = $app->app_code->getUnlimit($order->verify_code, ['page' => 'pages/verification/index']);
  358. if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
  359. $filename = $response->saveAs(storage_path('app/public/verify_code'), $order->verify_code);
  360. $order->verify_qrcode = Storage::disk('public')->url('verify_code/' . $filename);
  361. }
  362. }
  363. unset($order->agent, $order->agent_id); //必须unset掉$order->agent,否则会造成appsecret泄漏
  364. $order->coupon = Coupon::query()
  365. ->whereIn('id', $order->coupon_id)
  366. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  367. ->get(['tag']);
  368. return $this->success($order);
  369. }
  370. /**
  371. * 计算最终价格(扣除优惠券之后的价格)
  372. * $price:原价;$coupon:优惠券;$num:产品数量;$pay_type:支付方式
  373. * @param float $price
  374. * @param int $num
  375. * @param int $pay_type
  376. * @param Model $agent_product
  377. * @return float
  378. */
  379. private function calc($price, $num, $pay_type, $agent_product)
  380. {
  381. //根据支付方式计算价格
  382. if (in_array($pay_type, [PayType::DEPOSIT_PAY, PayType::EARNEST_PAY, PayType::DOWN_PAYMENT])) {
  383. if ($pay_type == PayType::DEPOSIT_PAY && $agent_product->deposit && $agent_product->deposit_timeout) {
  384. return $agent_product->deposit;
  385. }
  386. if ($pay_type == PayType::EARNEST_PAY && $agent_product->earnest && $agent_product->earnest_timeout) {
  387. return $agent_product->earnest;
  388. }
  389. }
  390. $total_price = $price * $num;
  391. /*//没有任何优惠券时直接返回最终价
  392. if ($coupon && $coupon->isEmpty()) {
  393. return $total_price;
  394. }
  395. $coupon = $coupon->toArray();
  396. foreach ($coupon as $v) {
  397. // TODO 未判断优惠券有效期
  398. if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  399. if ($total_price >= $v['detail']['full']) {
  400. $total_price -= $v['detail']['reduction'];
  401. }
  402. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  403. $total_price *= $v['detail']['discount'];
  404. }
  405. }*/
  406. return round($total_price, 2);
  407. }
  408. // 生成订单号
  409. private function getOrderNo(): string
  410. {
  411. list($micro, $sec) = explode(' ', microtime());
  412. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  413. return date('ymdHis', $sec) . $micro . mt_rand(1000, 9999);
  414. }
  415. }