star-insure/api-client

Star Insure API 客户端

7.0.0 2024-05-31 04:14 UTC

README

一个为Laravel应用提供的包,它包括对Star Inure API的封装,并为与Star auth应用进行身份验证提供了路由、控制器和中间件模板。

安装

您可以通过composer安装此包

composer require star-insure/api-client

将这些值添加到您的.env文件中

# API
SIS_API_URL=http://api.starinsure.test
SIS_API_AUTH_STRATEGY=user|app
SIS_API_TOKEN=dev
SIS_API_GROUP_ID=2

# OAuth client
SIS_API_CLIENT_ID=app
SIS_API_CLIENT_SECRET=secret

发布配置

php artisan vendor:publish --tag=starinsure

追加路由

将以下行添加到您的/routes/web.php文件中。

require __DIR__.'/oauth.php';

使用方法

API

通过实例化一个新的客户端,或使用StarInsure\Api\Facades\StarApi门面来调用Star API。

StarApi::get('/users/me');
StarApi::get('/users');

身份验证

使用Laravel提供的"auth"中间件。

Route::get('/protected', function () {
    return 'Only authenticated users can see this.';
})->middleware('auth');

或路由组

Route::middleware(['auth'])->group(function () {
    Route::get('/protected', function () {
        return "Only authenticated users can see this.";
    });
});

如果没有有效会话,用户将被自动重定向到身份验证服务器,登录成功后会返回到请求的目的地。

辅助函数

遵循Laravel风格,您还可以使用辅助函数。要注册身份验证辅助函数以覆盖Laravel内置的auth()函数,请按照以下步骤操作。

此包依赖于funkjedi/composer-include-files,允许您在依赖项的全局函数之前加载自己的函数。

app目录中创建一个helpers.php文件(或编辑现有的一个)

// We use this helper purely to help the IDE recognise the global function's return type
if (! function_exists('auth') && isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] === 'ide') {
    /**
     * Get the available auth instance.
     */
    function auth(): StarInsure\Api\StarAuthManager
    {
        return new \StarInsure\Api\StarAuthManager(
            app(),
            config('star.api_url').'/api/'.config('star.version'),
        );
    }
}

if (! function_exists('api')) {
    /**
     * Global helper to create an instance of the StarApi client.
     */
    function api(string $token = null)
    {
        return new \StarInsure\Api\StarApi(
            auth_strategy: config('star.auth_strategy'),
            version: config('star.version'),
            apiTokenOverride: $token,
        );
    }
}

if (! function_exists('appApi')) {
    /**
     * An instance of the API client for non-authenticated routes
     */
    function appApi()
    {
        return new \StarInsure\Api\StarApi(
            'app',
            config('star.version'),
            config('star.token'),
            config('star.group_id')
        );
    }
}

composer.json中自动加载辅助函数文件

"autoload": {
    ...
    "files": [
        "app/helpers.php"
    ]
},

在将辅助函数文件添加到composer.json后,您需要导出自加载器

composer dump-autoload

现在您可以使用全局辅助函数,而不必担心命名空间/导入。

$user = auth()->user();
$id = auth()->id();
$group = auth()->group();
$role = auth()->role();
$permissions = auth()->permissions();
$context = auth()->context();

$apiResponse = api()->get('/users/me', [ 'include' => 'groups' ]);