V1Controller.php 12 KB

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