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

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