diff --git a/app/Exceptions/ApiException.php b/app/Exceptions/ApiException.php index 4ef4283..374f354 100644 --- a/app/Exceptions/ApiException.php +++ b/app/Exceptions/ApiException.php @@ -10,7 +10,7 @@ class ApiException extends Exception protected $message; // 错误消息 protected $errors; // 全部错误信息 - public function __construct($code = 400, $message = null, $errors = null) + public function __construct($message = null, $code = 400, $errors = null) { $this->message = $message; $this->code = $code; diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 78aeaa1..ee26a4e 100755 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -58,7 +58,7 @@ class Handler extends ExceptionHandler public function render($request, Throwable $exception) { if ($exception instanceof ViewException) { - $this->fail([500, '主题渲染失败。如更新主题,参数可能发生变化请重新配置主题后再试。']); + return $this->fail([500, '主题渲染失败。如更新主题,参数可能发生变化请重新配置主题后再试。']); } // ApiException主动抛出错误 if ($exception instanceof ApiException) { diff --git a/app/Helpers/ApiResponse.php b/app/Helpers/ApiResponse.php index 9561103..cc96e61 100644 --- a/app/Helpers/ApiResponse.php +++ b/app/Helpers/ApiResponse.php @@ -47,7 +47,7 @@ trait ApiResponse return response() ->json([ 'status' => $status, - 'code' => $code, + // 'code' => $code, 'message' => $message, 'data' => $data ?? null, 'error' => $error, diff --git a/app/Http/Controllers/V1/Admin/ConfigController.php b/app/Http/Controllers/V1/Admin/ConfigController.php index 2932345..a85109a 100755 --- a/app/Http/Controllers/V1/Admin/ConfigController.php +++ b/app/Http/Controllers/V1/Admin/ConfigController.php @@ -19,9 +19,7 @@ class ConfigController extends Controller $files = array_map(function ($item) use ($path) { return str_replace($path, '', $item); }, glob($path . '*')); - return response([ - 'data' => $files - ]); + return $this->success($files); } public function getThemeTemplate() @@ -30,9 +28,7 @@ class ConfigController extends Controller $files = array_map(function ($item) use ($path) { return str_replace($path, '', $item); }, glob($path . '*')); - return response([ - 'data' => $files - ]); + return $this->success($files); } public function testSendMail(Request $request) @@ -59,9 +55,7 @@ class ConfigController extends Controller $telegramService = new TelegramService($request->input('telegram_bot_token')); $telegramService->getMe(); $telegramService->setWebhook($hookUrl); - return response([ - 'data' => true - ]); + return $this->success(true); } public function fetch(Request $request) @@ -163,16 +157,12 @@ class ConfigController extends Controller ] ]; if ($key && isset($data[$key])) { - return response([ - 'data' => [ - $key => $data[$key] - ] + return $this->success([ + $key => $data[$key] ]); }; // TODO: default should be in Dict - return response([ - 'data' => $data - ]); + return $this->success($data); } public function save(ConfigSave $request) @@ -196,8 +186,6 @@ class ConfigController extends Controller Cache::forget('admin_settings'); // \Artisan::call('horizon:terminate'); //重启队列使配置生效 - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/CouponController.php b/app/Http/Controllers/V1/Admin/CouponController.php index a5b29cf..4674820 100644 --- a/app/Http/Controllers/V1/Admin/CouponController.php +++ b/app/Http/Controllers/V1/Admin/CouponController.php @@ -31,21 +31,21 @@ class CouponController extends Controller public function show(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数有误'); - } + $request->validate([ + 'id' => 'required|numeric' + ],[ + 'id.required' => '优惠券ID不能为空', + 'id.numeric' => '优惠券ID必须为数字' + ]); $coupon = Coupon::find($request->input('id')); if (!$coupon) { - throw new ApiException(500, '优惠券不存在'); + return $this->fail([400202,'优惠券不存在']); } $coupon->show = !$coupon->show; if (!$coupon->save()) { - throw new ApiException(500, '保存失败'); + return $this->fail([500,'保存失败']); } - - return response([ - 'data' => true - ]); + return $this->success(true); } public function generate(CouponGenerate $request) @@ -61,19 +61,18 @@ class CouponController extends Controller $params['code'] = Helper::randomChar(8); } if (!Coupon::create($params)) { - throw new ApiException(500, '创建失败'); + return $this->fail([500,'创建失败']); } } else { try { Coupon::find($request->input('id'))->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } } - return response([ - 'data' => true - ]); + return $this->success(true); } private function multiGenerate(CouponGenerate $request) @@ -99,12 +98,12 @@ class CouponController extends Controller } return $item; }, $coupons))) { - throw new ApiException(500, '生成失败'); + throw new \Exception(); } DB::commit(); }catch(\Exception $e){ DB::rollBack(); - throw $e; + return $this->fail([500, '生成失败']); } $data = "名称,类型,金额或比例,开始时间,结束时间,可用次数,可用于订阅,券码,生成时间\r\n"; @@ -123,19 +122,20 @@ class CouponController extends Controller public function drop(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数有误'); - } + $request->validate([ + 'id' => 'required|numeric' + ],[ + 'id.required' => '优惠券ID不能为空', + 'id.numeric' => '优惠券ID必须为数字' + ]); $coupon = Coupon::find($request->input('id')); if (!$coupon) { - throw new ApiException(500, '优惠券不存在'); + return $this->fail([400202,'优惠券不存在']); } if (!$coupon->delete()) { - throw new ApiException(500, '删除失败'); + return $this->fail([500,'删除失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/KnowledgeController.php b/app/Http/Controllers/V1/Admin/KnowledgeController.php index 25c7a71..991c9dc 100644 --- a/app/Http/Controllers/V1/Admin/KnowledgeController.php +++ b/app/Http/Controllers/V1/Admin/KnowledgeController.php @@ -16,23 +16,18 @@ class KnowledgeController extends Controller { if ($request->input('id')) { $knowledge = Knowledge::find($request->input('id'))->toArray(); - if (!$knowledge) throw new ApiException(500, '知识不存在'); - return response([ - 'data' => $knowledge - ]); + if (!$knowledge) return $this->fail([400202,'知识不存在']); + return $this->success($knowledge); } - return response([ - 'data' => Knowledge::select(['title', 'id', 'updated_at', 'category', 'show']) - ->orderBy('sort', 'ASC') - ->get() - ]); + $data = Knowledge::select(['title', 'id', 'updated_at', 'category', 'show']) + ->orderBy('sort', 'ASC') + ->get(); + return $this->success($data); } public function getCategory(Request $request) { - return response([ - 'data' => array_keys(Knowledge::get()->groupBy('category')->toArray()) - ]); + return $this->success(array_keys(Knowledge::get()->groupBy('category')->toArray())); } public function save(KnowledgeSave $request) @@ -41,38 +36,37 @@ class KnowledgeController extends Controller if (!$request->input('id')) { if (!Knowledge::create($params)) { - throw new ApiException(500, '创建失败'); + return $this->fail([500,'创建失败']); } } else { try { Knowledge::find($request->input('id'))->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'创建失败']); } } - return response([ - 'data' => true - ]); + return $this->success(true); } public function show(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数有误'); - } + $request->validate([ + 'id' => 'required|numeric' + ],[ + 'id.required' => '知识库ID不能为空' + ]); $knowledge = Knowledge::find($request->input('id')); if (!$knowledge) { - throw new ApiException(500, '知识不存在'); + throw new ApiException('知识不存在'); } - $knowledge->show = $knowledge->show ? 0 : 1; + $knowledge->show = !$knowledge->show; if (!$knowledge->save()) { - throw new ApiException(500, '保存失败'); + throw new ApiException('保存失败'); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function sort(KnowledgeSort $request) @@ -87,28 +81,26 @@ class KnowledgeController extends Controller DB::commit(); } catch (\Exception $e) { DB::rollBack(); - throw new ApiException(500, '保存失败'); + throw new ApiException('保存失败'); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数有误'); - } + $request->validate([ + 'id' => 'required|numeric' + ],[ + 'id.required' => '知识库ID不能为空' + ]); $knowledge = Knowledge::find($request->input('id')); if (!$knowledge) { - throw new ApiException(500, '知识不存在'); + return $this->fail([400202,'知识不存在']); } if (!$knowledge->delete()) { - throw new ApiException(500, '删除失败'); + return $this->fail([500,'删除失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/NoticeController.php b/app/Http/Controllers/V1/Admin/NoticeController.php index 511973b..49a1c49 100644 --- a/app/Http/Controllers/V1/Admin/NoticeController.php +++ b/app/Http/Controllers/V1/Admin/NoticeController.php @@ -12,9 +12,7 @@ class NoticeController extends Controller { public function fetch(Request $request) { - return response([ - 'data' => Notice::orderBy('id', 'DESC')->get() - ]); + return $this->success(Notice::orderBy('id', 'DESC')->get()); } public function save(NoticeSave $request) @@ -27,18 +25,16 @@ class NoticeController extends Controller ]); if (!$request->input('id')) { if (!Notice::create($data)) { - throw new ApiException(500, '保存失败'); + return $this->fail([500 ,'保存失败']); } } else { try { Notice::find($request->input('id'))->update($data); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + return $this->fail([500 ,'保存失败']); } } - return response([ - 'data' => true - ]); + return $this->success(true); } @@ -46,36 +42,32 @@ class NoticeController extends Controller public function show(Request $request) { if (empty($request->input('id'))) { - throw new ApiException(422, '参数有误'); + return $this->fail([500 ,'公告ID不能为空']); } $notice = Notice::find($request->input('id')); if (!$notice) { - throw new ApiException(500, '公告不存在'); + return $this->fail([400202 ,'公告不存在']); } $notice->show = $notice->show ? 0 : 1; if (!$notice->save()) { - throw new ApiException(500, '保存失败'); + return $this->fail([500 ,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) { if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); + return $this->fail([422 ,'公告ID不能为空']); } $notice = Notice::find($request->input('id')); if (!$notice) { - throw new ApiException(500, '公告不存在'); + return $this->fail([400202 ,'公告不存在']); } if (!$notice->delete()) { - throw new ApiException(500, '删除失败'); + return $this->fail([500 ,'删除失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/OrderController.php b/app/Http/Controllers/V1/Admin/OrderController.php index 293ec33..2462cda 100644 --- a/app/Http/Controllers/V1/Admin/OrderController.php +++ b/app/Http/Controllers/V1/Admin/OrderController.php @@ -41,14 +41,12 @@ class OrderController extends Controller public function detail(Request $request) { $order = Order::find($request->input('id')); - if (!$order) throw new ApiException(500, '订单不存在'); + if (!$order) return $this->fail([400202 ,'订单不存在']); $order['commission_log'] = CommissionLog::where('trade_no', $order->trade_no)->get(); if ($order->surplus_order_ids) { $order['surplus_orders'] = Order::whereIn('id', $order->surplus_order_ids)->get(); } - return response([ - 'data' => $order - ]); + return $this->success($order); } public function fetch(OrderFetch $request) @@ -84,17 +82,15 @@ class OrderController extends Controller $order = Order::where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - throw new ApiException(500, '订单不存在'); + return $this->fail([400202 ,'订单不存在']); } - if ($order->status !== 0) throw new ApiException(500, '只能对待支付的订单进行操作'); + if ($order->status !== 0) return $this->fail([400 ,'只能对待支付的订单进行操作']); $orderService = new OrderService($order); if (!$orderService->paid('manual_operation')) { - throw new ApiException(500, '更新失败'); + return $this->fail([500 ,'更新失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function cancel(Request $request) @@ -102,17 +98,15 @@ class OrderController extends Controller $order = Order::where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - throw new ApiException(500, '订单不存在'); + return $this->fail([400202 ,'订单不存在']); } - if ($order->status !== 0) throw new ApiException(500, '只能对待支付的订单进行操作'); + if ($order->status !== 0) return $this->fail([400 ,'只能对待支付的订单进行操作']); $orderService = new OrderService($order); if (!$orderService->cancel()) { - throw new ApiException(500, '更新失败'); + return $this->fail([400 ,'更新失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function update(OrderUpdate $request) @@ -124,18 +118,17 @@ class OrderController extends Controller $order = Order::where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - throw new ApiException(500, '订单不存在'); + return $this->fail([400202 ,'订单不存在']); } try { $order->update($params); } catch (\Exception $e) { - throw new ApiException(500, '更新失败'); + \Log::error($e); + return $this->fail([500 ,'更新失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function assign(OrderAssign $request) @@ -144,16 +137,16 @@ class OrderController extends Controller $user = User::where('email', $request->input('email'))->first(); if (!$user) { - throw new ApiException(500, '该用户不存在'); + return $this->fail([400202 ,'该用户不存在']); } if (!$plan) { - throw new ApiException(500, '该订阅不存在'); + return $this->fail([400202 ,'该订阅不存在']); } $userService = new UserService(); if ($userService->isNotCompleteOrderByUserId($user->id)) { - throw new ApiException(500, '该用户还有待支付的订单,无法分配'); + return $this->fail([400 ,'该用户还有待支付的订单,无法分配']); } try { @@ -179,7 +172,7 @@ class OrderController extends Controller $orderService->setInvite($user); if (!$order->save()) { - throw new ApiException(500, '订单创建失败'); + return $this->fail([500 ,'订单创建失败']); } DB::commit(); }catch(\Exception $e){ @@ -187,8 +180,6 @@ class OrderController extends Controller throw $e; } - return response([ - 'data' => $order->trade_no - ]); + return $this->success($order->trade_no); } } diff --git a/app/Http/Controllers/V1/Admin/PaymentController.php b/app/Http/Controllers/V1/Admin/PaymentController.php index e7c5223..039d832 100644 --- a/app/Http/Controllers/V1/Admin/PaymentController.php +++ b/app/Http/Controllers/V1/Admin/PaymentController.php @@ -18,9 +18,7 @@ class PaymentController extends Controller foreach (glob(base_path('app//Payments') . '/*.php') as $file) { array_push($methods, pathinfo($file)['filename']); } - return response([ - 'data' => $methods - ]); + return $this->success($methods); } public function fetch() @@ -34,34 +32,28 @@ class PaymentController extends Controller } $payments[$k]['notify_url'] = $notifyUrl; } - return response([ - 'data' => $payments - ]); + return $this->success($payments); } public function getPaymentForm(Request $request) { $paymentService = new PaymentService($request->input('payment'), $request->input('id')); - return response([ - 'data' => $paymentService->form() - ]); + return $this->success($paymentService->form()); } public function show(Request $request) { $payment = Payment::find($request->input('id')); - if (!$payment) throw new ApiException(500, '支付方式不存在'); + if (!$payment) return $this->fail([400202 ,'支付方式不存在']); $payment->enable = !$payment->enable; - if (!$payment->save()) throw new ApiException(500, '保存失败'); - return response([ - 'data' => true - ]); + if (!$payment->save()) return $this->fail([500 ,'保存失败']); + return $this->success(true); } public function save(Request $request) { if (!admin_setting('app_url')) { - throw new ApiException(500, '请在站点配置中配置站点地址'); + return $this->fail([400 ,'请在站点配置中配置站点地址']); } $params = $request->validate([ 'name' => 'required', @@ -81,32 +73,27 @@ class PaymentController extends Controller ]); if ($request->input('id')) { $payment = Payment::find($request->input('id')); - if (!$payment) throw new ApiException(500, '支付方式不存在'); + if (!$payment) return $this->fail([400202 ,'支付方式不存在']); try { $payment->update($params); } catch (\Exception $e) { - throw new ApiException(500, $e->getMessage()); + \Log::error($e); + return $this->fail([500 ,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } $params['uuid'] = Helper::randomChar(8); if (!Payment::create($params)) { - throw new ApiException(500, '保存失败'); + return $this->fail([500 ,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) { $payment = Payment::find($request->input('id')); - if (!$payment) throw new ApiException(500, '支付方式不存在'); - return response([ - 'data' => $payment->delete() - ]); + if (!$payment) return $this->fail([400202 ,'支付方式不存在']); + return $this->success($payment->delete()); } @@ -122,17 +109,15 @@ class PaymentController extends Controller DB::beginTransaction(); foreach ($request->input('ids') as $k => $v) { if (!Payment::find($v)->update(['sort' => $k + 1])) { - throw new ApiException(500, '保存失败'); + throw new \Exception(); } } DB::commit(); }catch(\Exception $e){ DB::rollBack(); - throw $e; + return $this->fail([500 ,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/PlanController.php b/app/Http/Controllers/V1/Admin/PlanController.php index b2a3293..79c63c7 100755 --- a/app/Http/Controllers/V1/Admin/PlanController.php +++ b/app/Http/Controllers/V1/Admin/PlanController.php @@ -26,9 +26,7 @@ class PlanController extends Controller if ($plans[$k]->id === $counts[$kk]->plan_id) $plans[$k]->count = $counts[$kk]->count; } } - return response([ - 'data' => $plans - ]); + return $this->success($plans); } public function save(PlanSave $request) @@ -37,7 +35,7 @@ class PlanController extends Controller if ($request->input('id')) { $plan = Plan::find($request->input('id')); if (!$plan) { - throw new ApiException(500, '该订阅不存在'); + return $this->fail([400202 ,'该订阅不存在']); } DB::beginTransaction(); // update user group id and transfer @@ -53,37 +51,32 @@ class PlanController extends Controller DB::commit(); } catch (\Exception $e) { DB::rollBack(); - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500 ,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } if (!Plan::create($params)) { - throw new ApiException(500, '创建失败'); + return $this->fail([500 ,'创建失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) { if (Order::where('plan_id', $request->input('id'))->first()) { - throw new ApiException(500, '该订阅下存在订单无法删除'); + return $this->fail([400201 ,'该订阅下存在订单无法删除']); } if (User::where('plan_id', $request->input('id'))->first()) { - throw new ApiException(500, '该订阅下存在用户无法删除'); + return $this->fail([400201 ,'该订阅下存在用户无法删除']); } if ($request->input('id')) { $plan = Plan::find($request->input('id')); if (!$plan) { - throw new ApiException(500, '该订阅ID不存在'); + return $this->fail([400202 ,'该订阅不存在']); } } - return response([ - 'data' => $plan->delete() - ]); + return $this->success($plan->delete()); } public function update(PlanUpdate $request) @@ -95,13 +88,14 @@ class PlanController extends Controller $plan = Plan::find($request->input('id')); if (!$plan) { - throw new ApiException(500, '该订阅不存在'); + return $this->fail([400202 ,'该订阅不存在']); } try { $plan->update($updateData); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500 ,'保存失败']); } return $this->success(); @@ -114,13 +108,14 @@ class PlanController extends Controller DB::beginTransaction(); foreach ($request->input('plan_ids') as $k => $v) { if (!Plan::find($v)->update(['sort' => $k + 1])) { - throw new ApiException(500, '保存失败'); + throw new \Exception(); } } DB::commit(); }catch (\Exception $e){ DB::rollBack(); - throw $e; + \Log::error($e); + return $this->fail([500 ,'保存失败']); } return $this->success(true); } diff --git a/app/Http/Controllers/V1/Admin/Server/GroupController.php b/app/Http/Controllers/V1/Admin/Server/GroupController.php index fc3b515..40b544a 100644 --- a/app/Http/Controllers/V1/Admin/Server/GroupController.php +++ b/app/Http/Controllers/V1/Admin/Server/GroupController.php @@ -16,9 +16,7 @@ class GroupController extends Controller public function fetch(Request $request) { if ($request->input('group_id')) { - return response([ - 'data' => [ServerGroup::find($request->input('group_id'))] - ]); + return $this->success([ServerGroup::find($request->input('group_id'))]); } $serverGroups = ServerGroup::get(); $serverService = new ServerService(); @@ -32,15 +30,13 @@ class GroupController extends Controller } } } - return response([ - 'data' => $serverGroups - ]); + return $this->success($serverGroups); } public function save(Request $request) { if (empty($request->input('name'))) { - throw new ApiException(500, '组名不能为空'); + return $this->fail([422,'组名不能为空']); } if ($request->input('id')) { @@ -50,9 +46,7 @@ class GroupController extends Controller } $serverGroup->name = $request->input('name'); - return response([ - 'data' => $serverGroup->save() - ]); + return $this->success($serverGroup->save()); } public function drop(Request $request) @@ -60,25 +54,23 @@ class GroupController extends Controller if ($request->input('id')) { $serverGroup = ServerGroup::find($request->input('id')); if (!$serverGroup) { - throw new ApiException(500, '组不存在'); + return $this->fail([400202,'组不存在']); } } $servers = ServerVmess::all(); foreach ($servers as $server) { if (in_array($request->input('id'), $server->group_id)) { - throw new ApiException(500, '该组已被节点所使用,无法删除'); + return $this->fail([400,'该组已被节点所使用,无法删除']); } } if (Plan::where('group_id', $request->input('id'))->first()) { - throw new ApiException(500, '该组已被订阅所使用,无法删除'); + return $this->fail([400, '该组已被订阅所使用,无法删除']); } if (User::where('group_id', $request->input('id'))->first()) { - throw new ApiException(500, '该组已被用户所使用,无法删除'); + return $this->fail([400, '该组已被用户所使用,无法删除']); } - return response([ - 'data' => $serverGroup->delete() - ]); + return $this->success($serverGroup->delete()); } } diff --git a/app/Http/Controllers/V1/Admin/Server/HysteriaController.php b/app/Http/Controllers/V1/Admin/Server/HysteriaController.php index 1a6e83d..c75e484 100644 --- a/app/Http/Controllers/V1/Admin/Server/HysteriaController.php +++ b/app/Http/Controllers/V1/Admin/Server/HysteriaController.php @@ -45,25 +45,22 @@ class HysteriaController extends Controller if ($request->input('id')) { $server = ServerHysteria::find($request->input('id')); if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202, '服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } if (!ServerHysteria::create($params)) { - throw new ApiException(500, '创建失败'); + return $this->fail([500,'创建失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) @@ -71,12 +68,10 @@ class HysteriaController extends Controller if ($request->input('id')) { $server = ServerHysteria::find($request->input('id')); if (!$server) { - throw new ApiException(500, '节点ID不存在'); + return $this->fail([400202,'节点ID不存在']); } } - return response([ - 'data' => $server->delete() - ]); + return $this->success($server->delete()); } public function update(Request $request) @@ -93,17 +88,16 @@ class HysteriaController extends Controller $server = ServerHysteria::find($request->input('id')); if (!$server) { - throw new ApiException(500, '该服务器不存在'); + return $this->fail([400202,'该服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function copy(Request $request) @@ -111,14 +105,9 @@ class HysteriaController extends Controller $server = ServerHysteria::find($request->input('id')); $server->show = 0; if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202,'服务器不存在']); } - if (!ServerHysteria::create($server->toArray())) { - throw new ApiException(500, '复制失败'); - } - - return response([ - 'data' => true - ]); + ServerHysteria::create($server->toArray()); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/Server/ManageController.php b/app/Http/Controllers/V1/Admin/Server/ManageController.php index 0bfa05e..c34d6f2 100644 --- a/app/Http/Controllers/V1/Admin/Server/ManageController.php +++ b/app/Http/Controllers/V1/Admin/Server/ManageController.php @@ -13,9 +13,7 @@ class ManageController extends Controller public function getNodes(Request $request) { $serverService = new ServerService(); - return response([ - 'data' => $serverService->getAllServers() - ]); + return $this->success($serverService->getAllServers()); } public function sort(Request $request) @@ -33,15 +31,15 @@ class ManageController extends Controller foreach ($params as $k => $v) { $model = 'App\\Models\\Server' . ucfirst($k); foreach($v as $id => $sort) { - if (!$model::find($id)->update(['sort' => $sort])) { - throw new ApiException(500, '保存失败'); - } + $model::where('id', $id)->update(['sort' => $sort]); } } DB::commit(); }catch (\Exception $e){ DB::rollBack(); - throw $e; + \Log::error($e); + return $this->fail([500,'保存失败']); + } return $this->success(true); } diff --git a/app/Http/Controllers/V1/Admin/Server/RouteController.php b/app/Http/Controllers/V1/Admin/Server/RouteController.php index 1559ec9..3cea539 100644 --- a/app/Http/Controllers/V1/Admin/Server/RouteController.php +++ b/app/Http/Controllers/V1/Admin/Server/RouteController.php @@ -44,24 +44,26 @@ class RouteController extends Controller try { $route = ServerRoute::find($request->input('id')); $route->update($params); - return [ - 'data' => true - ]; + return $this->success(true); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } } - if (!ServerRoute::create($params)) throw new ApiException(500, '创建失败'); - return [ - 'data' => true - ]; + try{ + ServerRoute::create($params); + return $this->success(true); + }catch(\Exception $e){ + \Log::error($e); + return $this->fail([500,'创建失败']); + } } public function drop(Request $request) { $route = ServerRoute::find($request->input('id')); - if (!$route) throw new ApiException(500, '路由不存在'); - if (!$route->delete()) throw new ApiException(500, '删除失败'); + if (!$route) throw new ApiException('路由不存在'); + if (!$route->delete()) throw new ApiException('删除失败'); return [ 'data' => true ]; diff --git a/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php b/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php index 25999ce..3748030 100644 --- a/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php +++ b/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php @@ -17,25 +17,26 @@ class ShadowsocksController extends Controller if ($request->input('id')) { $server = ServerShadowsocks::find($request->input('id')); if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202, '服务器不存在']); } try { $server->update($params); + return $this->success(true); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } - return response([ - 'data' => true - ]); } - if (!ServerShadowsocks::create($params)) { - throw new ApiException(500, '创建失败'); + try{ + ServerShadowsocks::create($params); + return $this->success(true); + }catch(\Exception $e){ + \Log::error($e); + return $this->fail([500,'创建失败']); } - return response([ - 'data' => true - ]); + } public function drop(Request $request) @@ -43,12 +44,10 @@ class ShadowsocksController extends Controller if ($request->input('id')) { $server = ServerShadowsocks::find($request->input('id')); if (!$server) { - throw new ApiException(500, '节点ID不存在'); + return $this->fail([400202, '节点不存在']); } } - return response([ - 'data' => $server->delete() - ]); + return $this->success($server->delete()); } public function update(ServerShadowsocksUpdate $request) @@ -60,17 +59,16 @@ class ShadowsocksController extends Controller $server = ServerShadowsocks::find($request->input('id')); if (!$server) { - throw new ApiException(500, '该服务器不存在'); + return $this->fail([400202, '该服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function copy(Request $request) @@ -78,14 +76,9 @@ class ShadowsocksController extends Controller $server = ServerShadowsocks::find($request->input('id')); $server->show = 0; if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202,'服务器不存在']); } - if (!ServerShadowsocks::create($server->toArray())) { - throw new ApiException(500, '复制失败'); - } - - return response([ - 'data' => true - ]); + ServerShadowsocks::create($server->toArray()); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/Server/TrojanController.php b/app/Http/Controllers/V1/Admin/Server/TrojanController.php index 71e7bb3..a8797ec 100644 --- a/app/Http/Controllers/V1/Admin/Server/TrojanController.php +++ b/app/Http/Controllers/V1/Admin/Server/TrojanController.php @@ -18,25 +18,19 @@ class TrojanController extends Controller if ($request->input('id')) { $server = ServerTrojan::find($request->input('id')); if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202,'服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500, '保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } - if (!ServerTrojan::create($params)) { - throw new ApiException(500, '创建失败'); - } - - return response([ - 'data' => true - ]); + ServerTrojan::create($params); + return $this->success(true); } public function drop(Request $request) @@ -44,12 +38,10 @@ class TrojanController extends Controller if ($request->input('id')) { $server = ServerTrojan::find($request->input('id')); if (!$server) { - throw new ApiException(500, '节点ID不存在'); + return $this->fail([400202,'节点ID不存在']); } } - return response([ - 'data' => $server->delete() - ]); + return $this->success($server->delete()); } public function update(ServerTrojanUpdate $request) @@ -61,17 +53,16 @@ class TrojanController extends Controller $server = ServerTrojan::find($request->input('id')); if (!$server) { - throw new ApiException(500, '该服务器不存在'); + return $this->fail([400202,'该服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function copy(Request $request) @@ -79,22 +70,15 @@ class TrojanController extends Controller $server = ServerTrojan::find($request->input('id')); $server->show = 0; if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202,'服务器不存在']); } - if (!ServerTrojan::create($server->toArray())) { - throw new ApiException(500, '复制失败'); - } - - return response([ - 'data' => true - ]); + ServerTrojan::create($server->toArray()); + return $this->success(true); } public function viewConfig(Request $request) { $serverService = new ServerService(); $config = $serverService->getTrojanConfig($request->input('node_id'), 23333); - return response([ - 'data' => $config - ]); + return $this->success($config); } } diff --git a/app/Http/Controllers/V1/Admin/Server/VlessController.php b/app/Http/Controllers/V1/Admin/Server/VlessController.php index c2eebfc..7b7b973 100644 --- a/app/Http/Controllers/V1/Admin/Server/VlessController.php +++ b/app/Http/Controllers/V1/Admin/Server/VlessController.php @@ -62,25 +62,19 @@ class VlessController extends Controller if ($request->input('id')) { $server = ServerVless::find($request->input('id')); if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202, '服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500, '保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } + ServerVless::create($params); - if (!ServerVless::create($params)) { - throw new ApiException(500, '创建失败'); - } - - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) @@ -88,12 +82,10 @@ class VlessController extends Controller if ($request->input('id')) { $server = ServerVless::find($request->input('id')); if (!$server) { - throw new ApiException(500, '节点ID不存在'); + return $this->fail([400202,'节点不存在']); } } - return response([ - 'data' => $server->delete() - ]); + return $this->success($server->delete()); } public function update(Request $request) @@ -105,17 +97,16 @@ class VlessController extends Controller $server = ServerVless::find($request->input('id')); if (!$server) { - throw new ApiException(500, '该服务器不存在'); + return $this->fail([400202, '该服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500, '保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function copy(Request $request) @@ -123,14 +114,9 @@ class VlessController extends Controller $server = ServerVless::find($request->input('id')); $server->show = 0; if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202, '该服务器不存在']); } - if (!ServerVless::create($server->toArray())) { - throw new ApiException(500, '复制失败'); - } - - return response([ - 'data' => true - ]); + ServerVless::create($server->toArray()); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/Server/VmessController.php b/app/Http/Controllers/V1/Admin/Server/VmessController.php index b827aac..ecd8446 100644 --- a/app/Http/Controllers/V1/Admin/Server/VmessController.php +++ b/app/Http/Controllers/V1/Admin/Server/VmessController.php @@ -18,25 +18,20 @@ class VmessController extends Controller if ($request->input('id')) { $server = ServerVmess::find($request->input('id')); if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202, '服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500, '保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } - if (!ServerVmess::create($params)) { - throw new ApiException(500, '创建失败'); - } + ServerVmess::create($params); - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) @@ -44,12 +39,10 @@ class VmessController extends Controller if ($request->input('id')) { $server = ServerVmess::find($request->input('id')); if (!$server) { - throw new ApiException(500, '节点ID不存在'); + return $this->fail([400202, '节点不存在']); } } - return response([ - 'data' => $server->delete() - ]); + return $this->success($server->delete()); } public function update(ServerVmessUpdate $request) @@ -61,17 +54,16 @@ class VmessController extends Controller $server = ServerVmess::find($request->input('id')); if (!$server) { - throw new ApiException(500, '该服务器不存在'); + return $this->fail([400202, '该服务器不存在']); } try { $server->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500, '保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function copy(Request $request) @@ -79,14 +71,9 @@ class VmessController extends Controller $server = ServerVmess::find($request->input('id')); $server->show = 0; if (!$server) { - throw new ApiException(500, '服务器不存在'); + return $this->fail([400202, '该服务器不存在']); } - if (!ServerVmess::create($server->toArray())) { - throw new ApiException(500, '复制失败'); - } - - return response([ - 'data' => true - ]); + ServerVmess::create($server->toArray()); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Admin/SystemController.php b/app/Http/Controllers/V1/Admin/SystemController.php index 228335a..8c2f8f1 100644 --- a/app/Http/Controllers/V1/Admin/SystemController.php +++ b/app/Http/Controllers/V1/Admin/SystemController.php @@ -20,20 +20,17 @@ class SystemController extends Controller { public function getSystemStatus() { - return response([ - 'data' => [ - 'schedule' => $this->getScheduleStatus(), - 'horizon' => $this->getHorizonStatus(), - 'schedule_last_runtime' => Cache::get(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null)) - ] - ]); + $data = [ + 'schedule' => $this->getScheduleStatus(), + 'horizon' => $this->getHorizonStatus(), + 'schedule_last_runtime' => Cache::get(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null)) + ]; + return $this->success($data); } public function getQueueWorkload(WorkloadRepository $workload) { - return response([ - 'data' => collect($workload->get())->sortBy('name')->values()->toArray() - ]); + return $this->success(collect($workload->get())->sortBy('name')->values()->toArray()); } protected function getScheduleStatus():bool @@ -54,23 +51,22 @@ class SystemController extends Controller public function getQueueStats() { - return response([ - 'data' => [ - 'failedJobs' => app(JobRepository::class)->countRecentlyFailed(), - 'jobsPerMinute' => app(MetricsRepository::class)->jobsProcessedPerMinute(), - 'pausedMasters' => $this->totalPausedMasters(), - 'periods' => [ - 'failedJobs' => config('horizon.trim.recent_failed', config('horizon.trim.failed')), - 'recentJobs' => config('horizon.trim.recent'), - ], - 'processes' => $this->totalProcessCount(), - 'queueWithMaxRuntime' => app(MetricsRepository::class)->queueWithMaximumRuntime(), - 'queueWithMaxThroughput' => app(MetricsRepository::class)->queueWithMaximumThroughput(), - 'recentJobs' => app(JobRepository::class)->countRecent(), - 'status' => $this->getHorizonStatus(), - 'wait' => collect(app(WaitTimeCalculator::class)->calculate())->take(1), - ] - ]); + $data = [ + 'failedJobs' => app(JobRepository::class)->countRecentlyFailed(), + 'jobsPerMinute' => app(MetricsRepository::class)->jobsProcessedPerMinute(), + 'pausedMasters' => $this->totalPausedMasters(), + 'periods' => [ + 'failedJobs' => config('horizon.trim.recent_failed', config('horizon.trim.failed')), + 'recentJobs' => config('horizon.trim.recent'), + ], + 'processes' => $this->totalProcessCount(), + 'queueWithMaxRuntime' => app(MetricsRepository::class)->queueWithMaximumRuntime(), + 'queueWithMaxThroughput' => app(MetricsRepository::class)->queueWithMaximumThroughput(), + 'recentJobs' => app(JobRepository::class)->countRecent(), + 'status' => $this->getHorizonStatus(), + 'wait' => collect(app(WaitTimeCalculator::class)->calculate())->take(1), + ]; + return $this->success($data); } /** diff --git a/app/Http/Controllers/V1/Admin/ThemeController.php b/app/Http/Controllers/V1/Admin/ThemeController.php index c6db848..8db527d 100644 --- a/app/Http/Controllers/V1/Admin/ThemeController.php +++ b/app/Http/Controllers/V1/Admin/ThemeController.php @@ -34,12 +34,11 @@ class ThemeController extends Controller $themeService = new ThemeService($theme); $themeService->init(); } - return response([ - 'data' => [ - 'themes' => $themeConfigs, - 'active' => admin_setting('frontend_theme', 'Xboard') - ] - ]); + $data = [ + 'themes' => $themeConfigs, + 'active' => admin_setting('frontend_theme', 'Xboard') + ]; + return $this->success($data); } public function getThemeConfig(Request $request) @@ -47,9 +46,7 @@ class ThemeController extends Controller $payload = $request->validate([ 'name' => 'required|in:' . join(',', $this->themes) ]); - return response([ - 'data' => admin_setting("theme_{$payload['name']}") ?? config("theme.{$payload['name']}") - ]); + return $this->success(admin_setting("theme_{$payload['name']}") ?? config("theme.{$payload['name']}")); } public function saveThemeConfig(Request $request) @@ -59,11 +56,11 @@ class ThemeController extends Controller 'config' => 'required' ]); $payload['config'] = json_decode(base64_decode($payload['config']), true); - if (!$payload['config'] || !is_array($payload['config'])) throw new ApiException(422, '参数有误'); + if (!$payload['config'] || !is_array($payload['config'])) return $this->fail([422,'参数不正确']); $themeConfigFile = public_path("theme/{$payload['name']}/config.json"); - if (!File::exists($themeConfigFile)) throw new ApiException(500, '主题不存在'); + if (!File::exists($themeConfigFile)) return $this->fail([400202,'主题不存在']); $themeConfig = json_decode(File::get($themeConfigFile), true); - if (!isset($themeConfig['configs']) || !is_array($themeConfig)) throw new ApiException(500, '主题配置文件有误'); + if (!isset($themeConfig['configs']) || !is_array($themeConfig)) return $this->fail([422,'主题配置文件有误']); $validateFields = array_column($themeConfig['configs'], 'field_name'); $config = []; foreach ($validateFields as $validateField) { @@ -77,11 +74,8 @@ class ThemeController extends Controller admin_setting(["theme_{$payload['name']}" => $config]); // sleep(2); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + return $this->fail([200002, '保存失败']); } - - return response([ - 'data' => $config - ]); + return $this->success($config); } } diff --git a/app/Http/Controllers/V1/Admin/TicketController.php b/app/Http/Controllers/V1/Admin/TicketController.php index 233f20a..8dd7da9 100644 --- a/app/Http/Controllers/V1/Admin/TicketController.php +++ b/app/Http/Controllers/V1/Admin/TicketController.php @@ -8,6 +8,7 @@ use App\Models\Ticket; use App\Models\TicketMessage; use App\Models\User; use App\Services\TicketService; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\Request; class TicketController extends Controller @@ -18,7 +19,7 @@ class TicketController extends Controller $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - throw new ApiException(500, '工单不存在'); + return $this->fail([400202,'工单不存在']); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); for ($i = 0; $i < count($ticket['message']); $i++) { @@ -28,9 +29,7 @@ class TicketController extends Controller $ticket['message'][$i]['is_me'] = false; } } - return response([ - 'data' => $ticket - ]); + return $this->success($ticket); } $current = $request->input('current') ? $request->input('current') : 1; $pageSize = $request->input('pageSize') >= 10 ? $request->input('pageSize') : 10; @@ -56,39 +55,38 @@ class TicketController extends Controller public function reply(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); - } - if (empty($request->input('message'))) { - throw new ApiException(500, '消息不能为空'); - } + $request->validate([ + 'id' => 'required|numeric', + 'message' => 'required|string' + ],[ + 'id.required' => '工单ID不能为空', + 'message.required' => '消息不能为空' + ]); $ticketService = new TicketService(); $ticketService->replyByAdmin( $request->input('id'), $request->input('message'), $request->user['id'] ); - return response([ - 'data' => true - ]); + return $this->success(true); } public function close(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); - } - $ticket = Ticket::where('id', $request->input('id')) - ->first(); - if (!$ticket) { - throw new ApiException(500, '工单不存在'); - } - $ticket->status = 1; - if (!$ticket->save()) { - throw new ApiException(500, '关闭失败'); - } - return response([ - 'data' => true + $request->validate([ + 'id' => 'required|numeric' + ],[ + 'id.required' => '工单ID不能为空' ]); + try { + $ticket = Ticket::findOrFail($request->input('id')); + $ticket->status = 1; + $ticket->save(); + return $this->success(true); + } catch (ModelNotFoundException $e) { + return $this->fail([400202, '工单不存在']); + } catch (\Exception $e) { + return $this->fail([500101, '关闭失败']); + } } } diff --git a/app/Http/Controllers/V1/Admin/UserController.php b/app/Http/Controllers/V1/Admin/UserController.php index 90d492a..c3ed2bc 100644 --- a/app/Http/Controllers/V1/Admin/UserController.php +++ b/app/Http/Controllers/V1/Admin/UserController.php @@ -21,12 +21,10 @@ class UserController extends Controller public function resetSecret(Request $request) { $user = User::find($request->input('id')); - if (!$user) throw new ApiException(500, '用户不存在'); + if (!$user) return $this->fail([400202,'用户不存在']); $user->token = Helper::guid(); $user->uuid = Helper::guid(true); - return response([ - 'data' => $user->save() - ]); + return $this->success($user->save()); } private function filter(Request $request, $builder) @@ -85,46 +83,45 @@ class UserController extends Controller public function getUserInfoById(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); - } - $user = User::find($request->input('id')); - if ($user->invite_user_id) { - $user['invite_user'] = User::find($user->invite_user_id); - } - return response([ - 'data' => $user + $request->validate([ + 'id'=> 'required|numeric' + ],[ + 'id.required' => '用户ID不能为空' ]); + $user = User::find($request->input('id'))->load('invite_user'); + return $this->success($user); } public function update(UserUpdate $request) { $params = $request->validated(); + $user = User::find($request->input('id')); if (!$user) { - throw new ApiException(500, '用户不存在'); + return $this->fail([400202, '用户不存在']); } + // 检查邮箱是否被使用 if (User::where('email', $params['email'])->first() && $user->email !== $params['email']) { - throw new ApiException(500, '邮箱已被使用'); + return $this->fail([400201, '邮箱已被使用']); } + // 处理密码 if (isset($params['password'])) { $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT); $params['password_algo'] = NULL; } else { unset($params['password']); } + // 处理订阅计划 if (isset($params['plan_id'])) { $plan = Plan::find($params['plan_id']); if (!$plan) { - throw new ApiException(500, '订阅计划不存在'); + return $this->fail([400202, '订阅计划不存在']); } $params['group_id'] = $plan->group_id; } - if ($request->input('invite_user_email')) { - $inviteUser = User::where('email', $request->input('invite_user_email'))->first(); - if ($inviteUser) { - $params['invite_user_id'] = $inviteUser->id; - } + // 处理邀请用户 + if ($request->input('invite_user_email') && $inviteUser = User::where('email', $request->input('invite_user_email'))->first()) { + $params['invite_user_id'] = $inviteUser->id; } else { $params['invite_user_id'] = null; } @@ -137,11 +134,10 @@ class UserController extends Controller try { $user->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'保存失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function dumpCSV(Request $request) @@ -178,7 +174,7 @@ class UserController extends Controller if ($request->input('plan_id')) { $plan = Plan::find($request->input('plan_id')); if (!$plan) { - throw new ApiException(500, '订阅计划不存在'); + return $this->fail([400202,'订阅计划不存在']); } } $user = [ @@ -191,15 +187,13 @@ class UserController extends Controller 'token' => Helper::guid() ]; if (User::where('email', $user['email'])->first()) { - throw new ApiException(500, '邮箱已存在于系统中'); + return $this->fail([400201,'邮箱已存在于系统中']); } $user['password'] = password_hash($request->input('password') ?? $user['email'], PASSWORD_DEFAULT); if (!User::create($user)) { - throw new ApiException(500, '生成失败'); + return $this->fail([500,'生成失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } if ($request->input('generate_count')) { $this->multiGenerate($request); @@ -211,7 +205,7 @@ class UserController extends Controller if ($request->input('plan_id')) { $plan = Plan::find($request->input('plan_id')); if (!$plan) { - throw new ApiException(500, '订阅计划不存在'); + return $this->fail([400202,'订阅计划不存在']); } } $users = []; @@ -233,12 +227,13 @@ class UserController extends Controller try{ DB::beginTransaction(); if (!User::insert($users)) { - throw new ApiException(500, '生成失败'); + throw new \Exception(); } DB::commit(); }catch(\Exception $e){ DB::rollBack(); - throw $e; + \Log::error($e); + return $this->fail([500,'生成失败']); } $data = "账号,密码,过期时间,UUID,创建时间,订阅地址\r\n"; foreach($users as $user) { @@ -272,9 +267,7 @@ class UserController extends Controller 'send_email_mass'); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function ban(Request $request) @@ -288,11 +281,10 @@ class UserController extends Controller 'banned' => 1 ]); } catch (\Exception $e) { - throw new ApiException(500, '处理失败'); + \Log::error($e); + return $this->fail([500,'处理失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Client/AppController.php b/app/Http/Controllers/V1/Client/AppController.php index ca86433..72ae9c9 100644 --- a/app/Http/Controllers/V1/Client/AppController.php +++ b/app/Http/Controllers/V1/Client/AppController.php @@ -65,31 +65,26 @@ class AppController extends Controller || strpos($request->header('user-agent'), 'tunnelab/4.0.0') !== false ) { if (strpos($request->header('user-agent'), 'Win64') !== false) { - return response([ - 'data' => [ + $data = [ 'version' => admin_setting('windows_version'), 'download_url' => admin_setting('windows_download_url') - ] - ]); + ]; } else { - return response([ - 'data' => [ + $data = [ 'version' => admin_setting('macos_version'), 'download_url' => admin_setting('macos_download_url') - ] - ]); + ]; } - return; - } - return response([ - 'data' => [ + }else{ + $data = [ 'windows_version' => admin_setting('windows_version'), 'windows_download_url' => admin_setting('windows_download_url'), 'macos_version' => admin_setting('macos_version'), 'macos_download_url' => admin_setting('macos_download_url'), 'android_version' => admin_setting('android_version'), 'android_download_url' => admin_setting('android_download_url') - ] - ]); + ]; + } + return $this->success($data); } } diff --git a/app/Http/Controllers/V1/Guest/CommController.php b/app/Http/Controllers/V1/Guest/CommController.php index 9477612..8698d57 100644 --- a/app/Http/Controllers/V1/Guest/CommController.php +++ b/app/Http/Controllers/V1/Guest/CommController.php @@ -10,21 +10,20 @@ class CommController extends Controller { public function config() { - return response([ - 'data' => [ - 'tos_url' => admin_setting('tos_url'), - 'is_email_verify' => (int)admin_setting('email_verify', 0) ? 1 : 0, - 'is_invite_force' => (int)admin_setting('invite_force', 0) ? 1 : 0, - 'email_whitelist_suffix' => (int)admin_setting('email_whitelist_enable', 0) - ? $this->getEmailSuffix() - : 0, - 'is_recaptcha' => (int)admin_setting('recaptcha_enable', 0) ? 1 : 0, - 'recaptcha_site_key' => admin_setting('recaptcha_site_key'), - 'app_description' => admin_setting('app_description'), - 'app_url' => admin_setting('app_url'), - 'logo' => admin_setting('logo'), - ] - ]); + $data = [ + 'tos_url' => admin_setting('tos_url'), + 'is_email_verify' => (int)admin_setting('email_verify', 0) ? 1 : 0, + 'is_invite_force' => (int)admin_setting('invite_force', 0) ? 1 : 0, + 'email_whitelist_suffix' => (int)admin_setting('email_whitelist_enable', 0) + ? $this->getEmailSuffix() + : 0, + 'is_recaptcha' => (int)admin_setting('recaptcha_enable', 0) ? 1 : 0, + 'recaptcha_site_key' => admin_setting('recaptcha_site_key'), + 'app_description' => admin_setting('app_description'), + 'app_url' => admin_setting('app_url'), + 'logo' => admin_setting('logo'), + ]; + return $this->success($data); } private function getEmailSuffix() diff --git a/app/Http/Controllers/V1/Guest/PaymentController.php b/app/Http/Controllers/V1/Guest/PaymentController.php index a04ccea..4f084d6 100644 --- a/app/Http/Controllers/V1/Guest/PaymentController.php +++ b/app/Http/Controllers/V1/Guest/PaymentController.php @@ -17,13 +17,13 @@ class PaymentController extends Controller try { $paymentService = new PaymentService($method, null, $uuid); $verify = $paymentService->notify($request->input()); - if (!$verify) throw new ApiException(500, 'verify error'); + if (!$verify) return $this->fail([422,'verify error']); if (!$this->handle($verify['trade_no'], $verify['callback_no'])) { - throw new ApiException(500, 'handle error'); + return $this->fail([400,'handle error']); } return(isset($verify['custom_result']) ? $verify['custom_result'] : 'success'); } catch (\Exception $e) { - throw new ApiException(500, 'fail'); + return $this->fail([500,'fail']); } } @@ -31,7 +31,7 @@ class PaymentController extends Controller { $order = Order::where('trade_no', $tradeNo)->first(); if (!$order) { - throw new ApiException(500, 'order is not found'); + return $this->fail([400202,'order is not found']); } if ($order->status !== 0) return true; $orderService = new OrderService($order); diff --git a/app/Http/Controllers/V1/Guest/PlanController.php b/app/Http/Controllers/V1/Guest/PlanController.php index 647e98a..ae2e782 100755 --- a/app/Http/Controllers/V1/Guest/PlanController.php +++ b/app/Http/Controllers/V1/Guest/PlanController.php @@ -11,8 +11,6 @@ class PlanController extends Controller public function fetch(Request $request) { $plan = Plan::where('show', 1)->get(); - return response([ - 'data' => $plan - ]); + return $this->success($plan); } } diff --git a/app/Http/Controllers/V1/Guest/TelegramController.php b/app/Http/Controllers/V1/Guest/TelegramController.php index 63be33a..0bd8017 100644 --- a/app/Http/Controllers/V1/Guest/TelegramController.php +++ b/app/Http/Controllers/V1/Guest/TelegramController.php @@ -16,7 +16,7 @@ class TelegramController extends Controller public function __construct(Request $request) { if ($request->input('access_token') !== md5(admin_setting('telegram_bot_token'))) { - throw new ApiException(401); + throw new ApiException('access_token is error', 401); } $this->telegramService = new TelegramService(); diff --git a/app/Http/Controllers/V1/Passport/AuthController.php b/app/Http/Controllers/V1/Passport/AuthController.php index 7434fe1..b8eb7dd 100644 --- a/app/Http/Controllers/V1/Passport/AuthController.php +++ b/app/Http/Controllers/V1/Passport/AuthController.php @@ -3,6 +3,7 @@ namespace App\Http\Controllers\V1\Passport; use App\Exceptions\ApiException; +use App\Helpers\ResponseEnum; use App\Http\Controllers\Controller; use App\Http\Requests\Passport\AuthForget; use App\Http\Requests\Passport\AuthLogin; @@ -24,7 +25,7 @@ class AuthController extends Controller public function loginWithMailLink(Request $request) { if (!(int)admin_setting('login_with_mail_link_enable')) { - throw new ApiException(404); + return $this->fail([404,null]); } $params = $request->validate([ 'email' => 'required|email:strict', @@ -32,14 +33,12 @@ class AuthController extends Controller ]); if (Cache::get(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $params['email']))) { - throw new ApiException(500, __('Sending frequently, please try again later')); + return $this->fail([429 ,__('Sending frequently, please try again later')]); } $user = User::where('email', $params['email'])->first(); if (!$user) { - return response([ - 'data' => true - ]); + return $this->success(true); } $code = Helper::guid(); @@ -68,9 +67,7 @@ class AuthController extends Controller ] ]); - return response([ - 'data' => $link - ]); + return $this->success($link); } @@ -79,16 +76,16 @@ class AuthController extends Controller if ((int)admin_setting('register_limit_by_ip_enable', 0)) { $registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0; if ((int)$registerCountByIP >= (int)admin_setting('register_limit_count', 3)) { - throw new ApiException(500, __('Register frequently, please try again after :minute minute', [ + return $this->fail([429,__('Register frequently, please try again after :minute minute', [ 'minute' => admin_setting('register_limit_expire', 60) - ])); + ])]); } } if ((int)admin_setting('recaptcha_enable', 0)) { $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); if (!$recaptchaResp->isSuccess()) { - throw new ApiException(500, __('Invalid code is incorrect')); + return $this->fail([400,__('Invalid code is incorrect')]); } } if ((int)admin_setting('email_whitelist_enable', 0)) { @@ -96,36 +93,36 @@ class AuthController extends Controller $request->input('email'), admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT)) ) { - throw new ApiException(500, __('Email suffix is not in the Whitelist')); + return $this->fail([400,__('Email suffix is not in the Whitelist')]); } } if ((int)admin_setting('email_gmail_limit_enable', 0)) { $prefix = explode('@', $request->input('email'))[0]; if (strpos($prefix, '.') !== false || strpos($prefix, '+') !== false) { - throw new ApiException(500, __('Gmail alias is not supported')); + return $this->fail([400,__('Gmail alias is not supported')]); } } if ((int)admin_setting('stop_register', 0)) { - throw new ApiException(500, __('Registration has closed')); + return $this->fail([400,__('Registration has closed')]); } if ((int)admin_setting('invite_force', 0)) { if (empty($request->input('invite_code'))) { - throw new ApiException(500, __('You must use the invitation code to register')); + return $this->fail([422,__('You must use the invitation code to register')]); } } if ((int)admin_setting('email_verify', 0)) { if (empty($request->input('email_code'))) { - throw new ApiException(500, __('Email verification code cannot be empty')); + return $this->fail([422,__('Email verification code cannot be empty')]); } if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { - throw new ApiException(500, __('Incorrect email verification code')); + return $this->fail([400,__('Incorrect email verification code')]); } } $email = $request->input('email'); $password = $request->input('password'); $exist = User::where('email', $email)->first(); if ($exist) { - throw new ApiException(500, __('Email already exists')); + return $this->fail([400201,__('Email already exists')]); } $user = new User(); $user->email = $email; @@ -141,7 +138,7 @@ class AuthController extends Controller ->first(); if (!$inviteCode) { if ((int)admin_setting('invite_force', 0)) { - throw new ApiException(500, __('Invalid invitation code')); + return $this->fail([400,__('Invalid invitation code')]); } } else { $user->invite_user_id = $inviteCode->user_id ? $inviteCode->user_id : null; @@ -165,7 +162,7 @@ class AuthController extends Controller } if (!$user->save()) { - throw new ApiException(500, __('Register failed')); + return $this->fail([500,__('Register failed')]); } if ((int)admin_setting('email_verify', 0)) { Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))); @@ -184,9 +181,8 @@ class AuthController extends Controller $authService = new AuthService($user); - return response()->json([ - 'data' => $authService->generateAuthData($request) - ]); + $data = $authService->generateAuthData($request); + return $this->success($data); } public function login(AuthLogin $request) @@ -197,15 +193,15 @@ class AuthController extends Controller if ((int)admin_setting('password_limit_enable', 1)) { $passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0); if ($passwordErrorCount >= (int)admin_setting('password_limit_count', 5)) { - throw new ApiException(500, __('There are too many password errors, please try again after :minute minutes.', [ + return $this->fail([429,__('There are too many password errors, please try again after :minute minutes.', [ 'minute' => admin_setting('password_limit_expire', 60) - ])); + ])]); } } $user = User::where('email', $email)->first(); if (!$user) { - throw new ApiException(500, __('Incorrect email or password')); + return $this->fail([400, __('Incorrect email or password')]); } if (!Helper::multiPasswordVerify( $user->password_algo, @@ -220,17 +216,15 @@ class AuthController extends Controller 60 * (int)admin_setting('password_limit_expire', 60) ); } - throw new ApiException(500, __('Incorrect email or password')); + return $this->fail([400, __('Incorrect email or password')]); } if ($user->banned) { - throw new ApiException(500, __('Your account has been suspended')); + return $this->fail([400, __('Your account has been suspended')]); } $authService = new AuthService($user); - return response([ - 'data' => $authService->generateAuthData($request) - ]); + return $this->success($authService->generateAuthData($request)); } public function token2Login(Request $request) @@ -249,30 +243,28 @@ class AuthController extends Controller $key = CacheKey::get('TEMP_TOKEN', $request->input('verify')); $userId = Cache::get($key); if (!$userId) { - throw new ApiException(500, __('Token error')); + return $this->fail([400,__('Token error')]); } $user = User::find($userId); if (!$user) { - throw new ApiException(500, __('The user does not ')); + return $this->fail([400,__('The user does not ')]); } if ($user->banned) { - throw new ApiException(500, __('Your account has been suspended')); + return $this->fail([400,__('Your account has been suspended')]); } Cache::forget($key); $authService = new AuthService($user); - return response([ - 'data' => $authService->generateAuthData($request) - ]); + return $this->success($authService->generateAuthData($request)); } } public function getQuickLoginUrl(Request $request) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); + if (!$authorization) return $this->fail(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED); $user = AuthService::decryptAuthData($authorization); - if (!$user) throw new ApiException(403, '未登录或登陆已过期'); + if (!$user) return $this->fail(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED_EXPIRED); $code = Helper::guid(); $key = CacheKey::get('TEMP_TOKEN', $code); @@ -283,33 +275,29 @@ class AuthController extends Controller } else { $url = url($redirect); } - return response([ - 'data' => $url - ]); + return $this->success($url); } public function forget(AuthForget $request) { $forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $request->input('email')); $forgetRequestLimit = (int)Cache::get($forgetRequestLimitKey); - if ($forgetRequestLimit >= 3) throw new ApiException(500, __('Reset failed, Please try again later')); + if ($forgetRequestLimit >= 3) return $this->fail([429, __('Reset failed, Please try again later')]); if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { Cache::put($forgetRequestLimitKey, $forgetRequestLimit ? $forgetRequestLimit + 1 : 1, 300); - throw new ApiException(500, __('Incorrect email verification code')); + return $this->fail([400,__('Incorrect email verification code')]); } $user = User::where('email', $request->input('email'))->first(); if (!$user) { - throw new ApiException(500, __('This email is not registered in the system')); + return $this->fail([400,__('This email is not registered in the system')]); } $user->password = password_hash($request->input('password'), PASSWORD_DEFAULT); $user->password_algo = NULL; $user->password_salt = NULL; if (!$user->save()) { - throw new ApiException(500, __('Reset failed')); + return $this->fail([500,__('Reset failed')]); } Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))); - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Passport/CommController.php b/app/Http/Controllers/V1/Passport/CommController.php index 60f941a..ce135fa 100644 --- a/app/Http/Controllers/V1/Passport/CommController.php +++ b/app/Http/Controllers/V1/Passport/CommController.php @@ -17,9 +17,7 @@ class CommController extends Controller { private function isEmailVerify() { - return response([ - 'data' => (int)admin_setting('email_verify', 0) ? 1 : 0 - ]); + return $this->success((int)admin_setting('email_verify', 0) ? 1 : 0); } public function sendEmailVerify(CommSendEmailVerify $request) @@ -28,12 +26,12 @@ class CommController extends Controller $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); if (!$recaptchaResp->isSuccess()) { - throw new ApiException(500, __('Invalid code is incorrect')); + return $this->fail([400, __('Invalid code is incorrect')]); } } $email = $request->input('email'); if (Cache::get(CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP', $email))) { - throw new ApiException(500, __('Email verification code has been sent, please request again later')); + return $this->fail([400, __('Email verification code has been sent, please request again later')]); } $code = rand(100000, 999999); $subject = admin_setting('app_name', 'XBoard') . __('Email verification code'); @@ -51,9 +49,7 @@ class CommController extends Controller Cache::put(CacheKey::get('EMAIL_VERIFY_CODE', $email), $code, 300); Cache::put(CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP', $email), time(), 60); - return response([ - 'data' => true - ]); + return $this->success(true); } public function pv(Request $request) @@ -64,9 +60,7 @@ class CommController extends Controller $inviteCode->save(); } - return response([ - 'data' => true - ]); + return $this->success(true); } private function getEmailSuffix() diff --git a/app/Http/Controllers/V1/Server/DeepbworkController.php b/app/Http/Controllers/V1/Server/DeepbworkController.php index 65105f7..b0b92b9 100644 --- a/app/Http/Controllers/V1/Server/DeepbworkController.php +++ b/app/Http/Controllers/V1/Server/DeepbworkController.php @@ -22,10 +22,10 @@ class DeepbworkController extends Controller { $token = $request->input('token'); if (empty($token)) { - throw new ApiException(500, 'token is null'); + throw new ApiException('token is null'); } if ($token !== admin_setting('server_token')) { - throw new ApiException(500, 'token is error'); + throw new ApiException('token is error'); } } @@ -36,7 +36,7 @@ class DeepbworkController extends Controller $nodeId = $request->input('node_id'); $server = ServerVmess::find($nodeId); if (!$server) { - throw new ApiException(500, 'fail'); + return $this->fail([400,'节点不存在']); } Cache::put(CacheKey::get('SERVER_VMESS_LAST_CHECK_AT', $server->id), time(), 3600); $serverService = new ServerService(); @@ -93,15 +93,18 @@ class DeepbworkController extends Controller // 后端获取配置 public function config(Request $request) { - $nodeId = $request->input('node_id'); - $localPort = $request->input('local_port'); - if (empty($nodeId) || empty($localPort)) { - throw new ApiException(422, '参数错误'); - } + $request->validate([ + 'node_id' => 'required', + 'local_port' => 'required' + ],[ + 'node_id.required' => '节点ID不能为空', + 'local_port.required' => '本地端口不能为空' + ]); try { - $json = $this->getV2RayConfig($nodeId, $localPort); + $json = $this->getV2RayConfig($request->input('node_id'), $request->input('local_port')); } catch (\Exception $e) { - throw new ApiException(500, $e->getMessage()); + \Log::error($e); + throw new ApiException($e->getMessage()); } return(json_encode($json, JSON_UNESCAPED_UNICODE)); @@ -111,7 +114,7 @@ class DeepbworkController extends Controller { $server = ServerVmess::find($nodeId); if (!$server) { - throw new ApiException(500, '节点不存在'); + return $this->fail([400,'节点不存在']); } $json = json_decode(self::V2RAY_CONFIG); $json->log->loglevel = (int)admin_setting('server_log_enable') ? 'debug' : 'none'; diff --git a/app/Http/Controllers/V1/Server/ShadowsocksTidalabController.php b/app/Http/Controllers/V1/Server/ShadowsocksTidalabController.php index 41e38e0..5575b4e 100644 --- a/app/Http/Controllers/V1/Server/ShadowsocksTidalabController.php +++ b/app/Http/Controllers/V1/Server/ShadowsocksTidalabController.php @@ -21,10 +21,10 @@ class ShadowsocksTidalabController extends Controller { $token = $request->input('token'); if (empty($token)) { - throw new ApiException(500, 'token is null'); + throw new ApiException('token is null'); } if ($token !== admin_setting('server_token')) { - throw new ApiException(500, 'token is error'); + throw new ApiException('token is error'); } } @@ -35,7 +35,7 @@ class ShadowsocksTidalabController extends Controller $nodeId = $request->input('node_id'); $server = ServerShadowsocks::find($nodeId); if (!$server) { - throw new ApiException(500, 'fail'); + return $this->fail([400,'节点不存在']); } Cache::put(CacheKey::get('SERVER_SHADOWSOCKS_LAST_CHECK_AT', $server->id), time(), 3600); $serverService = new ServerService(); diff --git a/app/Http/Controllers/V1/Server/TrojanTidalabController.php b/app/Http/Controllers/V1/Server/TrojanTidalabController.php index be4eaec..b5941ca 100644 --- a/app/Http/Controllers/V1/Server/TrojanTidalabController.php +++ b/app/Http/Controllers/V1/Server/TrojanTidalabController.php @@ -22,10 +22,10 @@ class TrojanTidalabController extends Controller { $token = $request->input('token'); if (empty($token)) { - throw new ApiException(500, 'token is null'); + throw new ApiException('token is null'); } if ($token !== admin_setting('server_token')) { - throw new ApiException(500, 'token is error'); + throw new ApiException('token is error'); } } @@ -36,7 +36,7 @@ class TrojanTidalabController extends Controller $nodeId = $request->input('node_id'); $server = ServerTrojan::find($nodeId); if (!$server) { - throw new ApiException(500, 'fail'); + return $this->fail([400,'节点不存在']); } Cache::put(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $server->id), time(), 3600); $serverService = new ServerService(); @@ -89,15 +89,18 @@ class TrojanTidalabController extends Controller // 后端获取配置 public function config(Request $request) { - $nodeId = $request->input('node_id'); - $localPort = $request->input('local_port'); - if (empty($nodeId) || empty($localPort)) { - throw new ApiException(422, '参数错误'); - } + $request->validate([ + 'node_id' => 'required', + 'local_port' => 'required' + ],[ + 'node_id.required' => '节点ID不能为空', + 'local_port.required' => '本地端口不能为空' + ]); try { - $json = $this->getTrojanConfig($nodeId, $localPort); + $json = $this->getTrojanConfig($request->input('node_id'), $request->input('local_port')); } catch (\Exception $e) { - throw new ApiException(500, $e->getMessage()); + \Log::error($e); + return $this->fail([500,'配置获取失败']); } return(json_encode($json, JSON_UNESCAPED_UNICODE)); @@ -107,7 +110,7 @@ class TrojanTidalabController extends Controller { $server = ServerTrojan::find($nodeId); if (!$server) { - throw new ApiException(500, '节点不存在'); + return $this->fail([400, '节点不存在']); } $json = json_decode(self::TROJAN_CONFIG); diff --git a/app/Http/Controllers/V1/Server/UniProxyController.php b/app/Http/Controllers/V1/Server/UniProxyController.php index 73e036f..8a132fc 100644 --- a/app/Http/Controllers/V1/Server/UniProxyController.php +++ b/app/Http/Controllers/V1/Server/UniProxyController.php @@ -92,9 +92,7 @@ class UniProxyController extends Controller $userService = new UserService(); $userService->trafficFetch($this->nodeInfo->toArray(), $this->nodeType, $data , $ip); - return response([ - 'data' => true - ]); + return $this->success(true); } // 后端获取配置 @@ -174,8 +172,6 @@ class UniProxyController extends Controller // 后端提交在线数据 public function alive(Request $request) { - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Staff/NoticeController.php b/app/Http/Controllers/V1/Staff/NoticeController.php index e0c186c..cf30cb3 100644 --- a/app/Http/Controllers/V1/Staff/NoticeController.php +++ b/app/Http/Controllers/V1/Staff/NoticeController.php @@ -12,9 +12,8 @@ class NoticeController extends Controller { public function fetch(Request $request) { - return response([ - 'data' => Notice::orderBy('id', 'DESC')->get() - ]); + $data = Notice::orderBy('id', 'DESC')->get(); + return $this->success($data); } public function save(NoticeSave $request) @@ -26,34 +25,34 @@ class NoticeController extends Controller ]); if (!$request->input('id')) { if (!Notice::create($data)) { - throw new ApiException(500, '保存失败'); + return $this->fail([500, '创建失败']); } } else { try { Notice::find($request->input('id'))->update($data); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500, '保存失败']); } } - return response([ - 'data' => true - ]); + return $this->success(true); } public function drop(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); - } + $request->validate([ + 'id' => 'required' + ],[ + 'id.required' => '公告ID不能为空' + ]); + $notice = Notice::find($request->input('id')); if (!$notice) { - throw new ApiException(500, '公告不存在'); + return $this->fail([400202,'公告不存在']); } if (!$notice->delete()) { - throw new ApiException(500, '删除失败'); + return $this->fail([500,'公告删除失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Staff/PlanController.php b/app/Http/Controllers/V1/Staff/PlanController.php index 1735bf7..96a507e 100755 --- a/app/Http/Controllers/V1/Staff/PlanController.php +++ b/app/Http/Controllers/V1/Staff/PlanController.php @@ -30,8 +30,6 @@ class PlanController extends Controller if ($plans[$k]->id === $counts[$kk]->plan_id) $plans[$k]->count = $counts[$kk]->count; } } - return response([ - 'data' => $plans - ]); + return $this->success($plans); } } diff --git a/app/Http/Controllers/V1/Staff/TicketController.php b/app/Http/Controllers/V1/Staff/TicketController.php index 3456846..5944245 100644 --- a/app/Http/Controllers/V1/Staff/TicketController.php +++ b/app/Http/Controllers/V1/Staff/TicketController.php @@ -17,7 +17,7 @@ class TicketController extends Controller $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - throw new ApiException(500, '工单不存在'); + return $this->fail([400,'工单不存在']); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); for ($i = 0; $i < count($ticket['message']); $i++) { @@ -27,9 +27,7 @@ class TicketController extends Controller $ticket['message'][$i]['is_me'] = false; } } - return response([ - 'data' => $ticket - ]); + return $this->success($ticket); } $current = $request->input('current') ? $request->input('current') : 1; $pageSize = $request->input('pageSize') >= 10 ? $request->input('pageSize') : 10; @@ -48,39 +46,37 @@ class TicketController extends Controller public function reply(Request $request) { - if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); - } - if (empty($request->input('message'))) { - throw new ApiException(500, '消息不能为空'); - } + $request->validate([ + 'id' => 'required', + 'message' => 'required|string' + ],[ + 'id.required' => '工单ID不能为空', + 'message.required' => '消息不能为空' + ]); $ticketService = new TicketService(); $ticketService->replyByAdmin( $request->input('id'), $request->input('message'), $request->user['id'] ); - return response([ - 'data' => true - ]); + return $this->success(true); } public function close(Request $request) { + if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); + return $this->fail([422,'工单ID不能为空']); } $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - throw new ApiException(500, '工单不存在'); + return $this->fail([400202,'工单不存在']); } $ticket->status = 1; if (!$ticket->save()) { - throw new ApiException(500, '关闭失败'); + return $this->fail([500, '工单关闭失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Staff/UserController.php b/app/Http/Controllers/V1/Staff/UserController.php index 5b20a50..97bd9df 100644 --- a/app/Http/Controllers/V1/Staff/UserController.php +++ b/app/Http/Controllers/V1/Staff/UserController.php @@ -16,16 +16,14 @@ class UserController extends Controller public function getUserInfoById(Request $request) { if (empty($request->input('id'))) { - throw new ApiException(422, '参数错误'); + return $this->fail([422,'用户ID不能为空']); } $user = User::where('is_admin', 0) ->where('id', $request->input('id')) ->where('is_staff', 0) ->first(); - if (!$user) throw new ApiException(500, '用户不存在'); - return response([ - 'data' => $user - ]); + if (!$user) return $this->fail([400202,'用户不存在']); + return $this->success($user); } public function update(UserUpdate $request) @@ -33,10 +31,10 @@ class UserController extends Controller $params = $request->validated(); $user = User::find($request->input('id')); if (!$user) { - throw new ApiException(500, '用户不存在'); + return $this->fail([400202,'用户不存在']); } if (User::where('email', $params['email'])->first() && $user->email !== $params['email']) { - throw new ApiException(500, '邮箱已被使用'); + return $this->fail([400201,'邮箱已被使用']); } if (isset($params['password'])) { $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT); @@ -47,7 +45,7 @@ class UserController extends Controller if (isset($params['plan_id'])) { $plan = Plan::find($params['plan_id']); if (!$plan) { - throw new ApiException(500, '订阅计划不存在'); + return $this->fail([400202,'订阅不存在']); } $params['group_id'] = $plan->group_id; } @@ -55,11 +53,10 @@ class UserController extends Controller try { $user->update($params); } catch (\Exception $e) { - throw new ApiException(500, '保存失败'); + \Log::error($e); + return $this->fail([500,'更新失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function sendMail(UserSendMail $request) @@ -82,9 +79,7 @@ class UserController extends Controller ]); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function ban(Request $request) @@ -98,11 +93,10 @@ class UserController extends Controller 'banned' => 1 ]); } catch (\Exception $e) { - throw new ApiException(500, '处理失败'); + \Log::error($e); + return $this->fail([500,'处理上失败']); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/User/CommController.php b/app/Http/Controllers/V1/User/CommController.php index ec67b13..fa0ae27 100644 --- a/app/Http/Controllers/V1/User/CommController.php +++ b/app/Http/Controllers/V1/User/CommController.php @@ -12,21 +12,20 @@ class CommController extends Controller { public function config() { - return response([ - 'data' => [ - 'is_telegram' => (int)admin_setting('telegram_bot_enable', 0), - 'telegram_discuss_link' => admin_setting('telegram_discuss_link'), - 'stripe_pk' => admin_setting('stripe_pk_live'), - 'withdraw_methods' => admin_setting('commission_withdraw_method', Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT), - 'withdraw_close' => (int)admin_setting('withdraw_close_enable', 0), - 'currency' => admin_setting('currency', 'CNY'), - 'currency_symbol' => admin_setting('currency_symbol', '¥'), - 'commission_distribution_enable' => (int)admin_setting('commission_distribution_enable', 0), - 'commission_distribution_l1' => admin_setting('commission_distribution_l1'), - 'commission_distribution_l2' => admin_setting('commission_distribution_l2'), - 'commission_distribution_l3' => admin_setting('commission_distribution_l3') - ] - ]); + $data = [ + 'is_telegram' => (int)admin_setting('telegram_bot_enable', 0), + 'telegram_discuss_link' => admin_setting('telegram_discuss_link'), + 'stripe_pk' => admin_setting('stripe_pk_live'), + 'withdraw_methods' => admin_setting('commission_withdraw_method', Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT), + 'withdraw_close' => (int)admin_setting('withdraw_close_enable', 0), + 'currency' => admin_setting('currency', 'CNY'), + 'currency_symbol' => admin_setting('currency_symbol', '¥'), + 'commission_distribution_enable' => (int)admin_setting('commission_distribution_enable', 0), + 'commission_distribution_l1' => admin_setting('commission_distribution_l1'), + 'commission_distribution_l2' => admin_setting('commission_distribution_l2'), + 'commission_distribution_l3' => admin_setting('commission_distribution_l3') + ]; + return $this->success($data); } public function getStripePublicKey(Request $request) @@ -34,9 +33,7 @@ class CommController extends Controller $payment = Payment::where('id', $request->input('id')) ->where('payment', 'StripeCredit') ->first(); - if (!$payment) throw new ApiException(500, 'payment is not found'); - return response([ - 'data' => $payment->config['stripe_pk_live'] - ]); + if (!$payment) throw new ApiException('payment is not found'); + return $this->success($payment->config['stripe_pk_live']); } } diff --git a/app/Http/Controllers/V1/User/CouponController.php b/app/Http/Controllers/V1/User/CouponController.php index fe29188..a70dcc2 100644 --- a/app/Http/Controllers/V1/User/CouponController.php +++ b/app/Http/Controllers/V1/User/CouponController.php @@ -12,14 +12,12 @@ class CouponController extends Controller public function check(Request $request) { if (empty($request->input('code'))) { - throw new ApiException(500, __('Coupon cannot be empty')); + return $this->fail([422,__('Coupon cannot be empty')]); } $couponService = new CouponService($request->input('code')); $couponService->setPlanId($request->input('plan_id')); $couponService->setUserId($request->user['id']); $couponService->check(); - return response([ - 'data' => $couponService->getCoupon() - ]); + return $this->success($couponService->getCoupon()); } } diff --git a/app/Http/Controllers/V1/User/InviteController.php b/app/Http/Controllers/V1/User/InviteController.php index e4c35c7..83295fe 100644 --- a/app/Http/Controllers/V1/User/InviteController.php +++ b/app/Http/Controllers/V1/User/InviteController.php @@ -16,14 +16,12 @@ class InviteController extends Controller public function save(Request $request) { if (InviteCode::where('user_id', $request->user['id'])->where('status', 0)->count() >= admin_setting('invite_gen_limit', 5)) { - throw new ApiException(500, __('The maximum number of creations has been reached')); + return $this->fail([400,__('The maximum number of creations has been reached')]); } $inviteCode = new InviteCode(); $inviteCode->user_id = $request->user['id']; $inviteCode->code = Helper::randomChar(8); - return response([ - 'data' => $inviteCode->save() - ]); + return $this->success($inviteCode->save()); } public function details(Request $request) @@ -79,11 +77,12 @@ class InviteController extends Controller //可用佣金 (int)$user->commission_balance ]; - return response([ + $data = [ 'data' => [ 'codes' => $codes, 'stat' => $stat ] - ]); + ]; + return $this->success($data); } } diff --git a/app/Http/Controllers/V1/User/KnowledgeController.php b/app/Http/Controllers/V1/User/KnowledgeController.php index b79a749..ac412aa 100644 --- a/app/Http/Controllers/V1/User/KnowledgeController.php +++ b/app/Http/Controllers/V1/User/KnowledgeController.php @@ -19,7 +19,7 @@ class KnowledgeController extends Controller ->where('show', 1) ->first() ->toArray(); - if (!$knowledge) throw new ApiException(500, __('Article does not exist')); + if (!$knowledge) return $this->fail([500, __('Article does not exist')]); $user = User::find($request->user['id']); $userService = new UserService(); if (!$userService->isAvailable($user)) { @@ -38,9 +38,7 @@ class KnowledgeController extends Controller ), $knowledge['body'] ); - return response([ - 'data' => $knowledge - ]); + return $this->success($knowledge); } $builder = Knowledge::select(['id', 'category', 'title', 'updated_at']) ->where('language', $request->input('language')) @@ -56,9 +54,7 @@ class KnowledgeController extends Controller $knowledges = $builder->get() ->groupBy('category'); - return response([ - 'data' => $knowledges - ]); + return $this->success($knowledges); } private function formatAccessData(&$body) diff --git a/app/Http/Controllers/V1/User/OrderController.php b/app/Http/Controllers/V1/User/OrderController.php index 978a801..8bff4a2 100755 --- a/app/Http/Controllers/V1/User/OrderController.php +++ b/app/Http/Controllers/V1/User/OrderController.php @@ -16,14 +16,7 @@ use App\Services\PlanService; use App\Services\UserService; use App\Utils\Helper; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; -use Library\BitpayX; -use Library\Epay; -use Library\MGate; -use Omnipay\Omnipay; -use Stripe\Source; -use Stripe\Stripe; class OrderController extends Controller { @@ -43,9 +36,7 @@ class OrderController extends Controller } } } - return response([ - 'data' => $order->makeHidden(['id', 'user_id']) - ]); + return $this->success($order->makeHidden(['id', 'user_id'])); } public function detail(Request $request) @@ -54,26 +45,24 @@ class OrderController extends Controller ->where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - throw new ApiException(500, __('Order does not exist or has been paid')); + return $this->fail([400, __('Order does not exist or has been paid')]); } $order['plan'] = Plan::find($order->plan_id); $order['try_out_plan_id'] = (int)admin_setting('try_out_plan_id'); if (!$order['plan']) { - throw new ApiException(500, __('Subscription plan does not exist')); + return $this->fail([400, __('Subscription plan does not exist')]); } if ($order->surplus_order_ids) { $order['surplus_orders'] = Order::whereIn('id', $order->surplus_order_ids)->get(); } - return response([ - 'data' => $order - ]); + return $this->success($order); } public function save(OrderSave $request) { $userService = new UserService(); if ($userService->isNotCompleteOrderByUserId($request->user['id'])) { - throw new ApiException(500, __('You have an unpaid or pending order, please try again later or cancel it')); + return $this->fail([400, __('You have an unpaid or pending order, please try again later or cancel it')]); } $planService = new PlanService($request->input('plan_id')); @@ -82,36 +71,36 @@ class OrderController extends Controller $user = User::find($request->user['id']); if (!$plan) { - throw new ApiException(500, __('Subscription plan does not exist')); + return $this->fail([400, __('Subscription plan does not exist')]); } if ($user->plan_id !== $plan->id && !$planService->haveCapacity() && $request->input('period') !== 'reset_price') { - throw new ApiException(500, __('Current product is sold out')); + throw new ApiException(__('Current product is sold out')); } if ($plan[$request->input('period')] === NULL) { - throw new ApiException(500, __('This payment period cannot be purchased, please choose another period')); + return $this->fail([400, __('This payment period cannot be purchased, please choose another period')]); } if ($request->input('period') === 'reset_price') { if (!$userService->isAvailable($user) || $plan->id !== $user->plan_id) { - throw new ApiException(500, __('Subscription has expired or no active subscription, unable to purchase Data Reset Package')); + return $this->fail([400, __('Subscription has expired or no active subscription, unable to purchase Data Reset Package')]); } } if ((!$plan->show && !$plan->renew) || (!$plan->show && $user->plan_id !== $plan->id)) { if ($request->input('period') !== 'reset_price') { - throw new ApiException(500, __('This subscription has been sold out, please choose another subscription')); + return $this->fail([400, __('This subscription has been sold out, please choose another subscription')]); } } if (!$plan->renew && $user->plan_id == $plan->id && $request->input('period') !== 'reset_price') { - throw new ApiException(500, __('This subscription cannot be renewed, please change to another subscription')); + return $this->fail([400, __('This subscription cannot be renewed, please change to another subscription')]); } if (!$plan->show && $plan->renew && !$userService->isAvailable($user)) { - throw new ApiException(500, __('This subscription has expired, please change to another subscription')); + return $this->fail([400, __('This subscription has expired, please change to another subscription')]); } try{ @@ -127,7 +116,7 @@ class OrderController extends Controller if ($request->input('coupon_code')) { $couponService = new CouponService($request->input('coupon_code')); if (!$couponService->use($order)) { - throw new ApiException(500, __('Coupon failed')); + return $this->fail([400, __('Coupon failed')]); } $order->coupon_id = $couponService->getId(); } @@ -141,13 +130,13 @@ class OrderController extends Controller $userService = new UserService(); if ($remainingBalance > 0) { if (!$userService->addBalance($order->user_id, - $order->total_amount)) { - throw new ApiException(500, __('Insufficient balance')); + return $this->fail([400, __('Insufficient balance')]); } $order->balance_amount = $order->total_amount; $order->total_amount = 0; } else { if (!$userService->addBalance($order->user_id, - $user->balance)) { - throw new ApiException(500, __('Insufficient balance')); + return $this->fail([400, __('Insufficient balance')]); } $order->balance_amount = $user->balance; $order->total_amount = $order->total_amount - $user->balance; @@ -155,7 +144,7 @@ class OrderController extends Controller } if (!$order->save()) { - throw new ApiException(500, __('Failed to create order')); + return $this->fail([400, __('Failed to create order')]); } DB::commit(); }catch (\Exception $e){ @@ -163,9 +152,7 @@ class OrderController extends Controller throw $e; } - return response([ - 'data' => $order->trade_no - ]); + return $this->success($order->trade_no); } public function checkout(Request $request) @@ -177,26 +164,26 @@ class OrderController extends Controller ->where('status', 0) ->first(); if (!$order) { - throw new ApiException(500, __('Order does not exist or has been paid')); + return $this->fail([400, __('Order does not exist or has been paid')]); } // free process if ($order->total_amount <= 0) { $orderService = new OrderService($order); - if (!$orderService->paid($order->trade_no)) throw new ApiException(500, ''); + if (!$orderService->paid($order->trade_no)) return $this->fail([400, '支付失败']); return response([ 'type' => -1, 'data' => true ]); } $payment = Payment::find($method); - if (!$payment || $payment->enable !== 1) throw new ApiException(500, __('Payment method is not available')); + if (!$payment || $payment->enable !== 1) return $this->fail([400, __('Payment method is not available')]); $paymentService = new PaymentService($payment->payment, $payment->id); $order->handling_amount = NULL; if ($payment->handling_fee_fixed || $payment->handling_fee_percent) { $order->handling_amount = round(($order->total_amount * ($payment->handling_fee_percent / 100)) + $payment->handling_fee_fixed); } $order->payment_id = $method; - if (!$order->save()) throw new ApiException(500, __('Request failed, please try again later')); + if (!$order->save()) return $this->fail([400, __('Request failed, please try again later')]); $result = $paymentService->pay([ 'trade_no' => $tradeNo, 'total_amount' => isset($order->handling_amount) ? ($order->total_amount + $order->handling_amount) : $order->total_amount, @@ -216,11 +203,9 @@ class OrderController extends Controller ->where('user_id', $request->user['id']) ->first(); if (!$order) { - throw new ApiException(500, __('Order does not exist')); + return $this->fail([400, __('Order does not exist')]); } - return response([ - 'data' => $order->status - ]); + return $this->success($order->status); } public function getPaymentMethod() @@ -237,31 +222,27 @@ class OrderController extends Controller ->orderBy('sort', 'ASC') ->get(); - return response([ - 'data' => $methods - ]); + return $this->success($methods); } public function cancel(Request $request) { if (empty($request->input('trade_no'))) { - throw new ApiException(500, __('Invalid parameter')); + return $this->fail([422, __('Invalid parameter')]); } $order = Order::where('trade_no', $request->input('trade_no')) ->where('user_id', $request->user['id']) ->first(); if (!$order) { - throw new ApiException(500, __('Order does not exist')); + return $this->fail([400, __('Order does not exist')]); } if ($order->status !== 0) { - throw new ApiException(500, __('You can only cancel pending orders')); + return $this->fail([400, __('You can only cancel pending orders')]); } $orderService = new OrderService($order); if (!$orderService->cancel()) { - throw new ApiException(500, __('Cancel failed')); + return $this->fail([400, __('Cancel failed')]); } - return response([ - 'data' => true - ]); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/User/PlanController.php b/app/Http/Controllers/V1/User/PlanController.php index ffd6f29..3b3ab27 100755 --- a/app/Http/Controllers/V1/User/PlanController.php +++ b/app/Http/Controllers/V1/User/PlanController.php @@ -8,7 +8,6 @@ use App\Models\Plan; use App\Models\User; use App\Services\PlanService; use Illuminate\Http\Request; -use Illuminate\Support\Facades\DB; class PlanController extends Controller { @@ -18,14 +17,12 @@ class PlanController extends Controller if ($request->input('id')) { $plan = Plan::where('id', $request->input('id'))->first(); if (!$plan) { - throw new ApiException(500, __('Subscription plan does not exist')); + return $this->fail([400, __('Subscription plan does not exist')]); } if ((!$plan->show && !$plan->renew) || (!$plan->show && $user->plan_id !== $plan->id)) { - throw new ApiException(500, __('Subscription plan does not exist')); + return $this->fail([400, __('Subscription plan does not exist')]); } - return response([ - 'data' => $plan - ]); + return $this->success($plan); } $counts = PlanService::countActiveUsers(); @@ -37,8 +34,6 @@ class PlanController extends Controller if (!isset($counts[$plans[$k]->id])) continue; $plans[$k]->capacity_limit = $plans[$k]->capacity_limit - $counts[$plans[$k]->id]->count; } - return response([ - 'data' => $plans - ]); + return $this->success($plans); } } diff --git a/app/Http/Controllers/V1/User/StatController.php b/app/Http/Controllers/V1/User/StatController.php index 93097cf..3870b13 100644 --- a/app/Http/Controllers/V1/User/StatController.php +++ b/app/Http/Controllers/V1/User/StatController.php @@ -37,8 +37,6 @@ class StatController extends Controller } }; - return response([ - 'data' => $records - ]); + return $this->success($records); } } diff --git a/app/Http/Controllers/V1/User/TelegramController.php b/app/Http/Controllers/V1/User/TelegramController.php index 06a58ef..61709c2 100644 --- a/app/Http/Controllers/V1/User/TelegramController.php +++ b/app/Http/Controllers/V1/User/TelegramController.php @@ -13,11 +13,10 @@ class TelegramController extends Controller { $telegramService = new TelegramService(); $response = $telegramService->getMe(); - return response([ - 'data' => [ - 'username' => $response->result->username - ] - ]); + $data = [ + 'username' => $response->result->username + ]; + return $this->success($data); } public function unbind(Request $request) diff --git a/app/Http/Controllers/V1/User/TicketController.php b/app/Http/Controllers/V1/User/TicketController.php index 44df938..573826b 100644 --- a/app/Http/Controllers/V1/User/TicketController.php +++ b/app/Http/Controllers/V1/User/TicketController.php @@ -24,7 +24,7 @@ class TicketController extends Controller ->where('user_id', $request->user['id']) ->first(); if (!$ticket) { - throw new ApiException(500, __('Ticket does not exist')); + return $this->fail([400, __('Ticket does not exist')]); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); for ($i = 0; $i < count($ticket['message']); $i++) { @@ -34,16 +34,12 @@ class TicketController extends Controller $ticket['message'][$i]['is_me'] = false; } } - return response([ - 'data' => $ticket - ]); + return $this->success($ticket); } $ticket = Ticket::where('user_id', $request->user['id']) ->orderBy('created_at', 'DESC') ->get(); - return response([ - 'data' => $ticket - ]); + return $this->success($ticket); } public function save(TicketSave $request) @@ -51,7 +47,7 @@ class TicketController extends Controller try{ DB::beginTransaction(); if ((int)Ticket::where('status', 0)->where('user_id', $request->user['id'])->lockForUpdate()->count()) { - throw new ApiException(500, __('There are other unresolved tickets')); + return $this->fail([400, __('There are other unresolved tickets')]); } $ticket = Ticket::create(array_merge($request->only([ 'subject', @@ -60,7 +56,7 @@ class TicketController extends Controller 'user_id' => $request->user['id'] ])); if (!$ticket) { - throw new ApiException(500, __('Failed to open ticket')); + return $this->fail([400, __('Failed to open ticket')]); } $ticketMessage = TicketMessage::create([ 'user_id' => $request->user['id'], @@ -68,7 +64,7 @@ class TicketController extends Controller 'message' => $request->input('message') ]); if (!$ticketMessage) { - throw new ApiException(500, __('Failed to open ticket')); + return $this->fail([400, __('Failed to open ticket')]); } DB::commit(); }catch(\Exception $e){ @@ -76,30 +72,28 @@ class TicketController extends Controller throw $e; } $this->sendNotify($ticket, $request->input('message')); - return response([ - 'data' => true - ]); + return $this->success(true); } public function reply(Request $request) { if (empty($request->input('id'))) { - throw new ApiException(500, __('Invalid parameter')); + return $this->fail([400, __('Invalid parameter')]); } if (empty($request->input('message'))) { - throw new ApiException(500, __('Message cannot be empty')); + return $this->fail([400, __('Message cannot be empty')]); } $ticket = Ticket::where('id', $request->input('id')) ->where('user_id', $request->user['id']) ->first(); if (!$ticket) { - throw new ApiException(500, __('Ticket does not exist')); + return $this->fail([400, __('Ticket does not exist')]); } if ($ticket->status) { - throw new ApiException(500, __('The ticket is closed and cannot be replied')); + return $this->fail([400, __('The ticket is closed and cannot be replied')]); } if ($request->user['id'] == $this->getLastMessage($ticket->id)->user_id) { - throw new ApiException(500, __('Please wait for the technical enginneer to reply')); + return $this->fail([400, __('Please wait for the technical enginneer to reply')]); } $ticketService = new TicketService(); if (!$ticketService->reply( @@ -107,33 +101,29 @@ class TicketController extends Controller $request->input('message'), $request->user['id'] )) { - throw new ApiException(500, __('Ticket reply failed')); + return $this->fail([400, __('Ticket reply failed')]); } $this->sendNotify($ticket, $request->input('message')); - return response([ - 'data' => true - ]); + return $this->success(true); } public function close(Request $request) { if (empty($request->input('id'))) { - throw new ApiException(500, __('Invalid parameter')); + return $this->fail([422, __('Invalid parameter')]); } $ticket = Ticket::where('id', $request->input('id')) ->where('user_id', $request->user['id']) ->first(); if (!$ticket) { - throw new ApiException(500, __('Ticket does not exist')); + return $this->fail([400, __('Ticket does not exist')]); } $ticket->status = 1; if (!$ticket->save()) { - throw new ApiException(500, __('Close failed')); + return $this->fail([500, __('Close failed')]); } - return response([ - 'data' => true - ]); + return $this->success(true); } private function getLastMessage($ticketId) @@ -146,18 +136,18 @@ class TicketController extends Controller public function withdraw(TicketWithdraw $request) { if ((int)admin_setting('withdraw_close_enable', 0)) { - throw new ApiException(500, 'user.ticket.withdraw.not_support_withdraw'); + return $this->fail([400, 'Unsupported withdraw']); } if (!in_array( $request->input('withdraw_method'), admin_setting('commission_withdraw_method',Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT) )) { - throw new ApiException(500, __('Unsupported withdrawal method')); + return $this->fail([422, __('Unsupported withdrawal method')]); } $user = User::find($request->user['id']); $limit = admin_setting('commission_withdraw_limit', 100); if ($limit > ($user->commission_balance / 100)) { - throw new ApiException(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit])); + return $this->fail([422, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit])]); } try{ DB::beginTransaction(); @@ -168,7 +158,7 @@ class TicketController extends Controller 'user_id' => $request->user['id'] ]); if (!$ticket) { - throw new ApiException(500, __('Failed to open ticket')); + return $this->fail([400, __('Failed to open ticket')]); } $message = sprintf("%s\r\n%s", __('Withdrawal method') . ":" . $request->input('withdraw_method'), @@ -180,7 +170,7 @@ class TicketController extends Controller 'message' => $message ]); if (!$ticketMessage) { - throw new ApiException(500, __('Failed to open ticket')); + return $this->fail([400, __('Failed to open ticket')]); } DB::commit(); }catch(\Exception $e){ @@ -188,9 +178,7 @@ class TicketController extends Controller throw $e; } $this->sendNotify($ticket, $message); - return response([ - 'data' => true - ]); + return $this->success(true); } private function sendNotify(Ticket $ticket, string $message) diff --git a/app/Http/Controllers/V1/User/UserController.php b/app/Http/Controllers/V1/User/UserController.php index be79f70..0dbe572 100755 --- a/app/Http/Controllers/V1/User/UserController.php +++ b/app/Http/Controllers/V1/User/UserController.php @@ -24,24 +24,20 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } $authService = new AuthService($user); - return response([ - 'data' => $authService->getSessions() - ]); + return $this->success($authService->getSessions()); } public function removeActiveSession(Request $request) { $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } $authService = new AuthService($user); - return response([ - 'data' => $authService->removeSession($request->input('session_id')) - ]); + return $this->success($authService->removeSession($request->input('session_id'))); } public function checkLogin(Request $request) @@ -52,16 +48,14 @@ class UserController extends Controller if ($request->user['is_admin']) { $data['is_admin'] = true; } - return response([ - 'data' => $data - ]); + return $this->success($data); } public function changePassword(UserChangePassword $request) { $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } if (!Helper::multiPasswordVerify( $user->password_algo, @@ -69,17 +63,15 @@ class UserController extends Controller $request->input('old_password'), $user->password) ) { - throw new ApiException(500, __('The old password is wrong')); + return $this->fail([400, __('The old password is wrong')]); } $user->password = password_hash($request->input('new_password'), PASSWORD_DEFAULT); $user->password_algo = NULL; $user->password_salt = NULL; if (!$user->save()) { - throw new ApiException(500, __('Save failed')); + return $this->fail([400, __('Save failed')]); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function info(Request $request) @@ -104,12 +96,10 @@ class UserController extends Controller ]) ->first(); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } $user['avatar_url'] = 'https://cdn.v2ex.com/gravatar/' . md5($user->email) . '?s=64&d=identicon'; - return response([ - 'data' => $user - ]); + return $this->success($user); } public function getStat(Request $request) @@ -124,9 +114,7 @@ class UserController extends Controller User::where('invite_user_id', $request->user['id']) ->count() ]; - return response([ - 'data' => $stat - ]); + return $this->success($stat); } public function getSubscribe(Request $request) @@ -144,36 +132,32 @@ class UserController extends Controller ]) ->first(); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } if ($user->plan_id) { $user['plan'] = Plan::find($user->plan_id); if (!$user['plan']) { - throw new ApiException(500, __('Subscription plan does not exist')); + return $this->fail([400, __('Subscription plan does not exist')]); } } $user['subscribe_url'] = Helper::getSubscribeUrl("/api/v1/client/subscribe?token={$user['token']}"); $userService = new UserService(); $user['reset_day'] = $userService->getResetDay($user); - return response([ - 'data' => $user - ]); + return $this->success($user); } public function resetSecurity(Request $request) { $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } $user->uuid = Helper::guid(true); $user->token = Helper::guid(); if (!$user->save()) { - throw new ApiException(500, __('Reset failed')); + return $this->fail([400, __('Reset failed')]); } - return response([ - 'data' => Helper::getSubscribeUrl('/api/v1/client/subscribe?token=' . $user->token) - ]); + return $this->success(Helper::getSubscribeUrl('/api/v1/client/subscribe?token=' . $user->token)); } public function update(UserUpdate $request) @@ -185,43 +169,39 @@ class UserController extends Controller $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } try { $user->update($updateData); } catch (\Exception $e) { - throw new ApiException(500, __('Save failed')); + return $this->fail([400, __('Save failed')]); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function transfer(UserTransfer $request) { $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } if ($request->input('transfer_amount') > $user->commission_balance) { - throw new ApiException(500, __('Insufficient commission balance')); + return $this->fail([400, __('Insufficient commission balance')]); } $user->commission_balance = $user->commission_balance - $request->input('transfer_amount'); $user->balance = $user->balance + $request->input('transfer_amount'); if (!$user->save()) { - throw new ApiException(500, __('Transfer failed')); + return $this->fail([400, __('Transfer failed')]); } - return response([ - 'data' => true - ]); + return $this->success(true); } public function getQuickLoginUrl(Request $request) { $user = User::find($request->user['id']); if (!$user) { - throw new ApiException(500, __('The user does not exist')); + return $this->fail([400, __('The user does not exist')]); } $code = Helper::guid(); @@ -233,8 +213,6 @@ class UserController extends Controller } else { $url = url($redirect); } - return response([ - 'data' => $url - ]); + return $this->success($url); } } diff --git a/app/Http/Middleware/Admin.php b/app/Http/Middleware/Admin.php index d712d31..a5a8d86 100755 --- a/app/Http/Middleware/Admin.php +++ b/app/Http/Middleware/Admin.php @@ -19,10 +19,10 @@ class Admin public function handle($request, Closure $next) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException('未登录或登陆已过期', 403); $user = AuthService::decryptAuthData($authorization); - if (!$user || !$user['is_admin']) throw new ApiException(403, '未登录或登陆已过期'); + if (!$user || !$user['is_admin']) throw new ApiException('未登录或登陆已过期',403); $request->merge([ 'user' => $user ]); diff --git a/app/Http/Middleware/Client.php b/app/Http/Middleware/Client.php index d46378b..fd4086e 100755 --- a/app/Http/Middleware/Client.php +++ b/app/Http/Middleware/Client.php @@ -21,11 +21,11 @@ class Client { $token = $request->input('token'); if (empty($token)) { - throw new ApiException(403, 'token is null'); + throw new ApiException('token is null',403); } $user = User::where('token', $token)->first(); if (!$user) { - throw new ApiException(403, 'token is error'); + throw new ApiException('token is error',403); } $request->merge([ 'user' => $user diff --git a/app/Http/Middleware/Staff.php b/app/Http/Middleware/Staff.php index f51fd5e..5c700c1 100644 --- a/app/Http/Middleware/Staff.php +++ b/app/Http/Middleware/Staff.php @@ -18,10 +18,10 @@ class Staff public function handle($request, Closure $next) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException( '未登录或登陆已过期', 403); $user = AuthService::decryptAuthData($authorization); - if (!$user || !$user['is_staff']) throw new ApiException(403, '未登录或登陆已过期'); + if (!$user || !$user['is_staff']) throw new ApiException('未登录或登陆已过期', 403); $request->merge([ 'user' => $user ]); diff --git a/app/Http/Middleware/User.php b/app/Http/Middleware/User.php index 0b1e64f..b0483d6 100755 --- a/app/Http/Middleware/User.php +++ b/app/Http/Middleware/User.php @@ -19,10 +19,10 @@ class User public function handle($request, Closure $next) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException( '未登录或登陆已过期', 403); $user = AuthService::decryptAuthData($authorization); - if (!$user) throw new ApiException(403, '未登录或登陆已过期'); + if (!$user) throw new ApiException('未登录或登陆已过期', 403); $request->merge([ 'user' => $user ]); diff --git a/app/Http/Routes/V1/ServerRoute.php b/app/Http/Routes/V1/ServerRoute.php index 28db7f4..da4370d 100644 --- a/app/Http/Routes/V1/ServerRoute.php +++ b/app/Http/Routes/V1/ServerRoute.php @@ -15,7 +15,7 @@ class ServerRoute $router->any('/{class}/{action}', function($class, $action) { $controllerClass = "\\App\\Http\\Controllers\\V1\\Server\\" . ucfirst($class) . "Controller"; if(!(class_exists($controllerClass) && method_exists($controllerClass, $action))){ - throw new ApiException(404,'Not Found'); + throw new ApiException('Not Found',404); }; $ctrl = \App::make($controllerClass); return \App::call([$ctrl, $action]); diff --git a/app/Models/User.php b/app/Models/User.php index 01c3eb5..07f9945 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -13,4 +13,11 @@ class User extends Model 'created_at' => 'timestamp', 'updated_at' => 'timestamp' ]; + + + // 获取邀请人信息 + public function invite_user() + { + return $this->belongsTo(self::class, 'invite_user_id', 'id'); + } } diff --git a/app/Payments/AlipayF2F.php b/app/Payments/AlipayF2F.php index fdd7bf9..d4a587c 100644 --- a/app/Payments/AlipayF2F.php +++ b/app/Payments/AlipayF2F.php @@ -58,7 +58,8 @@ class AlipayF2F { 'data' => $gateway->getQrCodeUrl() ]; } catch (\Exception $e) { - throw new ApiException(500, $e->getMessage()); + \Log::error($e); + throw new ApiException($e->getMessage()); } } diff --git a/app/Payments/BTCPay.php b/app/Payments/BTCPay.php index 2f404cf..3822261 100644 --- a/app/Payments/BTCPay.php +++ b/app/Payments/BTCPay.php @@ -53,7 +53,7 @@ class BTCPay { $ret = @json_decode($ret_raw, true); if(empty($ret['checkoutLink'])) { - throw new ApiException(500, "error!"); + throw new ApiException("error!"); } return [ 'type' => 1, // Redirect to url @@ -76,7 +76,7 @@ class BTCPay { $computedSignature = "sha256=" . \hash_hmac('sha256', $payload, $this->config['btcpay_webhook_key']); if (!self::hashEqual($signraturHeader, $computedSignature)) { - throw new ApiException(400, 'HMAC signature does not match'); + throw new ApiException('HMAC signature does not match',400); return false; } @@ -98,7 +98,6 @@ class BTCPay { 'trade_no' => $out_trade_no, 'callback_no' => $pay_trade_no ]; - return response('success', 200); } diff --git a/app/Payments/CoinPayments.php b/app/Payments/CoinPayments.php index 2192be2..e4bb244 100644 --- a/app/Payments/CoinPayments.php +++ b/app/Payments/CoinPayments.php @@ -63,7 +63,7 @@ class CoinPayments { { if (!isset($params['merchant']) || $params['merchant'] != trim($this->config['coinpayments_merchant_id'])) { - throw new ApiException(500, 'No or incorrect Merchant ID passed'); + throw new ApiException('No or incorrect Merchant ID passed'); } $headers = getallheaders(); @@ -82,7 +82,7 @@ class CoinPayments { // } if (!hash_equals($hmac, $signHeader)) { - throw new ApiException(400, 'HMAC signature does not match'); + throw new ApiException('HMAC signature does not match', 400); } // HMAC Signature verified at this point, load some variables. @@ -96,7 +96,7 @@ class CoinPayments { ]; } else if ($status < 0) { //payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent - throw new ApiException(500, 'Payment Timed Out or Error'); + throw new ApiException('Payment Timed Out or Error'); } else { //payment is pending, you can optionally add a note to the order page return('IPN OK: pending'); diff --git a/app/Payments/Coinbase.php b/app/Payments/Coinbase.php index e4ab4f5..77897e1 100644 --- a/app/Payments/Coinbase.php +++ b/app/Payments/Coinbase.php @@ -51,7 +51,7 @@ class Coinbase { $ret = @json_decode($ret_raw, true); if(empty($ret['data']['hosted_url'])) { - throw new ApiException(500, "error!"); + throw new ApiException("error!"); } return [ 'type' => 1, @@ -71,7 +71,7 @@ class Coinbase { $computedSignature = \hash_hmac('sha256', $payload, $this->config['coinbase_webhook_key']); if (!self::hashEqual($signatureHeader, $computedSignature)) { - throw new ApiException(400, 'HMAC signature does not match'); + throw new ApiException( 'HMAC signature does not match', 400); } $out_trade_no = $json_param['event']['data']['metadata']['outTradeNo']; @@ -80,7 +80,6 @@ class Coinbase { 'trade_no' => $out_trade_no, 'callback_no' => $pay_trade_no ]; - return response('success', 200); } diff --git a/app/Payments/MGate.php b/app/Payments/MGate.php index 46f877c..9c359b9 100644 --- a/app/Payments/MGate.php +++ b/app/Payments/MGate.php @@ -63,21 +63,21 @@ class MGate { $curl->post($this->config['mgate_url'] . '/v1/gateway/fetch', http_build_query($params)); $result = $curl->response; if (!$result) { - throw new ApiException(500, '网络异常'); + throw new ApiException('网络异常'); } if ($curl->error) { if (isset($result->errors)) { $errors = (array)$result->errors; - throw new ApiException(500, $errors[array_keys($errors)[0]][0]); + throw new ApiException($errors[array_keys($errors)[0]][0]); } if (isset($result->message)) { - throw new ApiException(500, $result->message); + throw new ApiException($result->message); } - throw new ApiException(500, '未知错误'); + throw new ApiException('未知错误'); } $curl->close(); if (!isset($result->data->trade_no)) { - throw new ApiException(500, '接口请求失败'); + throw new ApiException('接口请求失败'); } return [ 'type' => 1, // 0:qrcode 1:url diff --git a/app/Payments/StripeAlipay.php b/app/Payments/StripeAlipay.php index 92a3b83..ec2bc9a 100644 --- a/app/Payments/StripeAlipay.php +++ b/app/Payments/StripeAlipay.php @@ -41,7 +41,7 @@ class StripeAlipay { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - throw new ApiException(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(__('Currency conversion has timed out, please try again later')); } Stripe::setApiKey($this->config['stripe_sk_live']); $source = Source::create([ @@ -59,7 +59,7 @@ class StripeAlipay { ] ]); if (!$source['redirect']['url']) { - throw new ApiException(500, __('Payment gateway request failed')); + throw new ApiException(__('Payment gateway request failed')); } return [ 'type' => 1, @@ -77,7 +77,7 @@ class StripeAlipay { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - throw new ApiException(400); + abort(400); } switch ($event->type) { case 'source.chargeable': @@ -104,7 +104,7 @@ class StripeAlipay { } break; default: - throw new ApiException(500, 'event is not support'); + throw new ApiException('event is not support'); } return('success'); } diff --git a/app/Payments/StripeCheckout.php b/app/Payments/StripeCheckout.php index bf2663b..cd0688e 100644 --- a/app/Payments/StripeCheckout.php +++ b/app/Payments/StripeCheckout.php @@ -48,7 +48,7 @@ class StripeCheckout { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - throw new ApiException(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(__('Currency conversion has timed out, please try again later')); } $customFieldName = isset($this->config['stripe_custom_field_name']) ? $this->config['stripe_custom_field_name'] : 'Contact Infomation'; @@ -87,7 +87,7 @@ class StripeCheckout { $session = Session::create($params); } catch (\Exception $e) { info($e); - throw new ApiException(500, "Failed to create order. Error: {$e->getMessage}"); + throw new ApiException("Failed to create order. Error: {$e->getMessage}"); } return [ 'type' => 1, // 0:qrcode 1:url @@ -105,7 +105,7 @@ class StripeCheckout { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - throw new ApiException(400); + abort(400); } switch ($event->type) { @@ -126,7 +126,7 @@ class StripeCheckout { ]; break; default: - throw new ApiException(500, 'event is not support'); + throw new ApiException('event is not support'); } return('success'); } diff --git a/app/Payments/StripeCredit.php b/app/Payments/StripeCredit.php index 1527677..6cbb8ee 100644 --- a/app/Payments/StripeCredit.php +++ b/app/Payments/StripeCredit.php @@ -47,7 +47,7 @@ class StripeCredit { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - throw new ApiException(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(__('Currency conversion has timed out, please try again later')); } Stripe::setApiKey($this->config['stripe_sk_live']); try { @@ -63,10 +63,10 @@ class StripeCredit { ]); } catch (\Exception $e) { info($e); - throw new ApiException(500, __('Payment failed. Please check your credit card information')); + throw new ApiException(__('Payment failed. Please check your credit card information')); } if (!$charge->paid) { - throw new ApiException(500, __('Payment failed. Please check your credit card information')); + throw new ApiException(__('Payment failed. Please check your credit card information')); } return [ 'type' => 2, @@ -84,7 +84,8 @@ class StripeCredit { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - throw new ApiException(400); + \Log::error($e); + abort(400); } switch ($event->type) { case 'source.chargeable': @@ -111,7 +112,7 @@ class StripeCredit { } break; default: - throw new ApiException(500, 'event is not support'); + throw new ApiException('event is not support'); } return('success'); } diff --git a/app/Payments/StripeWepay.php b/app/Payments/StripeWepay.php index 7c63fa1..885655e 100644 --- a/app/Payments/StripeWepay.php +++ b/app/Payments/StripeWepay.php @@ -41,7 +41,7 @@ class StripeWepay { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - throw new ApiException(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(__('Currency conversion has timed out, please try again later')); } Stripe::setApiKey($this->config['stripe_sk_live']); $source = Source::create([ @@ -59,7 +59,7 @@ class StripeWepay { ] ]); if (!$source['wechat']['qr_code_url']) { - throw new ApiException(500, __('Payment gateway request failed')); + throw new ApiException(__('Payment gateway request failed')); } return [ 'type' => 0, @@ -77,7 +77,7 @@ class StripeWepay { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - throw new ApiException(400); + abort(400); } switch ($event->type) { case 'source.chargeable': @@ -104,7 +104,7 @@ class StripeWepay { } break; default: - throw new ApiException(500, 'event is not support'); + throw new ApiException('event is not support'); } return('success'); } diff --git a/app/Payments/WechatPayNative.php b/app/Payments/WechatPayNative.php index 1ba47b4..7ac31cf 100644 --- a/app/Payments/WechatPayNative.php +++ b/app/Payments/WechatPayNative.php @@ -53,7 +53,7 @@ class WechatPayNative { $response = $request->send(); $response = $response->getData(); if ($response['return_code'] !== 'SUCCESS') { - throw new ApiException(500, $response['return_msg']); + throw new ApiException($response['return_msg']); } return [ 'type' => 0, diff --git a/app/Plugins/Telegram/Commands/Bind.php b/app/Plugins/Telegram/Commands/Bind.php index e33402c..93b62b8 100644 --- a/app/Plugins/Telegram/Commands/Bind.php +++ b/app/Plugins/Telegram/Commands/Bind.php @@ -13,25 +13,25 @@ class Bind extends Telegram { public function handle($message, $match = []) { if (!$message->is_private) return; if (!isset($message->args[0])) { - throw new ApiException(422, '参数有误,请携带订阅地址发送'); + throw new ApiException('参数有误,请携带订阅地址发送', 422); } $subscribeUrl = $message->args[0]; $subscribeUrl = parse_url($subscribeUrl); parse_str($subscribeUrl['query'], $query); $token = $query['token']; if (!$token) { - throw new ApiException(500, '订阅地址无效'); + throw new ApiException('订阅地址无效'); } $user = User::where('token', $token)->first(); if (!$user) { - throw new ApiException(500, '用户不存在'); + throw new ApiException('用户不存在'); } if ($user->telegram_id) { - throw new ApiException(500, '该账号已经绑定了Telegram账号'); + throw new ApiException('该账号已经绑定了Telegram账号'); } $user->telegram_id = $message->chat_id; if (!$user->save()) { - throw new ApiException(500, '设置失败'); + throw new ApiException('设置失败'); } $telegramService = $this->telegramService; $telegramService->sendMessage($message->chat_id, '绑定成功'); diff --git a/app/Plugins/Telegram/Commands/ReplyTicket.php b/app/Plugins/Telegram/Commands/ReplyTicket.php index 0468ac5..76383bf 100644 --- a/app/Plugins/Telegram/Commands/ReplyTicket.php +++ b/app/Plugins/Telegram/Commands/ReplyTicket.php @@ -21,7 +21,7 @@ class ReplyTicket extends Telegram { { $user = User::where('telegram_id', $msg->chat_id)->first(); if (!$user) { - throw new ApiException(500, '用户不存在'); + throw new ApiException('用户不存在'); } if (!$msg->text) return; if (!($user->is_admin || $user->is_staff)) return; diff --git a/app/Plugins/Telegram/Commands/UnBind.php b/app/Plugins/Telegram/Commands/UnBind.php index 65fbf82..ebd9325 100644 --- a/app/Plugins/Telegram/Commands/UnBind.php +++ b/app/Plugins/Telegram/Commands/UnBind.php @@ -20,7 +20,7 @@ class UnBind extends Telegram { } $user->telegram_id = NULL; if (!$user->save()) { - throw new ApiException(500, '解绑失败'); + throw new ApiException('解绑失败'); } $telegramService->sendMessage($message->chat_id, '解绑成功', 'markdown'); } diff --git a/app/Services/CouponService.php b/app/Services/CouponService.php index 8e87a76..42829d5 100644 --- a/app/Services/CouponService.php +++ b/app/Services/CouponService.php @@ -86,30 +86,30 @@ class CouponService public function check() { if (!$this->coupon || !$this->coupon->show) { - throw new ApiException(500, __('Invalid coupon')); + throw new ApiException(__('Invalid coupon')); } if ($this->coupon->limit_use <= 0 && $this->coupon->limit_use !== NULL) { - throw new ApiException(500, __('This coupon is no longer available')); + throw new ApiException(__('This coupon is no longer available')); } if (time() < $this->coupon->started_at) { - throw new ApiException(500, __('This coupon has not yet started')); + throw new ApiException(__('This coupon has not yet started')); } if (time() > $this->coupon->ended_at) { - throw new ApiException(500, __('This coupon has expired')); + throw new ApiException(__('This coupon has expired')); } if ($this->coupon->limit_plan_ids && $this->planId) { if (!in_array($this->planId, $this->coupon->limit_plan_ids)) { - throw new ApiException(500, __('The coupon code cannot be used for this subscription')); + throw new ApiException(__('The coupon code cannot be used for this subscription')); } } if ($this->coupon->limit_period && $this->period) { if (!in_array($this->period, $this->coupon->limit_period)) { - throw new ApiException(500, __('The coupon code cannot be used for this period')); + throw new ApiException(__('The coupon code cannot be used for this period')); } } if ($this->coupon->limit_use_with_user !== NULL && $this->userId) { if (!$this->checkLimitUseWithUser()) { - throw new ApiException(500, __('The coupon can only be used :limit_use_with_user per person', [ + throw new ApiException(__('The coupon can only be used :limit_use_with_user per person', [ 'limit_use_with_user' => $this->coupon->limit_use_with_user ])); } diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php index b541492..615e1ec 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -79,7 +79,7 @@ class OrderService }catch(\Exception $e){ DB::rollBack(); \Log::error($e); - throw new ApiException(500, '开通失败'); + throw new ApiException('开通失败'); } } @@ -90,7 +90,7 @@ class OrderService if ($order->period === 'reset_price') { $order->type = 4; } else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id && ($user->expired_at > time() || $user->expired_at === NULL)) { - if (!(int)admin_setting('plan_change_enable', 1)) throw new ApiException(500, '目前不允许更改订阅,请联系客服或提交工单操作'); + if (!(int)admin_setting('plan_change_enable', 1)) throw new ApiException('目前不允许更改订阅,请联系客服或提交工单操作'); $order->type = 3; if ((int)admin_setting('surplus_enable', 1)) $this->getSurplusValue($user, $order); if ($order->surplus_amount >= $order->total_amount) { diff --git a/app/Services/PaymentService.php b/app/Services/PaymentService.php index 0fb18a8..48a0fd7 100644 --- a/app/Services/PaymentService.php +++ b/app/Services/PaymentService.php @@ -17,7 +17,7 @@ class PaymentService { $this->method = $method; $this->class = '\\App\\Payments\\' . $this->method; - if (!class_exists($this->class)) throw new ApiException(500, 'gate is not found'); + if (!class_exists($this->class)) throw new ApiException('gate is not found'); if ($id) $payment = Payment::find($id)->toArray(); if ($uuid) $payment = Payment::where('uuid', $uuid)->first()->toArray(); $this->config = []; @@ -33,7 +33,7 @@ class PaymentService public function notify($params) { - if (!$this->config['enable']) throw new ApiException(500, 'gate is not enable'); + if (!$this->config['enable']) throw new ApiException('gate is not enable'); return $this->payment->notify($params); } diff --git a/app/Services/TelegramService.php b/app/Services/TelegramService.php index 60ce00f..0bbdf03 100644 --- a/app/Services/TelegramService.php +++ b/app/Services/TelegramService.php @@ -60,9 +60,9 @@ class TelegramService { $curl->get($this->api . $method . '?' . http_build_query($params)); $response = $curl->response; $curl->close(); - if (!isset($response->ok)) throw new ApiException(500, '请求失败'); + if (!isset($response->ok)) throw new ApiException('请求失败'); if (!$response->ok) { - throw new ApiException(500, '来自TG的错误:' . $response->description); + throw new ApiException('来自TG的错误:' . $response->description); } return $response; } diff --git a/app/Services/TicketService.php b/app/Services/TicketService.php index a6d1659..2ee5b5a 100644 --- a/app/Services/TicketService.php +++ b/app/Services/TicketService.php @@ -41,7 +41,7 @@ class TicketService { $ticket = Ticket::where('id', $ticketId) ->first(); if (!$ticket) { - throw new ApiException(500, '工单不存在'); + throw new ApiException('工单不存在'); } $ticket->status = 0; try{ @@ -57,7 +57,7 @@ class TicketService { $ticket->reply_status = 1; } if (!$ticketMessage || !$ticket->save()) { - throw new ApiException(500, '工单回复失败'); + throw new ApiException('工单回复失败'); } DB::commit(); }catch(\Exception $e){