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

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