V1Controller.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. namespace App\Http\Controllers\Api\Client;
  3. use App\Components\Helpers;
  4. use App\Http\Controllers\Controller;
  5. use App\Http\Controllers\PaymentController;
  6. use App\Models\Coupon;
  7. use App\Models\Goods;
  8. use App\Models\GoodsCategory;
  9. use App\Models\Order;
  10. use App\Models\ReferralLog;
  11. use App\Models\User;
  12. use Exception;
  13. use Hashids\Hashids;
  14. use Illuminate\Http\JsonResponse;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\Cache;
  17. use Log;
  18. use Validator;
  19. class V1Controller extends Controller
  20. {
  21. private static $method;
  22. public function __construct()
  23. {
  24. $this->middleware('auth:api', ['except' => ['login', 'register', 'shop', 'config', 'getConfig']]);
  25. auth()->shouldUse('api');
  26. }
  27. /**
  28. * @param Request $request
  29. * @return JsonResponse
  30. */
  31. public static function getStatus(Request $request): JsonResponse
  32. {
  33. $order_id = $request->input('order_id');
  34. $payment = Order::query()->find($order_id)->payment;
  35. if ($payment) {
  36. if ($payment->status === 1) {
  37. return response()->json(['ret' => 1, 'msg' => '支付成功']);
  38. }
  39. if ($payment->status === -1) {
  40. return response()->json(['ret' => 0, 'msg' => '订单超时未支付,已自动关闭']);
  41. }
  42. return response()->json(['ret' => 0, 'msg' => '等待支付']);
  43. }
  44. return response()->json(['ret' => 0, 'msg' => '未知订单']);
  45. }
  46. public function login(Request $request)
  47. {
  48. $validator = Validator::make($request->all(), [
  49. 'username' => 'required|'.(sysConfig('username_type') ?? 'email'),
  50. 'password' => 'required|string|min:6',
  51. ]);
  52. if ($validator->fails()) {
  53. return response()->json(['ret' => 0, 'msg' => $validator->errors()->all()], 422);
  54. }
  55. if ($token = auth()->attempt($validator->validated())) {
  56. return $this->createNewToken($token);
  57. }
  58. return response()->json(['ret' => 0, 'msg' => '登录信息错误'], 401);
  59. }
  60. protected function createNewToken($token)
  61. {
  62. return response()->json([
  63. 'ret' => 1,
  64. 'data' => [
  65. 'access_token' => $token,
  66. 'token_type' => 'bearer',
  67. 'expires_in' => auth()->factory()->getTTL() * 60,
  68. 'user' => auth()->user()->profile(),
  69. ],
  70. ]);
  71. }
  72. public function register(Request $request)
  73. {
  74. $validator = Validator::make($request->all(), [
  75. 'name' => 'required|string|between:2,100',
  76. 'username' => 'required|'.(sysConfig('username_type') ?? 'email').'|max:100|unique:user,username',
  77. 'password' => 'required|string|confirmed|min:6',
  78. ]);
  79. if ($validator->fails()) {
  80. return response()->json($validator->errors()->all(), 400);
  81. }
  82. $user = User::create(array_merge(
  83. $validator->validated(),
  84. ['password' => $request->password]
  85. ));
  86. return response()->json(['ret' => 1, 'user' => $user], 201);
  87. }
  88. public function logout()
  89. {
  90. auth()->logout();
  91. return response()->json(['ret' => 1]);
  92. }
  93. public function refresh()
  94. {
  95. return $this->createNewToken(auth()->refresh());
  96. }
  97. public function userProfile()
  98. {
  99. $user = auth()->user();
  100. $userInfo = $user->profile();
  101. $userInfo['subUrl'] = $user->subUrl();
  102. $totalTransfer = $user->transfer_enable;
  103. $usedTransfer = $user->used_traffic;
  104. $unusedTraffic = $totalTransfer - $usedTransfer > 0 ? $totalTransfer - $usedTransfer : 0;
  105. $userInfo['unusedTraffic'] = flowAutoShow($unusedTraffic);
  106. return response()->json(['ret' => 1, 'data' => $userInfo]);
  107. }
  108. public function nodeList(int $id = null)
  109. {
  110. $user = auth()->user();
  111. $nodes = $user->nodes()->get();
  112. return response()->json(['ret' => 1, 'data' => $nodes]);
  113. }
  114. public function shop()
  115. {
  116. $shops = [
  117. 'keys' => [],
  118. 'data' => [],
  119. ];
  120. foreach (GoodsCategory::query()->whereStatus(1)->get() as $item) {
  121. $shops['keys'][] = $item['name'];
  122. $shops['data'][$item['name']] = $item->goods()->get()->append('traffic_label')->toArray();
  123. }
  124. return response()->json(['ret' => 1, 'data' => $shops]);
  125. }
  126. public function getConfig()
  127. {
  128. $config = config('bobclient');
  129. $config['website_name'] = sysConfig('website_name');
  130. $config['website_url'] = sysConfig('website_url');
  131. $config['payment'] = [
  132. 'alipay' => sysConfig('is_AliPay'),
  133. 'wechat' => sysConfig('is_WeChatPay'),
  134. ];
  135. return response()->json(['ret' => 1, 'data' => $config]);
  136. }
  137. public function purchase(Request $request)
  138. {
  139. $goods_id = $request->input('goods_id');
  140. $coupon_sn = $request->input('coupon_sn');
  141. self::$method = $request->input('method');
  142. $credit = $request->input('amount');
  143. $pay_type = $request->input('pay_type');
  144. $amount = 0;
  145. // 充值余额
  146. if ($credit) {
  147. if (! is_numeric($credit) || $credit <= 0) {
  148. return response()->json(['ret' => 0, 'msg' => trans('user.payment.error')]);
  149. }
  150. $amount = $credit;
  151. // 购买服务
  152. } elseif ($goods_id && self::$method) {
  153. $goods = Goods::find($goods_id);
  154. if (! $goods || ! $goods->status) {
  155. return response()->json(['ret' => 0, 'msg' => '订单创建失败:商品已下架']);
  156. }
  157. $amount = $goods->price;
  158. // 是否有生效的套餐
  159. $activePlan = Order::userActivePlan()->doesntExist();
  160. // 无生效套餐,禁止购买加油包
  161. if ($goods->type === 1 && $activePlan) {
  162. return response()->json(['ret' => 0, 'msg' => '购买加油包前,请先购买套餐']);
  163. }
  164. // 单个商品限购
  165. if ($goods->limit_num) {
  166. $count = Order::uid()->where('status', '>=', 0)->whereGoodsId($goods_id)->count();
  167. if ($count >= $goods->limit_num) {
  168. return response()->json(['ret' => 0, 'msg' => '此商品限购'.$goods->limit_num.'次,您已购买'.$count.'次']);
  169. }
  170. }
  171. // 使用优惠券
  172. if ($coupon_sn) {
  173. $coupon = Coupon::whereStatus(0)->whereIn('type', [1, 2])->whereSn($coupon_sn)->first();
  174. if (! $coupon) {
  175. return response()->json(['ret' => 0, 'msg' => '订单创建失败:优惠券不存在']);
  176. }
  177. // 计算实际应支付总价
  178. $amount = $coupon->type === 2 ? $goods->price * $coupon->value / 100 : $goods->price - $coupon->value;
  179. $amount = $amount > 0 ? round($amount, 2) : 0; // 四舍五入保留2位小数,避免无法正常创建订单
  180. }
  181. //非余额付款下,检查在线支付是否开启
  182. if (self::$method !== 'credit') {
  183. // 判断是否开启在线支付
  184. if (! sysConfig('is_onlinePay')) {
  185. return response()->json(['ret' => 0, 'msg' => '订单创建失败:系统并未开启在线支付功能']);
  186. }
  187. // 判断是否存在同个商品的未支付订单
  188. if (Order::uid()->whereStatus(0)->exists()) {
  189. return response()->json(['ret' => 0, 'msg' => '订单创建失败:尚有未支付的订单,请先去支付']);
  190. }
  191. } elseif (Auth::getUser()->credit < $amount) { // 验证账号余额是否充足
  192. return response()->json(['ret' => 0, 'msg' => '您的余额不足,请先充值']);
  193. }
  194. // 价格异常判断
  195. if ($amount < 0) {
  196. return response()->json(['ret' => 0, 'msg' => '订单创建失败:订单总价异常']);
  197. }
  198. if ($amount === 0 && self::$method !== 'credit') {
  199. return response()->json(['ret' => 0, 'msg' => '订单创建失败:订单总价为0,无需使用在线支付']);
  200. }
  201. }
  202. // 生成订单
  203. try {
  204. $newOrder = Order::create([
  205. 'sn' => date('ymdHis').random_int(100000, 999999),
  206. 'user_id' => auth()->id(),
  207. 'goods_id' => $credit ? null : $goods_id,
  208. 'coupon_id' => $coupon->id ?? null,
  209. 'origin_amount' => $credit ?: ($goods->price ?? 0),
  210. 'amount' => $amount,
  211. 'pay_type' => $pay_type,
  212. 'pay_way' => self::$method,
  213. ]);
  214. // 使用优惠券,减少可使用次数
  215. if (! empty($coupon)) {
  216. if ($coupon->usable_times > 0) {
  217. $coupon->decrement('usable_times', 1);
  218. }
  219. Helpers::addCouponLog('订单支付使用', $coupon->id, $goods_id, $newOrder->id);
  220. }
  221. $request->merge(['id' => $newOrder->id, 'type' => $pay_type, 'amount' => $amount]);
  222. PaymentController::$method = self::$method;
  223. // 生成支付单
  224. $data = PaymentController::getClient()->purchase($request);
  225. $data = $data->getData(true);
  226. $data['order_id'] = $newOrder->id;
  227. return response()->json($data);
  228. } catch (Exception $e) {
  229. Log::error('订单生成错误:'.$e->getMessage());
  230. }
  231. return response()->json(['ret' => 0, 'msg' => '订单创建失败']);
  232. }
  233. public function gift(Request $request)
  234. {
  235. $user = $request->user('api');
  236. $referral_traffic = flowAutoShow(sysConfig('referral_traffic') * MB);
  237. $referral_percent = sysConfig('referral_percent');
  238. // 邀请码
  239. $code = $user->invites()->whereStatus(1)->value('code');
  240. $data['invite_gift'] = trans('user.invite.promotion', [
  241. 'traffic' => $referral_traffic,
  242. 'referral_percent' => $referral_percent * 100,
  243. ]);
  244. $affSalt = sysConfig('aff_salt');
  245. if (isset($affSalt)) {
  246. $aff_link = route('register', ['aff' => (new Hashids($affSalt, 8))->encode($user->id)]);
  247. } else {
  248. $aff_link = route('register', ['aff' => $user->id]);
  249. }
  250. $data['invite_url'] = $aff_link;
  251. $data['invite_text'] = $aff_link.'&(复制整段文字到浏览器打开即可访问),找梯子最重要的就是稳定,这个已经上线三年了,一直稳定没有被封过,赶紧下载备用吧!安装后打开填写我的邀请码【'.$code.'】,你还能多得3天会员.';
  252. // 累计数据
  253. $data['back_sum'] = ReferralLog::query()->where('inviter_id', $user->id)->sum('commission') / 100;
  254. $data['user_sum'] = $user->invitees()->count();
  255. $data['list'] = $user->invitees()->selectRaw('username, UNIX_TIMESTAMP(created_at) as created_at')->limit(10)->get();
  256. return response()->json(['ret' => 1, 'data' => $data]);
  257. }
  258. public function checkIn(Request $request): JsonResponse
  259. {
  260. $user = $request->user();
  261. // 系统开启登录加积分功能才可以签到
  262. if (! sysConfig('is_checkin')) {
  263. return response()->json(['ret' => 0, 'title' => trans('common.failed'), 'msg' => trans('user.home.attendance.disable')]);
  264. }
  265. // 已签到过,验证是否有效
  266. if (Cache::has('userCheckIn_'.$user->id)) {
  267. return response()->json(['ret' => 0, 'title' => trans('common.success'), 'msg' => trans('user.home.attendance.done')]);
  268. }
  269. $traffic = random_int((int) sysConfig('min_rand_traffic'), (int) sysConfig('max_rand_traffic')) * MB;
  270. if (! $user->incrementData($traffic)) {
  271. return response()->json(['ret' => 0, 'title' => trans('common.failed'), 'msg' => trans('user.home.attendance.failed')]);
  272. }
  273. // 写入用户流量变动记录
  274. Helpers::addUserTrafficModifyLog($user->id, null, $user->transfer_enable, $user->transfer_enable + $traffic, trans('user.home.attendance.attribute'));
  275. // 多久后可以再签到
  276. $ttl = sysConfig('traffic_limit_time') ? sysConfig('traffic_limit_time') * Minute : Day;
  277. Cache::put('userCheckIn_'.$user->id, '1', $ttl);
  278. return response()->json(['ret' => 1, 'msg' => trans('user.home.attendance.success', ['data' => flowAutoShow($traffic)])]);
  279. }
  280. }