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

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