diff --git a/app/Exceptions/ApiException.php b/app/Exceptions/ApiException.php new file mode 100644 index 0000000..4ef4283 --- /dev/null +++ b/app/Exceptions/ApiException.php @@ -0,0 +1,23 @@ +message = $message; + $this->code = $code; + $this->errors = $errors; + } + public function errors(){ + return $this->errors; + } + +} diff --git a/app/Exceptions/BusinessException.php b/app/Exceptions/BusinessException.php new file mode 100644 index 0000000..2079495 --- /dev/null +++ b/app/Exceptions/BusinessException.php @@ -0,0 +1,19 @@ +fail([500, '主题渲染失败。如更新主题,参数可能发生变化请重新配置主题后再试。']); + } + // ApiException主动抛出错误 + if ($exception instanceof ApiException) { + $code = $exception->getCode(); + $message = $exception->getMessage(); + $errors = $exception->errors(); + return $this->fail([$code, $message],null,$errors); } return parent::render($request, $exception); } @@ -63,7 +73,6 @@ class Handler extends ExceptionHandler protected function convertExceptionToArray(Throwable $e) { - Log::channel("daily")->info($e); return config('app.debug') ? [ 'message' => $e->getMessage(), 'exception' => get_class($e), diff --git a/app/Helpers/ApiResponse.php b/app/Helpers/ApiResponse.php new file mode 100644 index 0000000..9561103 --- /dev/null +++ b/app/Helpers/ApiResponse.php @@ -0,0 +1,104 @@ +jsonResponse('success', $codeResponse, $data, null); + } + + /** + * 失败 + * @param array $codeResponse + * @param mixed $data + * @param mixed $error + * @return JsonResponse + */ + public function fail($codeResponse=ResponseEnum::HTTP_ERROR, $data = null, $error=null): JsonResponse + { + return $this->jsonResponse('fail', $codeResponse, $data, $error); + } + + /** + * json响应 + * @param $status + * @param $codeResponse + * @param $data + * @param $error + * @return JsonResponse + */ + private function jsonResponse($status, $codeResponse, $data, $error): JsonResponse + { + list($code, $message) = $codeResponse; + return response() + ->json([ + 'status' => $status, + 'code' => $code, + 'message' => $message, + 'data' => $data ?? null, + 'error' => $error, + ],(int)substr(((string) $code),0,3)); + } + + /** + * 成功分页返回 + * @param $page + * @return JsonResponse + */ + protected function successPaginate($page): JsonResponse + { + return $this->success($this->paginate($page)); + } + + private function paginate($page) + { + if ($page instanceof LengthAwarePaginator){ + return [ + 'total' => $page->total(), + 'page' => $page->currentPage(), + 'limit' => $page->perPage(), + 'pages' => $page->lastPage(), + 'list' => $page->items() + ]; + } + if ($page instanceof Collection){ + $page = $page->toArray(); + } + if (!is_array($page) && !is_object($page)){ + return $page; + } + $total = count($page); + return [ + 'total' => $total, //数据总数 + 'page' => 1, // 当前页码 + 'limit' => $total, // 每页的数据条数 + 'pages' => 1, // 最后一页的页码 + 'list' => $page // 数据 + ]; + } + + /** + * 业务异常返回 + * @param array $codeResponse + * @param string $info + * @throws BusinessException + */ + public function throwBusinessException(array $codeResponse=ResponseEnum::HTTP_ERROR, string $info = '') + { + throw new BusinessException($codeResponse, $info); + } +} \ No newline at end of file diff --git a/app/Helpers/ResponseEnum.php b/app/Helpers/ResponseEnum.php new file mode 100644 index 0000000..f749ad3 --- /dev/null +++ b/app/Helpers/ResponseEnum.php @@ -0,0 +1,81 @@ +input('id'))) { - abort(500, '参数有误'); + throw new ApiException(422, '参数有误'); } $coupon = Coupon::find($request->input('id')); if (!$coupon) { - abort(500, '优惠券不存在'); + throw new ApiException(500, '优惠券不存在'); } - $coupon->show = $coupon->show ? 0 : 1; + $coupon->show = !$coupon->show; if (!$coupon->save()) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -60,13 +61,13 @@ class CouponController extends Controller $params['code'] = Helper::randomChar(8); } if (!Coupon::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } } else { try { Coupon::find($request->input('id'))->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } @@ -98,7 +99,7 @@ class CouponController extends Controller return $item; }, $coupons))) { DB::rollBack(); - abort(500, '生成失败'); + throw new ApiException(500, '生成失败'); } DB::commit(); $data = "名称,类型,金额或比例,开始时间,结束时间,可用次数,可用于订阅,券码,生成时间\r\n"; @@ -118,14 +119,14 @@ class CouponController extends Controller public function drop(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数有误'); + throw new ApiException(422, '参数有误'); } $coupon = Coupon::find($request->input('id')); if (!$coupon) { - abort(500, '优惠券不存在'); + throw new ApiException(500, '优惠券不存在'); } if (!$coupon->delete()) { - abort(500, '删除失败'); + throw new ApiException(500, '删除失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/KnowledgeController.php b/app/Http/Controllers/V1/Admin/KnowledgeController.php index 20932a9..db4f38b 100644 --- a/app/Http/Controllers/V1/Admin/KnowledgeController.php +++ b/app/Http/Controllers/V1/Admin/KnowledgeController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\KnowledgeSave; use App\Http\Requests\Admin\KnowledgeSort; @@ -15,7 +16,7 @@ class KnowledgeController extends Controller { if ($request->input('id')) { $knowledge = Knowledge::find($request->input('id'))->toArray(); - if (!$knowledge) abort(500, '知识不存在'); + if (!$knowledge) throw new ApiException(500, '知识不存在'); return response([ 'data' => $knowledge ]); @@ -40,13 +41,13 @@ class KnowledgeController extends Controller if (!$request->input('id')) { if (!Knowledge::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } } else { try { Knowledge::find($request->input('id'))->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } @@ -58,15 +59,15 @@ class KnowledgeController extends Controller public function show(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数有误'); + throw new ApiException(422, '参数有误'); } $knowledge = Knowledge::find($request->input('id')); if (!$knowledge) { - abort(500, '知识不存在'); + throw new ApiException(500, '知识不存在'); } $knowledge->show = $knowledge->show ? 0 : 1; if (!$knowledge->save()) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -85,7 +86,7 @@ class KnowledgeController extends Controller } } catch (\Exception $e) { DB::rollBack(); - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } DB::commit(); return response([ @@ -96,14 +97,14 @@ class KnowledgeController extends Controller public function drop(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数有误'); + throw new ApiException(422, '参数有误'); } $knowledge = Knowledge::find($request->input('id')); if (!$knowledge) { - abort(500, '知识不存在'); + throw new ApiException(500, '知识不存在'); } if (!$knowledge->delete()) { - abort(500, '删除失败'); + throw new ApiException(500, '删除失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/NoticeController.php b/app/Http/Controllers/V1/Admin/NoticeController.php index ec43341..511973b 100644 --- a/app/Http/Controllers/V1/Admin/NoticeController.php +++ b/app/Http/Controllers/V1/Admin/NoticeController.php @@ -2,11 +2,11 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\NoticeSave; use App\Models\Notice; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; class NoticeController extends Controller { @@ -27,13 +27,13 @@ class NoticeController extends Controller ]); if (!$request->input('id')) { if (!Notice::create($data)) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } else { try { Notice::find($request->input('id'))->update($data); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } return response([ @@ -46,15 +46,15 @@ class NoticeController extends Controller public function show(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数有误'); + throw new ApiException(422, '参数有误'); } $notice = Notice::find($request->input('id')); if (!$notice) { - abort(500, '公告不存在'); + throw new ApiException(500, '公告不存在'); } $notice->show = $notice->show ? 0 : 1; if (!$notice->save()) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -65,14 +65,14 @@ class NoticeController extends Controller public function drop(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } $notice = Notice::find($request->input('id')); if (!$notice) { - abort(500, '公告不存在'); + throw new ApiException(500, '公告不存在'); } if (!$notice->delete()) { - abort(500, '删除失败'); + throw new ApiException(500, '删除失败'); } return response([ 'data' => true diff --git a/app/Http/Controllers/V1/Admin/OrderController.php b/app/Http/Controllers/V1/Admin/OrderController.php index 16920d7..ecdf394 100644 --- a/app/Http/Controllers/V1/Admin/OrderController.php +++ b/app/Http/Controllers/V1/Admin/OrderController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\OrderAssign; use App\Http\Requests\Admin\OrderFetch; @@ -40,7 +41,7 @@ class OrderController extends Controller public function detail(Request $request) { $order = Order::find($request->input('id')); - if (!$order) abort(500, '订单不存在'); + if (!$order) throw new ApiException(500, '订单不存在'); $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(); @@ -83,13 +84,13 @@ class OrderController extends Controller $order = Order::where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - abort(500, '订单不存在'); + throw new ApiException(500, '订单不存在'); } - if ($order->status !== 0) abort(500, '只能对待支付的订单进行操作'); + if ($order->status !== 0) throw new ApiException(500, '只能对待支付的订单进行操作'); $orderService = new OrderService($order); if (!$orderService->paid('manual_operation')) { - abort(500, '更新失败'); + throw new ApiException(500, '更新失败'); } return response([ 'data' => true @@ -101,13 +102,13 @@ class OrderController extends Controller $order = Order::where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - abort(500, '订单不存在'); + throw new ApiException(500, '订单不存在'); } - if ($order->status !== 0) abort(500, '只能对待支付的订单进行操作'); + if ($order->status !== 0) throw new ApiException(500, '只能对待支付的订单进行操作'); $orderService = new OrderService($order); if (!$orderService->cancel()) { - abort(500, '更新失败'); + throw new ApiException(500, '更新失败'); } return response([ 'data' => true @@ -123,13 +124,13 @@ class OrderController extends Controller $order = Order::where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - abort(500, '订单不存在'); + throw new ApiException(500, '订单不存在'); } try { $order->update($params); } catch (\Exception $e) { - abort(500, '更新失败'); + throw new ApiException(500, '更新失败'); } return response([ @@ -143,16 +144,16 @@ class OrderController extends Controller $user = User::where('email', $request->input('email'))->first(); if (!$user) { - abort(500, '该用户不存在'); + throw new ApiException(500, '该用户不存在'); } if (!$plan) { - abort(500, '该订阅不存在'); + throw new ApiException(500, '该订阅不存在'); } $userService = new UserService(); if ($userService->isNotCompleteOrderByUserId($user->id)) { - abort(500, '该用户还有待支付的订单,无法分配'); + throw new ApiException(500, '该用户还有待支付的订单,无法分配'); } DB::beginTransaction(); @@ -178,7 +179,7 @@ class OrderController extends Controller if (!$order->save()) { DB::rollback(); - abort(500, '订单创建失败'); + throw new ApiException(500, '订单创建失败'); } DB::commit(); diff --git a/app/Http/Controllers/V1/Admin/PaymentController.php b/app/Http/Controllers/V1/Admin/PaymentController.php index 32fd5ee..187bd73 100644 --- a/app/Http/Controllers/V1/Admin/PaymentController.php +++ b/app/Http/Controllers/V1/Admin/PaymentController.php @@ -2,8 +2,8 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; -use App\Http\Requests\Admin\PaymentSave; use App\Models\Payment; use App\Services\PaymentService; use App\Utils\Helper; @@ -50,9 +50,9 @@ class PaymentController extends Controller public function show(Request $request) { $payment = Payment::find($request->input('id')); - if (!$payment) abort(500, '支付方式不存在'); + if (!$payment) throw new ApiException(500, '支付方式不存在'); $payment->enable = !$payment->enable; - if (!$payment->save()) abort(500, '保存失败'); + if (!$payment->save()) throw new ApiException(500, '保存失败'); return response([ 'data' => true ]); @@ -61,7 +61,7 @@ class PaymentController extends Controller public function save(Request $request) { if (!admin_setting('app_url')) { - abort(500, '请在站点配置中配置站点地址'); + throw new ApiException(500, '请在站点配置中配置站点地址'); } $params = $request->validate([ 'name' => 'required', @@ -81,11 +81,11 @@ class PaymentController extends Controller ]); if ($request->input('id')) { $payment = Payment::find($request->input('id')); - if (!$payment) abort(500, '支付方式不存在'); + if (!$payment) throw new ApiException(500, '支付方式不存在'); try { $payment->update($params); } catch (\Exception $e) { - abort(500, $e->getMessage()); + throw new ApiException(500, $e->getMessage()); } return response([ 'data' => true @@ -93,7 +93,7 @@ class PaymentController extends Controller } $params['uuid'] = Helper::randomChar(8); if (!Payment::create($params)) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -103,7 +103,7 @@ class PaymentController extends Controller public function drop(Request $request) { $payment = Payment::find($request->input('id')); - if (!$payment) abort(500, '支付方式不存在'); + if (!$payment) throw new ApiException(500, '支付方式不存在'); return response([ 'data' => $payment->delete() ]); @@ -122,7 +122,7 @@ class PaymentController extends Controller foreach ($request->input('ids') as $k => $v) { if (!Payment::find($v)->update(['sort' => $k + 1])) { DB::rollBack(); - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } DB::commit(); diff --git a/app/Http/Controllers/V1/Admin/PlanController.php b/app/Http/Controllers/V1/Admin/PlanController.php index 9d39d68..a3758e7 100755 --- a/app/Http/Controllers/V1/Admin/PlanController.php +++ b/app/Http/Controllers/V1/Admin/PlanController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\PlanSave; use App\Http\Requests\Admin\PlanSort; @@ -36,7 +37,7 @@ class PlanController extends Controller if ($request->input('id')) { $plan = Plan::find($request->input('id')); if (!$plan) { - abort(500, '该订阅不存在'); + throw new ApiException(500, '该订阅不存在'); } DB::beginTransaction(); // update user group id and transfer @@ -51,7 +52,7 @@ class PlanController extends Controller $plan->update($params); } catch (\Exception $e) { DB::rollBack(); - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } DB::commit(); return response([ @@ -59,7 +60,7 @@ class PlanController extends Controller ]); } if (!Plan::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } return response([ 'data' => true @@ -69,15 +70,15 @@ class PlanController extends Controller public function drop(Request $request) { if (Order::where('plan_id', $request->input('id'))->first()) { - abort(500, '该订阅下存在订单无法删除'); + throw new ApiException(500, '该订阅下存在订单无法删除'); } if (User::where('plan_id', $request->input('id'))->first()) { - abort(500, '该订阅下存在用户无法删除'); + throw new ApiException(500, '该订阅下存在用户无法删除'); } if ($request->input('id')) { $plan = Plan::find($request->input('id')); if (!$plan) { - abort(500, '该订阅ID不存在'); + throw new ApiException(500, '该订阅ID不存在'); } } return response([ @@ -94,13 +95,13 @@ class PlanController extends Controller $plan = Plan::find($request->input('id')); if (!$plan) { - abort(500, '该订阅不存在'); + throw new ApiException(500, '该订阅不存在'); } try { $plan->update($updateData); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -114,7 +115,7 @@ class PlanController extends Controller foreach ($request->input('plan_ids') as $k => $v) { if (!Plan::find($v)->update(['sort' => $k + 1])) { DB::rollBack(); - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } DB::commit(); diff --git a/app/Http/Controllers/V1/Admin/Server/GroupController.php b/app/Http/Controllers/V1/Admin/Server/GroupController.php index e7f7d99..fc3b515 100644 --- a/app/Http/Controllers/V1/Admin/Server/GroupController.php +++ b/app/Http/Controllers/V1/Admin/Server/GroupController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Plan; use App\Models\ServerGroup; @@ -39,7 +40,7 @@ class GroupController extends Controller public function save(Request $request) { if (empty($request->input('name'))) { - abort(500, '组名不能为空'); + throw new ApiException(500, '组名不能为空'); } if ($request->input('id')) { @@ -59,22 +60,22 @@ class GroupController extends Controller if ($request->input('id')) { $serverGroup = ServerGroup::find($request->input('id')); if (!$serverGroup) { - abort(500, '组不存在'); + throw new ApiException(500, '组不存在'); } } $servers = ServerVmess::all(); foreach ($servers as $server) { if (in_array($request->input('id'), $server->group_id)) { - abort(500, '该组已被节点所使用,无法删除'); + throw new ApiException(500, '该组已被节点所使用,无法删除'); } } if (Plan::where('group_id', $request->input('id'))->first()) { - abort(500, '该组已被订阅所使用,无法删除'); + throw new ApiException(500, '该组已被订阅所使用,无法删除'); } if (User::where('group_id', $request->input('id'))->first()) { - abort(500, '该组已被用户所使用,无法删除'); + throw new ApiException(500, '该组已被用户所使用,无法删除'); } return response([ 'data' => $serverGroup->delete() diff --git a/app/Http/Controllers/V1/Admin/Server/HysteriaController.php b/app/Http/Controllers/V1/Admin/Server/HysteriaController.php index caaf925..1a6e83d 100644 --- a/app/Http/Controllers/V1/Admin/Server/HysteriaController.php +++ b/app/Http/Controllers/V1/Admin/Server/HysteriaController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\ServerHysteria; use Illuminate\Http\Request; @@ -44,12 +45,12 @@ class HysteriaController extends Controller if ($request->input('id')) { $server = ServerHysteria::find($request->input('id')); if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -57,7 +58,7 @@ class HysteriaController extends Controller } if (!ServerHysteria::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } return response([ @@ -70,7 +71,7 @@ class HysteriaController extends Controller if ($request->input('id')) { $server = ServerHysteria::find($request->input('id')); if (!$server) { - abort(500, '节点ID不存在'); + throw new ApiException(500, '节点ID不存在'); } } return response([ @@ -92,12 +93,12 @@ class HysteriaController extends Controller $server = ServerHysteria::find($request->input('id')); if (!$server) { - abort(500, '该服务器不存在'); + throw new ApiException(500, '该服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -110,10 +111,10 @@ class HysteriaController extends Controller $server = ServerHysteria::find($request->input('id')); $server->show = 0; if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } if (!ServerHysteria::create($server->toArray())) { - abort(500, '复制失败'); + throw new ApiException(500, '复制失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/Server/ManageController.php b/app/Http/Controllers/V1/Admin/Server/ManageController.php index 9bcc932..367848e 100644 --- a/app/Http/Controllers/V1/Admin/Server/ManageController.php +++ b/app/Http/Controllers/V1/Admin/Server/ManageController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Services\ServerService; use Illuminate\Http\Request; @@ -33,7 +34,7 @@ class ManageController extends Controller foreach($v as $id => $sort) { if (!$model::find($id)->update(['sort' => $sort])) { DB::rollBack(); - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } } diff --git a/app/Http/Controllers/V1/Admin/Server/RouteController.php b/app/Http/Controllers/V1/Admin/Server/RouteController.php index 6326d95..1559ec9 100644 --- a/app/Http/Controllers/V1/Admin/Server/RouteController.php +++ b/app/Http/Controllers/V1/Admin/Server/RouteController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\ServerRoute; use Illuminate\Http\Request; @@ -47,10 +48,10 @@ class RouteController extends Controller 'data' => true ]; } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } - if (!ServerRoute::create($params)) abort(500, '创建失败'); + if (!ServerRoute::create($params)) throw new ApiException(500, '创建失败'); return [ 'data' => true ]; @@ -59,8 +60,8 @@ class RouteController extends Controller public function drop(Request $request) { $route = ServerRoute::find($request->input('id')); - if (!$route) abort(500, '路由不存在'); - if (!$route->delete()) abort(500, '删除失败'); + if (!$route) throw new ApiException(500, '路由不存在'); + if (!$route->delete()) throw new ApiException(500, '删除失败'); return [ 'data' => true ]; diff --git a/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php b/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php index fa7421d..25999ce 100644 --- a/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php +++ b/app/Http/Controllers/V1/Admin/Server/ShadowsocksController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\ServerShadowsocksSave; use App\Http\Requests\Admin\ServerShadowsocksUpdate; @@ -16,12 +17,12 @@ class ShadowsocksController extends Controller if ($request->input('id')) { $server = ServerShadowsocks::find($request->input('id')); if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -29,7 +30,7 @@ class ShadowsocksController extends Controller } if (!ServerShadowsocks::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } return response([ @@ -42,7 +43,7 @@ class ShadowsocksController extends Controller if ($request->input('id')) { $server = ServerShadowsocks::find($request->input('id')); if (!$server) { - abort(500, '节点ID不存在'); + throw new ApiException(500, '节点ID不存在'); } } return response([ @@ -59,12 +60,12 @@ class ShadowsocksController extends Controller $server = ServerShadowsocks::find($request->input('id')); if (!$server) { - abort(500, '该服务器不存在'); + throw new ApiException(500, '该服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -77,10 +78,10 @@ class ShadowsocksController extends Controller $server = ServerShadowsocks::find($request->input('id')); $server->show = 0; if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } if (!ServerShadowsocks::create($server->toArray())) { - abort(500, '复制失败'); + throw new ApiException(500, '复制失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/Server/TrojanController.php b/app/Http/Controllers/V1/Admin/Server/TrojanController.php index a159794..71e7bb3 100644 --- a/app/Http/Controllers/V1/Admin/Server/TrojanController.php +++ b/app/Http/Controllers/V1/Admin/Server/TrojanController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\ServerTrojanSave; use App\Http\Requests\Admin\ServerTrojanUpdate; @@ -17,12 +18,12 @@ class TrojanController extends Controller if ($request->input('id')) { $server = ServerTrojan::find($request->input('id')); if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -30,7 +31,7 @@ class TrojanController extends Controller } if (!ServerTrojan::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } return response([ @@ -43,7 +44,7 @@ class TrojanController extends Controller if ($request->input('id')) { $server = ServerTrojan::find($request->input('id')); if (!$server) { - abort(500, '节点ID不存在'); + throw new ApiException(500, '节点ID不存在'); } } return response([ @@ -60,12 +61,12 @@ class TrojanController extends Controller $server = ServerTrojan::find($request->input('id')); if (!$server) { - abort(500, '该服务器不存在'); + throw new ApiException(500, '该服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -78,10 +79,10 @@ class TrojanController extends Controller $server = ServerTrojan::find($request->input('id')); $server->show = 0; if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } if (!ServerTrojan::create($server->toArray())) { - abort(500, '复制失败'); + throw new ApiException(500, '复制失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/Server/VlessController.php b/app/Http/Controllers/V1/Admin/Server/VlessController.php index 3bf265e..c2eebfc 100644 --- a/app/Http/Controllers/V1/Admin/Server/VlessController.php +++ b/app/Http/Controllers/V1/Admin/Server/VlessController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\ServerVless; use Illuminate\Http\Request; @@ -61,12 +62,12 @@ class VlessController extends Controller if ($request->input('id')) { $server = ServerVless::find($request->input('id')); if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -74,7 +75,7 @@ class VlessController extends Controller } if (!ServerVless::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } return response([ @@ -87,7 +88,7 @@ class VlessController extends Controller if ($request->input('id')) { $server = ServerVless::find($request->input('id')); if (!$server) { - abort(500, '节点ID不存在'); + throw new ApiException(500, '节点ID不存在'); } } return response([ @@ -104,12 +105,12 @@ class VlessController extends Controller $server = ServerVless::find($request->input('id')); if (!$server) { - abort(500, '该服务器不存在'); + throw new ApiException(500, '该服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -122,10 +123,10 @@ class VlessController extends Controller $server = ServerVless::find($request->input('id')); $server->show = 0; if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } if (!ServerVless::create($server->toArray())) { - abort(500, '复制失败'); + throw new ApiException(500, '复制失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/Server/VmessController.php b/app/Http/Controllers/V1/Admin/Server/VmessController.php index ee337df..b827aac 100644 --- a/app/Http/Controllers/V1/Admin/Server/VmessController.php +++ b/app/Http/Controllers/V1/Admin/Server/VmessController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\ServerVmessSave; use App\Http\Requests\Admin\ServerVmessUpdate; @@ -17,12 +18,12 @@ class VmessController extends Controller if ($request->input('id')) { $server = ServerVmess::find($request->input('id')); if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -30,7 +31,7 @@ class VmessController extends Controller } if (!ServerVmess::create($params)) { - abort(500, '创建失败'); + throw new ApiException(500, '创建失败'); } return response([ @@ -43,7 +44,7 @@ class VmessController extends Controller if ($request->input('id')) { $server = ServerVmess::find($request->input('id')); if (!$server) { - abort(500, '节点ID不存在'); + throw new ApiException(500, '节点ID不存在'); } } return response([ @@ -60,12 +61,12 @@ class VmessController extends Controller $server = ServerVmess::find($request->input('id')); if (!$server) { - abort(500, '该服务器不存在'); + throw new ApiException(500, '该服务器不存在'); } try { $server->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ @@ -78,10 +79,10 @@ class VmessController extends Controller $server = ServerVmess::find($request->input('id')); $server->show = 0; if (!$server) { - abort(500, '服务器不存在'); + throw new ApiException(500, '服务器不存在'); } if (!ServerVmess::create($server->toArray())) { - abort(500, '复制失败'); + throw new ApiException(500, '复制失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/ThemeController.php b/app/Http/Controllers/V1/Admin/ThemeController.php index 03e0c1a..c6db848 100644 --- a/app/Http/Controllers/V1/Admin/ThemeController.php +++ b/app/Http/Controllers/V1/Admin/ThemeController.php @@ -2,10 +2,10 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Services\ThemeService; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; class ThemeController extends Controller @@ -59,11 +59,11 @@ class ThemeController extends Controller 'config' => 'required' ]); $payload['config'] = json_decode(base64_decode($payload['config']), true); - if (!$payload['config'] || !is_array($payload['config'])) abort(500, '参数有误'); + if (!$payload['config'] || !is_array($payload['config'])) throw new ApiException(422, '参数有误'); $themeConfigFile = public_path("theme/{$payload['name']}/config.json"); - if (!File::exists($themeConfigFile)) abort(500, '主题不存在'); + if (!File::exists($themeConfigFile)) throw new ApiException(500, '主题不存在'); $themeConfig = json_decode(File::get($themeConfigFile), true); - if (!isset($themeConfig['configs']) || !is_array($themeConfig)) abort(500, '主题配置文件有误'); + if (!isset($themeConfig['configs']) || !is_array($themeConfig)) throw new ApiException(500, '主题配置文件有误'); $validateFields = array_column($themeConfig['configs'], 'field_name'); $config = []; foreach ($validateFields as $validateField) { @@ -77,7 +77,7 @@ class ThemeController extends Controller admin_setting(["theme_{$payload['name']}" => $config]); // sleep(2); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ diff --git a/app/Http/Controllers/V1/Admin/TicketController.php b/app/Http/Controllers/V1/Admin/TicketController.php index 531cb85..233f20a 100644 --- a/app/Http/Controllers/V1/Admin/TicketController.php +++ b/app/Http/Controllers/V1/Admin/TicketController.php @@ -2,14 +2,13 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Ticket; use App\Models\TicketMessage; use App\Models\User; use App\Services\TicketService; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; class TicketController extends Controller { @@ -19,7 +18,7 @@ class TicketController extends Controller $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - abort(500, '工单不存在'); + throw new ApiException(500, '工单不存在'); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); for ($i = 0; $i < count($ticket['message']); $i++) { @@ -58,10 +57,10 @@ class TicketController extends Controller public function reply(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } if (empty($request->input('message'))) { - abort(500, '消息不能为空'); + throw new ApiException(500, '消息不能为空'); } $ticketService = new TicketService(); $ticketService->replyByAdmin( @@ -77,16 +76,16 @@ class TicketController extends Controller public function close(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - abort(500, '工单不存在'); + throw new ApiException(500, '工单不存在'); } $ticket->status = 1; if (!$ticket->save()) { - abort(500, '关闭失败'); + throw new ApiException(500, '关闭失败'); } return response([ 'data' => true diff --git a/app/Http/Controllers/V1/Admin/UserController.php b/app/Http/Controllers/V1/Admin/UserController.php index c12e689..d6e3890 100644 --- a/app/Http/Controllers/V1/Admin/UserController.php +++ b/app/Http/Controllers/V1/Admin/UserController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Admin; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\UserFetch; use App\Http\Requests\Admin\UserGenerate; @@ -20,7 +21,7 @@ class UserController extends Controller public function resetSecret(Request $request) { $user = User::find($request->input('id')); - if (!$user) abort(500, '用户不存在'); + if (!$user) throw new ApiException(500, '用户不存在'); $user->token = Helper::guid(); $user->uuid = Helper::guid(true); return response([ @@ -85,7 +86,7 @@ class UserController extends Controller public function getUserInfoById(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } $user = User::find($request->input('id')); if ($user->invite_user_id) { @@ -101,10 +102,10 @@ class UserController extends Controller $params = $request->validated(); $user = User::find($request->input('id')); if (!$user) { - abort(500, '用户不存在'); + throw new ApiException(500, '用户不存在'); } if (User::where('email', $params['email'])->first() && $user->email !== $params['email']) { - abort(500, '邮箱已被使用'); + throw new ApiException(500, '邮箱已被使用'); } if (isset($params['password'])) { $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT); @@ -115,7 +116,7 @@ class UserController extends Controller if (isset($params['plan_id'])) { $plan = Plan::find($params['plan_id']); if (!$plan) { - abort(500, '订阅计划不存在'); + throw new ApiException(500, '订阅计划不存在'); } $params['group_id'] = $plan->group_id; } @@ -136,7 +137,7 @@ class UserController extends Controller try { $user->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -177,7 +178,7 @@ class UserController extends Controller if ($request->input('plan_id')) { $plan = Plan::find($request->input('plan_id')); if (!$plan) { - abort(500, '订阅计划不存在'); + throw new ApiException(500, '订阅计划不存在'); } } $user = [ @@ -190,11 +191,11 @@ class UserController extends Controller 'token' => Helper::guid() ]; if (User::where('email', $user['email'])->first()) { - abort(500, '邮箱已存在于系统中'); + throw new ApiException(500, '邮箱已存在于系统中'); } $user['password'] = password_hash($request->input('password') ?? $user['email'], PASSWORD_DEFAULT); if (!User::create($user)) { - abort(500, '生成失败'); + throw new ApiException(500, '生成失败'); } return response([ 'data' => true @@ -210,7 +211,7 @@ class UserController extends Controller if ($request->input('plan_id')) { $plan = Plan::find($request->input('plan_id')); if (!$plan) { - abort(500, '订阅计划不存在'); + throw new ApiException(500, '订阅计划不存在'); } } $users = []; @@ -232,7 +233,7 @@ class UserController extends Controller DB::beginTransaction(); if (!User::insert($users)) { DB::rollBack(); - abort(500, '生成失败'); + throw new ApiException(500, '生成失败'); } DB::commit(); $data = "账号,密码,过期时间,UUID,创建时间,订阅地址\r\n"; @@ -283,7 +284,7 @@ class UserController extends Controller 'banned' => 1 ]); } catch (\Exception $e) { - abort(500, '处理失败'); + throw new ApiException(500, '处理失败'); } return response([ diff --git a/app/Http/Controllers/V1/Guest/PaymentController.php b/app/Http/Controllers/V1/Guest/PaymentController.php index 868ee4f..a04ccea 100644 --- a/app/Http/Controllers/V1/Guest/PaymentController.php +++ b/app/Http/Controllers/V1/Guest/PaymentController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Guest; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Order; use App\Services\OrderService; @@ -16,13 +17,13 @@ class PaymentController extends Controller try { $paymentService = new PaymentService($method, null, $uuid); $verify = $paymentService->notify($request->input()); - if (!$verify) abort(500, 'verify error'); + if (!$verify) throw new ApiException(500, 'verify error'); if (!$this->handle($verify['trade_no'], $verify['callback_no'])) { - abort(500, 'handle error'); + throw new ApiException(500, 'handle error'); } return(isset($verify['custom_result']) ? $verify['custom_result'] : 'success'); } catch (\Exception $e) { - abort(500, 'fail'); + throw new ApiException(500, 'fail'); } } @@ -30,7 +31,7 @@ class PaymentController extends Controller { $order = Order::where('trade_no', $tradeNo)->first(); if (!$order) { - abort(500, 'order is not found'); + throw new ApiException(500, 'order is not found'); } if ($order->status !== 0) return true; $orderService = new OrderService($order); diff --git a/app/Http/Controllers/V1/Guest/TelegramController.php b/app/Http/Controllers/V1/Guest/TelegramController.php index 0e6896d..63be33a 100644 --- a/app/Http/Controllers/V1/Guest/TelegramController.php +++ b/app/Http/Controllers/V1/Guest/TelegramController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Guest; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Services\TelegramService; use Illuminate\Http\Request; @@ -15,7 +16,7 @@ class TelegramController extends Controller public function __construct(Request $request) { if ($request->input('access_token') !== md5(admin_setting('telegram_bot_token'))) { - abort(401); + throw new ApiException(401); } $this->telegramService = new TelegramService(); diff --git a/app/Http/Controllers/V1/Passport/AuthController.php b/app/Http/Controllers/V1/Passport/AuthController.php index ef50224..7434fe1 100644 --- a/app/Http/Controllers/V1/Passport/AuthController.php +++ b/app/Http/Controllers/V1/Passport/AuthController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Passport; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Passport\AuthForget; use App\Http\Requests\Passport\AuthLogin; @@ -23,7 +24,7 @@ class AuthController extends Controller public function loginWithMailLink(Request $request) { if (!(int)admin_setting('login_with_mail_link_enable')) { - abort(404); + throw new ApiException(404); } $params = $request->validate([ 'email' => 'required|email:strict', @@ -31,7 +32,7 @@ class AuthController extends Controller ]); if (Cache::get(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $params['email']))) { - abort(500, __('Sending frequently, please try again later')); + throw new ApiException(500, __('Sending frequently, please try again later')); } $user = User::where('email', $params['email'])->first(); @@ -78,7 +79,7 @@ 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)) { - abort(500, __('Register frequently, please try again after :minute minute', [ + throw new ApiException(500, __('Register frequently, please try again after :minute minute', [ 'minute' => admin_setting('register_limit_expire', 60) ])); } @@ -87,7 +88,7 @@ class AuthController extends Controller $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); if (!$recaptchaResp->isSuccess()) { - abort(500, __('Invalid code is incorrect')); + throw new ApiException(500, __('Invalid code is incorrect')); } } if ((int)admin_setting('email_whitelist_enable', 0)) { @@ -95,36 +96,36 @@ class AuthController extends Controller $request->input('email'), admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT)) ) { - abort(500, __('Email suffix is not in the Whitelist')); + throw new ApiException(500, __('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) { - abort(500, __('Gmail alias is not supported')); + throw new ApiException(500, __('Gmail alias is not supported')); } } if ((int)admin_setting('stop_register', 0)) { - abort(500, __('Registration has closed')); + throw new ApiException(500, __('Registration has closed')); } if ((int)admin_setting('invite_force', 0)) { if (empty($request->input('invite_code'))) { - abort(500, __('You must use the invitation code to register')); + throw new ApiException(500, __('You must use the invitation code to register')); } } if ((int)admin_setting('email_verify', 0)) { if (empty($request->input('email_code'))) { - abort(500, __('Email verification code cannot be empty')); + throw new ApiException(500, __('Email verification code cannot be empty')); } if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { - abort(500, __('Incorrect email verification code')); + throw new ApiException(500, __('Incorrect email verification code')); } } $email = $request->input('email'); $password = $request->input('password'); $exist = User::where('email', $email)->first(); if ($exist) { - abort(500, __('Email already exists')); + throw new ApiException(500, __('Email already exists')); } $user = new User(); $user->email = $email; @@ -140,7 +141,7 @@ class AuthController extends Controller ->first(); if (!$inviteCode) { if ((int)admin_setting('invite_force', 0)) { - abort(500, __('Invalid invitation code')); + throw new ApiException(500, __('Invalid invitation code')); } } else { $user->invite_user_id = $inviteCode->user_id ? $inviteCode->user_id : null; @@ -164,7 +165,7 @@ class AuthController extends Controller } if (!$user->save()) { - abort(500, __('Register failed')); + throw new ApiException(500, __('Register failed')); } if ((int)admin_setting('email_verify', 0)) { Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))); @@ -196,7 +197,7 @@ 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)) { - abort(500, __('There are too many password errors, please try again after :minute minutes.', [ + throw new ApiException(500, __('There are too many password errors, please try again after :minute minutes.', [ 'minute' => admin_setting('password_limit_expire', 60) ])); } @@ -204,7 +205,7 @@ class AuthController extends Controller $user = User::where('email', $email)->first(); if (!$user) { - abort(500, __('Incorrect email or password')); + throw new ApiException(500, __('Incorrect email or password')); } if (!Helper::multiPasswordVerify( $user->password_algo, @@ -219,11 +220,11 @@ class AuthController extends Controller 60 * (int)admin_setting('password_limit_expire', 60) ); } - abort(500, __('Incorrect email or password')); + throw new ApiException(500, __('Incorrect email or password')); } if ($user->banned) { - abort(500, __('Your account has been suspended')); + throw new ApiException(500, __('Your account has been suspended')); } $authService = new AuthService($user); @@ -248,14 +249,14 @@ class AuthController extends Controller $key = CacheKey::get('TEMP_TOKEN', $request->input('verify')); $userId = Cache::get($key); if (!$userId) { - abort(500, __('Token error')); + throw new ApiException(500, __('Token error')); } $user = User::find($userId); if (!$user) { - abort(500, __('The user does not ')); + throw new ApiException(500, __('The user does not ')); } if ($user->banned) { - abort(500, __('Your account has been suspended')); + throw new ApiException(500, __('Your account has been suspended')); } Cache::forget($key); $authService = new AuthService($user); @@ -268,10 +269,10 @@ class AuthController extends Controller public function getQuickLoginUrl(Request $request) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) abort(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); $user = AuthService::decryptAuthData($authorization); - if (!$user) abort(403, '未登录或登陆已过期'); + if (!$user) throw new ApiException(403, '未登录或登陆已过期'); $code = Helper::guid(); $key = CacheKey::get('TEMP_TOKEN', $code); @@ -291,20 +292,20 @@ class AuthController extends Controller { $forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $request->input('email')); $forgetRequestLimit = (int)Cache::get($forgetRequestLimitKey); - if ($forgetRequestLimit >= 3) abort(500, __('Reset failed, Please try again later')); + if ($forgetRequestLimit >= 3) throw new ApiException(500, __('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); - abort(500, __('Incorrect email verification code')); + throw new ApiException(500, __('Incorrect email verification code')); } $user = User::where('email', $request->input('email'))->first(); if (!$user) { - abort(500, __('This email is not registered in the system')); + throw new ApiException(500, __('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()) { - abort(500, __('Reset failed')); + throw new ApiException(500, __('Reset failed')); } Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))); return response([ diff --git a/app/Http/Controllers/V1/Passport/CommController.php b/app/Http/Controllers/V1/Passport/CommController.php index 3f51638..60f941a 100644 --- a/app/Http/Controllers/V1/Passport/CommController.php +++ b/app/Http/Controllers/V1/Passport/CommController.php @@ -2,17 +2,15 @@ namespace App\Http\Controllers\V1\Passport; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Passport\CommSendEmailVerify; use App\Jobs\SendEmailJob; use App\Models\InviteCode; -use App\Models\User; use App\Utils\CacheKey; use App\Utils\Dict; -use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\Mail; use ReCaptcha\ReCaptcha; class CommController extends Controller @@ -30,12 +28,12 @@ class CommController extends Controller $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); if (!$recaptchaResp->isSuccess()) { - abort(500, __('Invalid code is incorrect')); + throw new ApiException(500, __('Invalid code is incorrect')); } } $email = $request->input('email'); if (Cache::get(CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP', $email))) { - abort(500, __('Email verification code has been sent, please request again later')); + throw new ApiException(500, __('Email verification code has been sent, please request again later')); } $code = rand(100000, 999999); $subject = admin_setting('app_name', 'XBoard') . __('Email verification code'); diff --git a/app/Http/Controllers/V1/Server/DeepbworkController.php b/app/Http/Controllers/V1/Server/DeepbworkController.php index 6914743..65105f7 100644 --- a/app/Http/Controllers/V1/Server/DeepbworkController.php +++ b/app/Http/Controllers/V1/Server/DeepbworkController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\ServerVmess; use App\Services\ServerService; @@ -9,8 +10,6 @@ use App\Services\UserService; use App\Utils\CacheKey; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Log; /* * V2ray Aurora @@ -23,10 +22,10 @@ class DeepbworkController extends Controller { $token = $request->input('token'); if (empty($token)) { - abort(500, 'token is null'); + throw new ApiException(500, 'token is null'); } if ($token !== admin_setting('server_token')) { - abort(500, 'token is error'); + throw new ApiException(500, 'token is error'); } } @@ -37,7 +36,7 @@ class DeepbworkController extends Controller $nodeId = $request->input('node_id'); $server = ServerVmess::find($nodeId); if (!$server) { - abort(500, 'fail'); + throw new ApiException(500, 'fail'); } Cache::put(CacheKey::get('SERVER_VMESS_LAST_CHECK_AT', $server->id), time(), 3600); $serverService = new ServerService(); @@ -97,12 +96,12 @@ class DeepbworkController extends Controller $nodeId = $request->input('node_id'); $localPort = $request->input('local_port'); if (empty($nodeId) || empty($localPort)) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } try { $json = $this->getV2RayConfig($nodeId, $localPort); } catch (\Exception $e) { - abort(500, $e->getMessage()); + throw new ApiException(500, $e->getMessage()); } return(json_encode($json, JSON_UNESCAPED_UNICODE)); @@ -112,7 +111,7 @@ class DeepbworkController extends Controller { $server = ServerVmess::find($nodeId); if (!$server) { - abort(500, '节点不存在'); + throw new ApiException(500, '节点不存在'); } $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 93104f0..41e38e0 100644 --- a/app/Http/Controllers/V1/Server/ShadowsocksTidalabController.php +++ b/app/Http/Controllers/V1/Server/ShadowsocksTidalabController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\ServerShadowsocks; use App\Services\ServerService; @@ -20,10 +21,10 @@ class ShadowsocksTidalabController extends Controller { $token = $request->input('token'); if (empty($token)) { - abort(500, 'token is null'); + throw new ApiException(500, 'token is null'); } if ($token !== admin_setting('server_token')) { - abort(500, 'token is error'); + throw new ApiException(500, 'token is error'); } } @@ -34,7 +35,7 @@ class ShadowsocksTidalabController extends Controller $nodeId = $request->input('node_id'); $server = ServerShadowsocks::find($nodeId); if (!$server) { - abort(500, 'fail'); + throw new ApiException(500, 'fail'); } 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 6661e4c..be4eaec 100644 --- a/app/Http/Controllers/V1/Server/TrojanTidalabController.php +++ b/app/Http/Controllers/V1/Server/TrojanTidalabController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Server; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\ServerTrojan; use App\Services\ServerService; @@ -9,8 +10,6 @@ use App\Services\UserService; use App\Utils\CacheKey; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Log; /* * Tidal Lab Trojan @@ -23,10 +22,10 @@ class TrojanTidalabController extends Controller { $token = $request->input('token'); if (empty($token)) { - abort(500, 'token is null'); + throw new ApiException(500, 'token is null'); } if ($token !== admin_setting('server_token')) { - abort(500, 'token is error'); + throw new ApiException(500, 'token is error'); } } @@ -37,7 +36,7 @@ class TrojanTidalabController extends Controller $nodeId = $request->input('node_id'); $server = ServerTrojan::find($nodeId); if (!$server) { - abort(500, 'fail'); + throw new ApiException(500, 'fail'); } Cache::put(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $server->id), time(), 3600); $serverService = new ServerService(); @@ -93,12 +92,12 @@ class TrojanTidalabController extends Controller $nodeId = $request->input('node_id'); $localPort = $request->input('local_port'); if (empty($nodeId) || empty($localPort)) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } try { $json = $this->getTrojanConfig($nodeId, $localPort); } catch (\Exception $e) { - abort(500, $e->getMessage()); + throw new ApiException(500, $e->getMessage()); } return(json_encode($json, JSON_UNESCAPED_UNICODE)); @@ -108,7 +107,7 @@ class TrojanTidalabController extends Controller { $server = ServerTrojan::find($nodeId); if (!$server) { - abort(500, '节点不存在'); + throw new ApiException(500, '节点不存在'); } $json = json_decode(self::TROJAN_CONFIG); diff --git a/app/Http/Controllers/V1/Staff/NoticeController.php b/app/Http/Controllers/V1/Staff/NoticeController.php index db518fb..e0c186c 100644 --- a/app/Http/Controllers/V1/Staff/NoticeController.php +++ b/app/Http/Controllers/V1/Staff/NoticeController.php @@ -2,11 +2,11 @@ namespace App\Http\Controllers\V1\Staff; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\NoticeSave; use App\Models\Notice; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; class NoticeController extends Controller { @@ -26,13 +26,13 @@ class NoticeController extends Controller ]); if (!$request->input('id')) { if (!Notice::create($data)) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } else { try { Notice::find($request->input('id'))->update($data); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } } return response([ @@ -43,14 +43,14 @@ class NoticeController extends Controller public function drop(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } $notice = Notice::find($request->input('id')); if (!$notice) { - abort(500, '公告不存在'); + throw new ApiException(500, '公告不存在'); } if (!$notice->delete()) { - abort(500, '删除失败'); + throw new ApiException(500, '删除失败'); } return response([ 'data' => true diff --git a/app/Http/Controllers/V1/Staff/TicketController.php b/app/Http/Controllers/V1/Staff/TicketController.php index 15246be..3456846 100644 --- a/app/Http/Controllers/V1/Staff/TicketController.php +++ b/app/Http/Controllers/V1/Staff/TicketController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Staff; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Ticket; use App\Models\TicketMessage; @@ -16,7 +17,7 @@ class TicketController extends Controller $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - abort(500, '工单不存在'); + throw new ApiException(500, '工单不存在'); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); for ($i = 0; $i < count($ticket['message']); $i++) { @@ -48,10 +49,10 @@ class TicketController extends Controller public function reply(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } if (empty($request->input('message'))) { - abort(500, '消息不能为空'); + throw new ApiException(500, '消息不能为空'); } $ticketService = new TicketService(); $ticketService->replyByAdmin( @@ -67,16 +68,16 @@ class TicketController extends Controller public function close(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } $ticket = Ticket::where('id', $request->input('id')) ->first(); if (!$ticket) { - abort(500, '工单不存在'); + throw new ApiException(500, '工单不存在'); } $ticket->status = 1; if (!$ticket->save()) { - abort(500, '关闭失败'); + throw new ApiException(500, '关闭失败'); } return response([ 'data' => true diff --git a/app/Http/Controllers/V1/Staff/UserController.php b/app/Http/Controllers/V1/Staff/UserController.php index 3d3d5ea..5b20a50 100644 --- a/app/Http/Controllers/V1/Staff/UserController.php +++ b/app/Http/Controllers/V1/Staff/UserController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\Staff; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\UserSendMail; use App\Http\Requests\Staff\UserUpdate; @@ -15,13 +16,13 @@ class UserController extends Controller public function getUserInfoById(Request $request) { if (empty($request->input('id'))) { - abort(500, '参数错误'); + throw new ApiException(422, '参数错误'); } $user = User::where('is_admin', 0) ->where('id', $request->input('id')) ->where('is_staff', 0) ->first(); - if (!$user) abort(500, '用户不存在'); + if (!$user) throw new ApiException(500, '用户不存在'); return response([ 'data' => $user ]); @@ -32,10 +33,10 @@ class UserController extends Controller $params = $request->validated(); $user = User::find($request->input('id')); if (!$user) { - abort(500, '用户不存在'); + throw new ApiException(500, '用户不存在'); } if (User::where('email', $params['email'])->first() && $user->email !== $params['email']) { - abort(500, '邮箱已被使用'); + throw new ApiException(500, '邮箱已被使用'); } if (isset($params['password'])) { $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT); @@ -46,7 +47,7 @@ class UserController extends Controller if (isset($params['plan_id'])) { $plan = Plan::find($params['plan_id']); if (!$plan) { - abort(500, '订阅计划不存在'); + throw new ApiException(500, '订阅计划不存在'); } $params['group_id'] = $plan->group_id; } @@ -54,7 +55,7 @@ class UserController extends Controller try { $user->update($params); } catch (\Exception $e) { - abort(500, '保存失败'); + throw new ApiException(500, '保存失败'); } return response([ 'data' => true @@ -97,7 +98,7 @@ class UserController extends Controller 'banned' => 1 ]); } catch (\Exception $e) { - abort(500, '处理失败'); + throw new ApiException(500, '处理失败'); } return response([ diff --git a/app/Http/Controllers/V1/User/CommController.php b/app/Http/Controllers/V1/User/CommController.php index acc312d..ec67b13 100644 --- a/app/Http/Controllers/V1/User/CommController.php +++ b/app/Http/Controllers/V1/User/CommController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Payment; use App\Utils\Dict; @@ -33,7 +34,7 @@ class CommController extends Controller $payment = Payment::where('id', $request->input('id')) ->where('payment', 'StripeCredit') ->first(); - if (!$payment) abort(500, 'payment is not found'); + if (!$payment) throw new ApiException(500, 'payment is not found'); return response([ 'data' => $payment->config['stripe_pk_live'] ]); diff --git a/app/Http/Controllers/V1/User/CouponController.php b/app/Http/Controllers/V1/User/CouponController.php index 6e08b64..fe29188 100644 --- a/app/Http/Controllers/V1/User/CouponController.php +++ b/app/Http/Controllers/V1/User/CouponController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Services\CouponService; use Illuminate\Http\Request; @@ -11,7 +12,7 @@ class CouponController extends Controller public function check(Request $request) { if (empty($request->input('code'))) { - abort(500, __('Coupon cannot be empty')); + throw new ApiException(500, __('Coupon cannot be empty')); } $couponService = new CouponService($request->input('code')); $couponService->setPlanId($request->input('plan_id')); diff --git a/app/Http/Controllers/V1/User/InviteController.php b/app/Http/Controllers/V1/User/InviteController.php index c43627f..e4c35c7 100644 --- a/app/Http/Controllers/V1/User/InviteController.php +++ b/app/Http/Controllers/V1/User/InviteController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\CommissionLog; use App\Models\InviteCode; @@ -15,7 +16,7 @@ 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)) { - abort(500, __('The maximum number of creations has been reached')); + throw new ApiException(500, __('The maximum number of creations has been reached')); } $inviteCode = new InviteCode(); $inviteCode->user_id = $request->user['id']; diff --git a/app/Http/Controllers/V1/User/KnowledgeController.php b/app/Http/Controllers/V1/User/KnowledgeController.php index 7d345e3..b79a749 100644 --- a/app/Http/Controllers/V1/User/KnowledgeController.php +++ b/app/Http/Controllers/V1/User/KnowledgeController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Knowledge; use App\Models\User; @@ -18,7 +19,7 @@ class KnowledgeController extends Controller ->where('show', 1) ->first() ->toArray(); - if (!$knowledge) abort(500, __('Article does not exist')); + if (!$knowledge) throw new ApiException(500, __('Article does not exist')); $user = User::find($request->user['id']); $userService = new UserService(); if (!$userService->isAvailable($user)) { diff --git a/app/Http/Controllers/V1/User/OrderController.php b/app/Http/Controllers/V1/User/OrderController.php index 80cfdcf..2bf620a 100755 --- a/app/Http/Controllers/V1/User/OrderController.php +++ b/app/Http/Controllers/V1/User/OrderController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\User\OrderSave; use App\Models\Order; @@ -53,12 +54,12 @@ class OrderController extends Controller ->where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { - abort(500, __('Order does not exist or has been paid')); + throw new ApiException(500, __('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']) { - abort(500, __('Subscription plan does not exist')); + throw new ApiException(500, __('Subscription plan does not exist')); } if ($order->surplus_order_ids) { $order['surplus_orders'] = Order::whereIn('id', $order->surplus_order_ids)->get(); @@ -72,7 +73,7 @@ class OrderController extends Controller { $userService = new UserService(); if ($userService->isNotCompleteOrderByUserId($request->user['id'])) { - abort(500, __('You have an unpaid or pending order, please try again later or cancel it')); + throw new ApiException(500, __('You have an unpaid or pending order, please try again later or cancel it')); } $planService = new PlanService($request->input('plan_id')); @@ -81,36 +82,36 @@ class OrderController extends Controller $user = User::find($request->user['id']); if (!$plan) { - abort(500, __('Subscription plan does not exist')); + throw new ApiException(500, __('Subscription plan does not exist')); } if ($user->plan_id !== $plan->id && !$planService->haveCapacity() && $request->input('period') !== 'reset_price') { - abort(500, __('Current product is sold out')); + throw new ApiException(500, __('Current product is sold out')); } if ($plan[$request->input('period')] === NULL) { - abort(500, __('This payment period cannot be purchased, please choose another period')); + throw new ApiException(500, __('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) { - abort(500, __('Subscription has expired or no active subscription, unable to purchase Data Reset Package')); + throw new ApiException(500, __('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') { - abort(500, __('This subscription has been sold out, please choose another subscription')); + throw new ApiException(500, __('This subscription has been sold out, please choose another subscription')); } } if (!$plan->renew && $user->plan_id == $plan->id && $request->input('period') !== 'reset_price') { - abort(500, __('This subscription cannot be renewed, please change to another subscription')); + throw new ApiException(500, __('This subscription cannot be renewed, please change to another subscription')); } if (!$plan->show && $plan->renew && !$userService->isAvailable($user)) { - abort(500, __('This subscription has expired, please change to another subscription')); + throw new ApiException(500, __('This subscription has expired, please change to another subscription')); } DB::beginTransaction(); @@ -126,7 +127,7 @@ class OrderController extends Controller $couponService = new CouponService($request->input('coupon_code')); if (!$couponService->use($order)) { DB::rollBack(); - abort(500, __('Coupon failed')); + throw new ApiException(500, __('Coupon failed')); } $order->coupon_id = $couponService->getId(); } @@ -141,14 +142,14 @@ class OrderController extends Controller if ($remainingBalance > 0) { if (!$userService->addBalance($order->user_id, - $order->total_amount)) { DB::rollBack(); - abort(500, __('Insufficient balance')); + throw new ApiException(500, __('Insufficient balance')); } $order->balance_amount = $order->total_amount; $order->total_amount = 0; } else { if (!$userService->addBalance($order->user_id, - $user->balance)) { DB::rollBack(); - abort(500, __('Insufficient balance')); + throw new ApiException(500, __('Insufficient balance')); } $order->balance_amount = $user->balance; $order->total_amount = $order->total_amount - $user->balance; @@ -157,7 +158,7 @@ class OrderController extends Controller if (!$order->save()) { DB::rollback(); - abort(500, __('Failed to create order')); + throw new ApiException(500, __('Failed to create order')); } DB::commit(); @@ -176,26 +177,26 @@ class OrderController extends Controller ->where('status', 0) ->first(); if (!$order) { - abort(500, __('Order does not exist or has been paid')); + throw new ApiException(500, __('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)) abort(500, ''); + if (!$orderService->paid($order->trade_no)) throw new ApiException(500, ''); return response([ 'type' => -1, 'data' => true ]); } $payment = Payment::find($method); - if (!$payment || $payment->enable !== 1) abort(500, __('Payment method is not available')); + if (!$payment || $payment->enable !== 1) throw new ApiException(500, __('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()) abort(500, __('Request failed, please try again later')); + if (!$order->save()) throw new ApiException(500, __('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, @@ -215,7 +216,7 @@ class OrderController extends Controller ->where('user_id', $request->user['id']) ->first(); if (!$order) { - abort(500, __('Order does not exist')); + throw new ApiException(500, __('Order does not exist')); } return response([ 'data' => $order->status @@ -244,20 +245,20 @@ class OrderController extends Controller public function cancel(Request $request) { if (empty($request->input('trade_no'))) { - abort(500, __('Invalid parameter')); + throw new ApiException(500, __('Invalid parameter')); } $order = Order::where('trade_no', $request->input('trade_no')) ->where('user_id', $request->user['id']) ->first(); if (!$order) { - abort(500, __('Order does not exist')); + throw new ApiException(500, __('Order does not exist')); } if ($order->status !== 0) { - abort(500, __('You can only cancel pending orders')); + throw new ApiException(500, __('You can only cancel pending orders')); } $orderService = new OrderService($order); if (!$orderService->cancel()) { - abort(500, __('Cancel failed')); + throw new ApiException(500, __('Cancel failed')); } return response([ 'data' => true diff --git a/app/Http/Controllers/V1/User/PlanController.php b/app/Http/Controllers/V1/User/PlanController.php index b17f195..ffd6f29 100755 --- a/app/Http/Controllers/V1/User/PlanController.php +++ b/app/Http/Controllers/V1/User/PlanController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Models\Plan; use App\Models\User; @@ -17,10 +18,10 @@ class PlanController extends Controller if ($request->input('id')) { $plan = Plan::where('id', $request->input('id'))->first(); if (!$plan) { - abort(500, __('Subscription plan does not exist')); + throw new ApiException(500, __('Subscription plan does not exist')); } if ((!$plan->show && !$plan->renew) || (!$plan->show && $user->plan_id !== $plan->id)) { - abort(500, __('Subscription plan does not exist')); + throw new ApiException(500, __('Subscription plan does not exist')); } return response([ 'data' => $plan diff --git a/app/Http/Controllers/V1/User/TicketController.php b/app/Http/Controllers/V1/User/TicketController.php index 385427a..7137e9a 100644 --- a/app/Http/Controllers/V1/User/TicketController.php +++ b/app/Http/Controllers/V1/User/TicketController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\User\TicketSave; use App\Http\Requests\User\TicketWithdraw; @@ -23,7 +24,7 @@ class TicketController extends Controller ->where('user_id', $request->user['id']) ->first(); if (!$ticket) { - abort(500, __('Ticket does not exist')); + throw new ApiException(500, __('Ticket does not exist')); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); for ($i = 0; $i < count($ticket['message']); $i++) { @@ -49,7 +50,7 @@ class TicketController extends Controller { DB::beginTransaction(); if ((int)Ticket::where('status', 0)->where('user_id', $request->user['id'])->lockForUpdate()->count()) { - abort(500, __('There are other unresolved tickets')); + throw new ApiException(500, __('There are other unresolved tickets')); } $ticket = Ticket::create(array_merge($request->only([ 'subject', @@ -59,7 +60,7 @@ class TicketController extends Controller ])); if (!$ticket) { DB::rollback(); - abort(500, __('Failed to open ticket')); + throw new ApiException(500, __('Failed to open ticket')); } $ticketMessage = TicketMessage::create([ 'user_id' => $request->user['id'], @@ -68,7 +69,7 @@ class TicketController extends Controller ]); if (!$ticketMessage) { DB::rollback(); - abort(500, __('Failed to open ticket')); + throw new ApiException(500, __('Failed to open ticket')); } DB::commit(); $this->sendNotify($ticket, $request->input('message')); @@ -80,22 +81,22 @@ class TicketController extends Controller public function reply(Request $request) { if (empty($request->input('id'))) { - abort(500, __('Invalid parameter')); + throw new ApiException(500, __('Invalid parameter')); } if (empty($request->input('message'))) { - abort(500, __('Message cannot be empty')); + throw new ApiException(500, __('Message cannot be empty')); } $ticket = Ticket::where('id', $request->input('id')) ->where('user_id', $request->user['id']) ->first(); if (!$ticket) { - abort(500, __('Ticket does not exist')); + throw new ApiException(500, __('Ticket does not exist')); } if ($ticket->status) { - abort(500, __('The ticket is closed and cannot be replied')); + throw new ApiException(500, __('The ticket is closed and cannot be replied')); } if ($request->user['id'] == $this->getLastMessage($ticket->id)->user_id) { - abort(500, __('Please wait for the technical enginneer to reply')); + throw new ApiException(500, __('Please wait for the technical enginneer to reply')); } $ticketService = new TicketService(); if (!$ticketService->reply( @@ -103,7 +104,7 @@ class TicketController extends Controller $request->input('message'), $request->user['id'] )) { - abort(500, __('Ticket reply failed')); + throw new ApiException(500, __('Ticket reply failed')); } $this->sendNotify($ticket, $request->input('message')); return response([ @@ -115,17 +116,17 @@ class TicketController extends Controller public function close(Request $request) { if (empty($request->input('id'))) { - abort(500, __('Invalid parameter')); + throw new ApiException(500, __('Invalid parameter')); } $ticket = Ticket::where('id', $request->input('id')) ->where('user_id', $request->user['id']) ->first(); if (!$ticket) { - abort(500, __('Ticket does not exist')); + throw new ApiException(500, __('Ticket does not exist')); } $ticket->status = 1; if (!$ticket->save()) { - abort(500, __('Close failed')); + throw new ApiException(500, __('Close failed')); } return response([ 'data' => true @@ -142,18 +143,18 @@ class TicketController extends Controller public function withdraw(TicketWithdraw $request) { if ((int)admin_setting('withdraw_close_enable', 0)) { - abort(500, 'user.ticket.withdraw.not_support_withdraw'); + throw new ApiException(500, 'user.ticket.withdraw.not_support_withdraw'); } if (!in_array( $request->input('withdraw_method'), admin_setting('commission_withdraw_method',Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT) )) { - abort(500, __('Unsupported withdrawal method')); + throw new ApiException(500, __('Unsupported withdrawal method')); } $user = User::find($request->user['id']); $limit = admin_setting('commission_withdraw_limit', 100); if ($limit > ($user->commission_balance / 100)) { - abort(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit])); + throw new ApiException(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit])); } DB::beginTransaction(); $subject = __('[Commission Withdrawal Request] This ticket is opened by the system'); @@ -164,7 +165,7 @@ class TicketController extends Controller ]); if (!$ticket) { DB::rollback(); - abort(500, __('Failed to open ticket')); + throw new ApiException(500, __('Failed to open ticket')); } $message = sprintf("%s\r\n%s", __('Withdrawal method') . ":" . $request->input('withdraw_method'), @@ -177,7 +178,7 @@ class TicketController extends Controller ]); if (!$ticketMessage) { DB::rollback(); - abort(500, __('Failed to open ticket')); + throw new ApiException(500, __('Failed to open ticket')); } DB::commit(); $this->sendNotify($ticket, $message); diff --git a/app/Http/Controllers/V1/User/UserController.php b/app/Http/Controllers/V1/User/UserController.php index 7a91706..be79f70 100755 --- a/app/Http/Controllers/V1/User/UserController.php +++ b/app/Http/Controllers/V1/User/UserController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\V1\User; +use App\Exceptions\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\User\UserChangePassword; use App\Http\Requests\User\UserTransfer; @@ -23,7 +24,7 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } $authService = new AuthService($user); return response([ @@ -35,7 +36,7 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } $authService = new AuthService($user); return response([ @@ -60,7 +61,7 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } if (!Helper::multiPasswordVerify( $user->password_algo, @@ -68,13 +69,13 @@ class UserController extends Controller $request->input('old_password'), $user->password) ) { - abort(500, __('The old password is wrong')); + throw new ApiException(500, __('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()) { - abort(500, __('Save failed')); + throw new ApiException(500, __('Save failed')); } return response([ 'data' => true @@ -103,7 +104,7 @@ class UserController extends Controller ]) ->first(); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } $user['avatar_url'] = 'https://cdn.v2ex.com/gravatar/' . md5($user->email) . '?s=64&d=identicon'; return response([ @@ -143,12 +144,12 @@ class UserController extends Controller ]) ->first(); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } if ($user->plan_id) { $user['plan'] = Plan::find($user->plan_id); if (!$user['plan']) { - abort(500, __('Subscription plan does not exist')); + throw new ApiException(500, __('Subscription plan does not exist')); } } $user['subscribe_url'] = Helper::getSubscribeUrl("/api/v1/client/subscribe?token={$user['token']}"); @@ -163,12 +164,12 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } $user->uuid = Helper::guid(true); $user->token = Helper::guid(); if (!$user->save()) { - abort(500, __('Reset failed')); + throw new ApiException(500, __('Reset failed')); } return response([ 'data' => Helper::getSubscribeUrl('/api/v1/client/subscribe?token=' . $user->token) @@ -184,12 +185,12 @@ class UserController extends Controller $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } try { $user->update($updateData); } catch (\Exception $e) { - abort(500, __('Save failed')); + throw new ApiException(500, __('Save failed')); } return response([ @@ -201,15 +202,15 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } if ($request->input('transfer_amount') > $user->commission_balance) { - abort(500, __('Insufficient commission balance')); + throw new ApiException(500, __('Insufficient commission balance')); } $user->commission_balance = $user->commission_balance - $request->input('transfer_amount'); $user->balance = $user->balance + $request->input('transfer_amount'); if (!$user->save()) { - abort(500, __('Transfer failed')); + throw new ApiException(500, __('Transfer failed')); } return response([ 'data' => true @@ -220,7 +221,7 @@ class UserController extends Controller { $user = User::find($request->user['id']); if (!$user) { - abort(500, __('The user does not exist')); + throw new ApiException(500, __('The user does not exist')); } $code = Helper::guid(); diff --git a/app/Http/Middleware/Admin.php b/app/Http/Middleware/Admin.php index c84a88c..d712d31 100755 --- a/app/Http/Middleware/Admin.php +++ b/app/Http/Middleware/Admin.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Exceptions\ApiException; use App\Services\AuthService; use Closure; use Illuminate\Support\Facades\Cache; @@ -18,10 +19,10 @@ class Admin public function handle($request, Closure $next) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) abort(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); $user = AuthService::decryptAuthData($authorization); - if (!$user || !$user['is_admin']) abort(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 c90b1a3..d46378b 100755 --- a/app/Http/Middleware/Client.php +++ b/app/Http/Middleware/Client.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Exceptions\ApiException; use App\Utils\CacheKey; use Closure; use App\Models\User; @@ -20,11 +21,11 @@ class Client { $token = $request->input('token'); if (empty($token)) { - abort(403, 'token is null'); + throw new ApiException(403, 'token is null'); } $user = User::where('token', $token)->first(); if (!$user) { - abort(403, 'token is error'); + throw new ApiException(403, 'token is error'); } $request->merge([ 'user' => $user diff --git a/app/Http/Middleware/Staff.php b/app/Http/Middleware/Staff.php index 237d278..f51fd5e 100644 --- a/app/Http/Middleware/Staff.php +++ b/app/Http/Middleware/Staff.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Exceptions\ApiException; use App\Services\AuthService; use Closure; @@ -17,10 +18,10 @@ class Staff public function handle($request, Closure $next) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) abort(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); $user = AuthService::decryptAuthData($authorization); - if (!$user || !$user['is_staff']) abort(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 0e9ce3f..0b1e64f 100755 --- a/app/Http/Middleware/User.php +++ b/app/Http/Middleware/User.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Exceptions\ApiException; use App\Services\AuthService; use Closure; use Illuminate\Support\Facades\Cache; @@ -18,10 +19,10 @@ class User public function handle($request, Closure $next) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); - if (!$authorization) abort(403, '未登录或登陆已过期'); + if (!$authorization) throw new ApiException(403, '未登录或登陆已过期'); $user = AuthService::decryptAuthData($authorization); - if (!$user) abort(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 0ff555c..28db7f4 100644 --- a/app/Http/Routes/V1/ServerRoute.php +++ b/app/Http/Routes/V1/ServerRoute.php @@ -1,6 +1,7 @@ 'server' ], function ($router) { $router->any('/{class}/{action}', function($class, $action) { - $ctrl = \App::make("\\App\\Http\\Controllers\\V1\\Server\\" . ucfirst($class) . "Controller"); + $controllerClass = "\\App\\Http\\Controllers\\V1\\Server\\" . ucfirst($class) . "Controller"; + if(!(class_exists($controllerClass) && method_exists($controllerClass, $action))){ + throw new ApiException(404,'Not Found'); + }; + $ctrl = \App::make($controllerClass); return \App::call([$ctrl, $action]); }); }); diff --git a/app/Jobs/SendEmailJob.php b/app/Jobs/SendEmailJob.php index 48bbf0b..3cff937 100644 --- a/app/Jobs/SendEmailJob.php +++ b/app/Jobs/SendEmailJob.php @@ -70,6 +70,5 @@ class SendEmailJob implements ShouldQueue MailLog::create($log); $log['config'] = config('mail'); - return $log; } } diff --git a/app/Payments/AlipayF2F.php b/app/Payments/AlipayF2F.php index e530b0f..fdd7bf9 100644 --- a/app/Payments/AlipayF2F.php +++ b/app/Payments/AlipayF2F.php @@ -4,6 +4,7 @@ * 自己写别抄,抄NMB抄 */ namespace App\Payments; +use App\Exceptions\ApiException; class AlipayF2F { public function __construct($config) @@ -57,7 +58,7 @@ class AlipayF2F { 'data' => $gateway->getQrCodeUrl() ]; } catch (\Exception $e) { - abort(500, $e->getMessage()); + throw new ApiException(500, $e->getMessage()); } } diff --git a/app/Payments/BTCPay.php b/app/Payments/BTCPay.php index d1e05dc..2f404cf 100644 --- a/app/Payments/BTCPay.php +++ b/app/Payments/BTCPay.php @@ -1,6 +1,7 @@ 1, // Redirect to url @@ -75,7 +76,7 @@ class BTCPay { $computedSignature = "sha256=" . \hash_hmac('sha256', $payload, $this->config['btcpay_webhook_key']); if (!self::hashEqual($signraturHeader, $computedSignature)) { - abort(400, 'HMAC signature does not match'); + throw new ApiException(400, 'HMAC signature does not match'); return false; } diff --git a/app/Payments/CoinPayments.php b/app/Payments/CoinPayments.php index 511fd82..2192be2 100644 --- a/app/Payments/CoinPayments.php +++ b/app/Payments/CoinPayments.php @@ -1,6 +1,7 @@ config['coinpayments_merchant_id'])) { - abort(500, 'No or incorrect Merchant ID passed'); + throw new ApiException(500, 'No or incorrect Merchant ID passed'); } $headers = getallheaders(); @@ -77,11 +78,11 @@ class CoinPayments { $hmac = hash_hmac("sha512", $request, trim($this->config['coinpayments_ipn_secret'])); // if ($hmac != $signHeader) { <-- Use this if you are running a version of PHP below 5.6.0 without the hash_equals function - // abort(400, 'HMAC signature does not match'); + // throw new ApiException(400, 'HMAC signature does not match'); // } if (!hash_equals($hmac, $signHeader)) { - abort(400, 'HMAC signature does not match'); + throw new ApiException(400, 'HMAC signature does not match'); } // HMAC Signature verified at this point, load some variables. @@ -95,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 - abort(500, 'Payment Timed Out or Error'); + throw new ApiException(500, '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 7fe8288..e4ab4f5 100644 --- a/app/Payments/Coinbase.php +++ b/app/Payments/Coinbase.php @@ -1,6 +1,7 @@ 1, @@ -70,7 +71,7 @@ class Coinbase { $computedSignature = \hash_hmac('sha256', $payload, $this->config['coinbase_webhook_key']); if (!self::hashEqual($signatureHeader, $computedSignature)) { - abort(400, 'HMAC signature does not match'); + throw new ApiException(400, 'HMAC signature does not match'); } $out_trade_no = $json_param['event']['data']['metadata']['outTradeNo']; diff --git a/app/Payments/MGate.php b/app/Payments/MGate.php index cb0be56..46f877c 100644 --- a/app/Payments/MGate.php +++ b/app/Payments/MGate.php @@ -5,6 +5,7 @@ */ namespace App\Payments; +use App\Exceptions\ApiException; use \Curl\Curl; class MGate { @@ -62,21 +63,21 @@ class MGate { $curl->post($this->config['mgate_url'] . '/v1/gateway/fetch', http_build_query($params)); $result = $curl->response; if (!$result) { - abort(500, '网络异常'); + throw new ApiException(500, '网络异常'); } if ($curl->error) { if (isset($result->errors)) { $errors = (array)$result->errors; - abort(500, $errors[array_keys($errors)[0]][0]); + throw new ApiException(500, $errors[array_keys($errors)[0]][0]); } if (isset($result->message)) { - abort(500, $result->message); + throw new ApiException(500, $result->message); } - abort(500, '未知错误'); + throw new ApiException(500, '未知错误'); } $curl->close(); if (!isset($result->data->trade_no)) { - abort(500, '接口请求失败'); + throw new ApiException(500, '接口请求失败'); } return [ 'type' => 1, // 0:qrcode 1:url diff --git a/app/Payments/StripeAlipay.php b/app/Payments/StripeAlipay.php index 3e81ace..92a3b83 100644 --- a/app/Payments/StripeAlipay.php +++ b/app/Payments/StripeAlipay.php @@ -5,6 +5,7 @@ */ namespace App\Payments; +use App\Exceptions\ApiException; use Stripe\Source; use Stripe\Stripe; @@ -40,7 +41,7 @@ class StripeAlipay { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - abort(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(500, __('Currency conversion has timed out, please try again later')); } Stripe::setApiKey($this->config['stripe_sk_live']); $source = Source::create([ @@ -58,7 +59,7 @@ class StripeAlipay { ] ]); if (!$source['redirect']['url']) { - abort(500, __('Payment gateway request failed')); + throw new ApiException(500, __('Payment gateway request failed')); } return [ 'type' => 1, @@ -76,7 +77,7 @@ class StripeAlipay { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - abort(400); + throw new ApiException(400); } switch ($event->type) { case 'source.chargeable': @@ -103,7 +104,7 @@ class StripeAlipay { } break; default: - abort(500, 'event is not support'); + throw new ApiException(500, 'event is not support'); } return('success'); } diff --git a/app/Payments/StripeCheckout.php b/app/Payments/StripeCheckout.php index 058dfbd..bf2663b 100644 --- a/app/Payments/StripeCheckout.php +++ b/app/Payments/StripeCheckout.php @@ -2,6 +2,7 @@ namespace App\Payments; +use App\Exceptions\ApiException; use Stripe\Stripe; use Stripe\Checkout\Session; @@ -47,7 +48,7 @@ class StripeCheckout { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - abort(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(500, __('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'; @@ -86,7 +87,7 @@ class StripeCheckout { $session = Session::create($params); } catch (\Exception $e) { info($e); - abort(500, "Failed to create order. Error: {$e->getMessage}"); + throw new ApiException(500, "Failed to create order. Error: {$e->getMessage}"); } return [ 'type' => 1, // 0:qrcode 1:url @@ -104,7 +105,7 @@ class StripeCheckout { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - abort(400); + throw new ApiException(400); } switch ($event->type) { @@ -125,7 +126,7 @@ class StripeCheckout { ]; break; default: - abort(500, 'event is not support'); + throw new ApiException(500, 'event is not support'); } return('success'); } diff --git a/app/Payments/StripeCredit.php b/app/Payments/StripeCredit.php index fe6d442..1527677 100644 --- a/app/Payments/StripeCredit.php +++ b/app/Payments/StripeCredit.php @@ -5,6 +5,7 @@ */ namespace App\Payments; +use App\Exceptions\ApiException; use Stripe\Source; use Stripe\Stripe; @@ -46,7 +47,7 @@ class StripeCredit { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - abort(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(500, __('Currency conversion has timed out, please try again later')); } Stripe::setApiKey($this->config['stripe_sk_live']); try { @@ -62,10 +63,10 @@ class StripeCredit { ]); } catch (\Exception $e) { info($e); - abort(500, __('Payment failed. Please check your credit card information')); + throw new ApiException(500, __('Payment failed. Please check your credit card information')); } if (!$charge->paid) { - abort(500, __('Payment failed. Please check your credit card information')); + throw new ApiException(500, __('Payment failed. Please check your credit card information')); } return [ 'type' => 2, @@ -83,7 +84,7 @@ class StripeCredit { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - abort(400); + throw new ApiException(400); } switch ($event->type) { case 'source.chargeable': @@ -110,7 +111,7 @@ class StripeCredit { } break; default: - abort(500, 'event is not support'); + throw new ApiException(500, 'event is not support'); } return('success'); } diff --git a/app/Payments/StripeWepay.php b/app/Payments/StripeWepay.php index 2543ed0..7c63fa1 100644 --- a/app/Payments/StripeWepay.php +++ b/app/Payments/StripeWepay.php @@ -5,6 +5,7 @@ */ namespace App\Payments; +use App\Exceptions\ApiException; use Stripe\Source; use Stripe\Stripe; @@ -40,7 +41,7 @@ class StripeWepay { $currency = $this->config['currency']; $exchange = $this->exchange('CNY', strtoupper($currency)); if (!$exchange) { - abort(500, __('Currency conversion has timed out, please try again later')); + throw new ApiException(500, __('Currency conversion has timed out, please try again later')); } Stripe::setApiKey($this->config['stripe_sk_live']); $source = Source::create([ @@ -58,7 +59,7 @@ class StripeWepay { ] ]); if (!$source['wechat']['qr_code_url']) { - abort(500, __('Payment gateway request failed')); + throw new ApiException(500, __('Payment gateway request failed')); } return [ 'type' => 0, @@ -76,7 +77,7 @@ class StripeWepay { $this->config['stripe_webhook_key'] ); } catch (\Stripe\Error\SignatureVerification $e) { - abort(400); + throw new ApiException(400); } switch ($event->type) { case 'source.chargeable': @@ -103,7 +104,7 @@ class StripeWepay { } break; default: - abort(500, 'event is not support'); + throw new ApiException(500, 'event is not support'); } return('success'); } diff --git a/app/Payments/WechatPayNative.php b/app/Payments/WechatPayNative.php index b65806a..1ba47b4 100644 --- a/app/Payments/WechatPayNative.php +++ b/app/Payments/WechatPayNative.php @@ -2,6 +2,7 @@ namespace App\Payments; +use App\Exceptions\ApiException; use Omnipay\Omnipay; use Omnipay\WechatPay\Helper; @@ -52,7 +53,7 @@ class WechatPayNative { $response = $request->send(); $response = $response->getData(); if ($response['return_code'] !== 'SUCCESS') { - abort(500, $response['return_msg']); + throw new ApiException(500, $response['return_msg']); } return [ 'type' => 0, diff --git a/app/Plugins/Telegram/Commands/Bind.php b/app/Plugins/Telegram/Commands/Bind.php index 0242bec..e33402c 100644 --- a/app/Plugins/Telegram/Commands/Bind.php +++ b/app/Plugins/Telegram/Commands/Bind.php @@ -2,6 +2,7 @@ namespace App\Plugins\Telegram\Commands; +use App\Exceptions\ApiException; use App\Models\User; use App\Plugins\Telegram\Telegram; @@ -12,25 +13,25 @@ class Bind extends Telegram { public function handle($message, $match = []) { if (!$message->is_private) return; if (!isset($message->args[0])) { - abort(500, '参数有误,请携带订阅地址发送'); + throw new ApiException(422, '参数有误,请携带订阅地址发送'); } $subscribeUrl = $message->args[0]; $subscribeUrl = parse_url($subscribeUrl); parse_str($subscribeUrl['query'], $query); $token = $query['token']; if (!$token) { - abort(500, '订阅地址无效'); + throw new ApiException(500, '订阅地址无效'); } $user = User::where('token', $token)->first(); if (!$user) { - abort(500, '用户不存在'); + throw new ApiException(500, '用户不存在'); } if ($user->telegram_id) { - abort(500, '该账号已经绑定了Telegram账号'); + throw new ApiException(500, '该账号已经绑定了Telegram账号'); } $user->telegram_id = $message->chat_id; if (!$user->save()) { - abort(500, '设置失败'); + throw new ApiException(500, '设置失败'); } $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 e4a64d0..0468ac5 100644 --- a/app/Plugins/Telegram/Commands/ReplyTicket.php +++ b/app/Plugins/Telegram/Commands/ReplyTicket.php @@ -2,6 +2,7 @@ namespace App\Plugins\Telegram\Commands; +use App\Exceptions\ApiException; use App\Models\User; use App\Plugins\Telegram\Telegram; use App\Services\TicketService; @@ -20,7 +21,7 @@ class ReplyTicket extends Telegram { { $user = User::where('telegram_id', $msg->chat_id)->first(); if (!$user) { - abort(500, '用户不存在'); + throw new ApiException(500, '用户不存在'); } 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 6dde5cf..65fbf82 100644 --- a/app/Plugins/Telegram/Commands/UnBind.php +++ b/app/Plugins/Telegram/Commands/UnBind.php @@ -2,6 +2,7 @@ namespace App\Plugins\Telegram\Commands; +use App\Exceptions\ApiException; use App\Models\User; use App\Plugins\Telegram\Telegram; @@ -19,7 +20,7 @@ class UnBind extends Telegram { } $user->telegram_id = NULL; if (!$user->save()) { - abort(500, '解绑失败'); + throw new ApiException(500, '解绑失败'); } $telegramService->sendMessage($message->chat_id, '解绑成功', 'markdown'); } diff --git a/app/Services/CouponService.php b/app/Services/CouponService.php index 68c00c0..8e87a76 100644 --- a/app/Services/CouponService.php +++ b/app/Services/CouponService.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Exceptions\ApiException; use App\Models\Coupon; use App\Models\Order; use Illuminate\Support\Facades\DB; @@ -85,30 +86,30 @@ class CouponService public function check() { if (!$this->coupon || !$this->coupon->show) { - abort(500, __('Invalid coupon')); + throw new ApiException(500, __('Invalid coupon')); } if ($this->coupon->limit_use <= 0 && $this->coupon->limit_use !== NULL) { - abort(500, __('This coupon is no longer available')); + throw new ApiException(500, __('This coupon is no longer available')); } if (time() < $this->coupon->started_at) { - abort(500, __('This coupon has not yet started')); + throw new ApiException(500, __('This coupon has not yet started')); } if (time() > $this->coupon->ended_at) { - abort(500, __('This coupon has expired')); + throw new ApiException(500, __('This coupon has expired')); } if ($this->coupon->limit_plan_ids && $this->planId) { if (!in_array($this->planId, $this->coupon->limit_plan_ids)) { - abort(500, __('The coupon code cannot be used for this subscription')); + throw new ApiException(500, __('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)) { - abort(500, __('The coupon code cannot be used for this period')); + throw new ApiException(500, __('The coupon code cannot be used for this period')); } } if ($this->coupon->limit_use_with_user !== NULL && $this->userId) { if (!$this->checkLimitUseWithUser()) { - abort(500, __('The coupon can only be used :limit_use_with_user per person', [ + throw new ApiException(500, __('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 280cdc1..2f0e5af 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -2,12 +2,11 @@ namespace App\Services; +use App\Exceptions\ApiException; use App\Jobs\OrderHandleJob; use App\Models\Order; use App\Models\Plan; use App\Models\User; -use App\Utils\CacheKey; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; class OrderService @@ -45,7 +44,7 @@ class OrderService ]); } catch (\Exception $e) { DB::rollback(); - abort(500, '开通失败'); + throw new ApiException(500, '开通失败'); } } switch ((string)$order->period) { @@ -75,12 +74,12 @@ class OrderService if (!$this->user->save()) { DB::rollBack(); - abort(500, '开通失败'); + throw new ApiException(500, '开通失败'); } $order->status = 3; if (!$order->save()) { DB::rollBack(); - abort(500, '开通失败'); + throw new ApiException(500, '开通失败'); } DB::commit(); @@ -93,7 +92,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)) abort(500, '目前不允许更改订阅,请联系客服或提交工单操作'); + if (!(int)admin_setting('plan_change_enable', 1)) throw new ApiException(500, '目前不允许更改订阅,请联系客服或提交工单操作'); $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 7fec8c4..0fb18a8 100644 --- a/app/Services/PaymentService.php +++ b/app/Services/PaymentService.php @@ -3,6 +3,7 @@ namespace App\Services; +use App\Exceptions\ApiException; use App\Models\Payment; class PaymentService @@ -16,7 +17,7 @@ class PaymentService { $this->method = $method; $this->class = '\\App\\Payments\\' . $this->method; - if (!class_exists($this->class)) abort(500, 'gate is not found'); + if (!class_exists($this->class)) throw new ApiException(500, 'gate is not found'); if ($id) $payment = Payment::find($id)->toArray(); if ($uuid) $payment = Payment::where('uuid', $uuid)->first()->toArray(); $this->config = []; @@ -32,7 +33,7 @@ class PaymentService public function notify($params) { - if (!$this->config['enable']) abort(500, 'gate is not enable'); + if (!$this->config['enable']) throw new ApiException(500, 'gate is not enable'); return $this->payment->notify($params); } diff --git a/app/Services/TelegramService.php b/app/Services/TelegramService.php index a7e4c26..60ce00f 100644 --- a/app/Services/TelegramService.php +++ b/app/Services/TelegramService.php @@ -1,10 +1,10 @@ get($this->api . $method . '?' . http_build_query($params)); $response = $curl->response; $curl->close(); - if (!isset($response->ok)) abort(500, '请求失败'); + if (!isset($response->ok)) throw new ApiException(500, '请求失败'); if (!$response->ok) { - abort(500, '来自TG的错误:' . $response->description); + throw new ApiException(500, '来自TG的错误:' . $response->description); } return $response; } diff --git a/app/Services/ThemeService.php b/app/Services/ThemeService.php index 71376ee..6332b2b 100644 --- a/app/Services/ThemeService.php +++ b/app/Services/ThemeService.php @@ -2,7 +2,6 @@ namespace App\Services; -use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; class ThemeService @@ -33,22 +32,5 @@ class ThemeService } catch (\Exception $e) { abort(500, "{$this->theme}初始化失败"); } - // $data = var_export($data, 1); - // try { - // if (!File::put(base_path() . "/config/theme/{$this->theme}.php", "theme}初始化失败"); - // } - // } catch (\Exception $e) { - // abort(500, '请检查V2Board目录权限'); - // } - - // try { - // Artisan::call('config:cache'); - // while (true) { - // if (config("theme.{$this->theme}")) break; - // } - // } catch (\Exception $e) { - // abort(500, "{$this->theme}初始化失败"); - // } } } diff --git a/app/Services/TicketService.php b/app/Services/TicketService.php index 1028509..985e145 100644 --- a/app/Services/TicketService.php +++ b/app/Services/TicketService.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Exceptions\ApiException; use App\Jobs\SendEmailJob; use App\Models\Ticket; use App\Models\TicketMessage; @@ -36,7 +37,7 @@ class TicketService { $ticket = Ticket::where('id', $ticketId) ->first(); if (!$ticket) { - abort(500, '工单不存在'); + throw new ApiException(500, '工单不存在'); } $ticket->status = 0; DB::beginTransaction(); @@ -52,7 +53,7 @@ class TicketService { } if (!$ticketMessage || !$ticket->save()) { DB::rollback(); - abort(500, '工单回复失败'); + throw new ApiException(500, '工单回复失败'); } DB::commit(); $this->sendEmailNotify($ticket, $ticketMessage);