PHPackages                             yansongda/laravel-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. yansongda/laravel-api

ActiveLibrary[API Development](/categories/api)

yansongda/laravel-api
=====================

基于 access\_token 的多用户 API 认证系统

v1.0.2(8y ago)5085718MITPHPPHP &gt;=5.6

Since Apr 6Pushed 8y ago3 watchersCompare

[ Source](https://github.com/yansongda/laravel-api)[ Packagist](https://packagist.org/packages/yansongda/laravel-api)[ RSS](/packages/yansongda-laravel-api/feed)WikiDiscussions master Synced 2w ago

READMEChangelogDependencies (5)Versions (4)Used By (0)

Laravel-API
===========

[](#laravel-api)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/2cee5bf3a3d7ce89676913f16ef084552edc41e6c1e0cce47745755f87096a29/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f79616e736f6e6764612f6c61726176656c2d6170692f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/yansongda/laravel-api/?branch=master)[![Build Status](https://camo.githubusercontent.com/dea2ac9dc46bddc00808457167e5cf3ce434261c5b8eb1999c768bdf6090a7fa/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f79616e736f6e6764612f6c61726176656c2d6170692f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/yansongda/laravel-api/build-status/master)[![Latest Stable Version](https://camo.githubusercontent.com/2d91f9b7fdcff987368068fb8daf4f7c7b7110abc7094fc11c906df5fdfcb587/68747470733a2f2f706f7365722e707567782e6f72672f79616e736f6e6764612f6c61726176656c2d6170692f762f737461626c65)](https://packagist.org/packages/yansongda/laravel-api)[![Latest Unstable Version](https://camo.githubusercontent.com/9fdd7721c379d5ab1dadcc0d89231d2c1330bc814330f674bbabf48140e1c969/68747470733a2f2f706f7365722e707567782e6f72672f79616e736f6e6764612f6c61726176656c2d6170692f762f756e737461626c65)](https://packagist.org/packages/yansongda/laravel-api)[![License](https://camo.githubusercontent.com/c803dd7132ce7767a53b86467c5a13f676a1e486b0d7d323dfe4fc8603b8356e/68747470733a2f2f706f7365722e707567782e6f72672f79616e736f6e6764612f6c61726176656c2d6170692f6c6963656e7365)](https://packagist.org/packages/yansongda/laravel-api)

当看到 Laravel-API 时，您可能在想：「不是有官方的 Passport 吗，干嘛又重复造轮子？」是的，对于中大型，且需要有 `OAuth` 授权的应用来说， Passport 的确是一个很好的选择。

**但是，对于我们经常开发的中小型应用呢？我们大部分时候可能只是需要提供一个对外服务的 API 接口而已，像是类似于微信开发、支付宝开发那样，给一组 APPID/appsecret 就开始提供纯粹的 API 服务，所以像 Passport 这样的重量级选手，可能就不是更好的选择了。**

您可能又会说：「我可以使用 Passport 的 密码授权令牌 啊！」是的，您可以使用，但是，看到 `client_id`/`client_secret`/`username`/`password` 您作何感想？

您可能又又会说：「我可以使用 Passport 的 `客户端凭据授权令牌`啊！」是的，您也可以使用，但是：

- `client_id` 是有序整数
- 还需要通过额外的 `$request` 信息，再去重新相关获取授权信息
- access\_token 那么长，对于一个小应用实在没必要
- ...

这些您能忍？

反正我是不能忍，所以，弄了这个轮子。

运行环境
----

[](#运行环境)

- php &gt;= 5.6
- composer
- laravel &gt;= 5.1

特点
--

[](#特点)

- 简答、易懂、快速
- 专门为 laravel 打造
- 使用自带的认证驱动模式
- 多用户多应用 access\_token 模式（类似支付宝/微信公众平台认证模式）

安装
--

[](#安装)

```
$ composer require yansongda/laravel-api
```

### 添加 ServiceProvider（optional. if laravel &lt; 5.5）

[](#添加-serviceprovideroptional-if-laravel--55)

```
// laravel < 5.5
Yansongda\LaravelApi\ApiServiceProvider::class,
```

使用方法
----

[](#使用方法)

1. 更改认证驱动

    在 config/auth.php 中，更改 `guards.api.driver` 为 **api**
2. 在 UserModel 中添加 trait

    在 `config(auth.provider.xx.model)` 的类中，添加 `use Yansongda\LaravelApi\Models\Traits\HasApiApps`
3. 运行数据迁移

    `php artian migrate`
4. 开始使用吧

### 添加 App 与 accessToken

[](#添加-app-与-accesstoken)

```
use Yansongda\LaravelApi\Api;

$app = Api::createApp(User::find(1), '备注可选');

$access_token = Api::generateAccessToken($app);
```

### 客户端使用

[](#客户端使用)

#### 获取 access\_token

[](#获取-access_token)

```
curl --data "app_id=f748864cb16db706be1e408cb49771a3&app_secret=ce57ec31a9f4f37dfbf810c2e4ea79f0" "http://api.dev/api/token"
# {"code":0,"message":"success","data":{"user_id":1,"app_id":"f748864cb16db706be1e408cb49771a3","access_token":"3857d7d56f4ffe1ab57b8a8f292b85fa","expired_in":7200}}
```

#### 使用

[](#使用)

有两种方式可以使用

- url 带上 `access_token` 参数进行认证.

    例如： `https://api.dev/?access_token=3857d7d56f4ffe1ab57b8a8f292b85fa`
- header 上进行认证

    例如：`Authorization: Bearer 3857d7d56f4ffe1ab57b8a8f292b85fa`

### 服务端认证

[](#服务端认证)

只需要在增加 `'auth:api'` 的 middleware 即可，增加后，`$request->user()/$request->user` 即为认证用户，`$request->app` 即为认证的 app\_id

```
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('user', function(Request $request) {
    dd($request->user());
    // $request->user 获取 user_id
});
Route::middleware('auth:api')->get('app', function(Request $request) {
    dd($request->app); // 获取 app_id
});
```

其它
--

[](#其它)

### access\_token 有效时间

[](#access_token-有效时间)

access\_token 有效时间默认为 `7200` 秒，当然，您可以自由设置该值：

```
// 在 AppServiceProvider 的 register 方法中增加

use Yansongda\LaravelApi\Api;

Api::$ttl = 7200;
// Api::setTtl(7200);
```

### 授权 token 路由

[](#授权-token-路由)

默认情况下，token 的授权通过自带的 `'api/token'` 路由进行 `post` 授权的，如果您想重写 token 的授权方式，您需要首先：

```
// 在 AppServiceProvider 的 register 方法中增加

use Yansongda\LaravelApi\Api;

Api::$enableRoute = false;
// Api::enableRoute(false);
```

### 授权 token 路由前缀

[](#授权-token-路由前缀)

默认情况下，自带的路由前缀为 `api`，如果您想更换为其它，请：

```
// 在 AppServiceProvider 的 register 方法中增加

use Yansongda\LaravelApi\Api;

Api::$routePrefix = 'api';
// Api::setRoutePrefix(’api‘);
```

### 授权 token 路由说明

[](#授权-token-路由说明)

- 命名为: api.token
- middleware: api

### 关于 refresh\_token

[](#关于-refresh_token)

本着简单易用的原则，并不提供 refresh\_token 这种操作，因为发现即使像微信那样提供了 refresh\_token 的接口，但是，很多人依然没有去使用，而是直接重新生成新的 access\_token。因此，SDK 直接去掉了 refresh\_token 的设计。

异常
--

[](#异常)

- AccessTokenNotProvidedException

    当客户端没有提供 access\_token 时，抛出 `AccessTokenNotProvidedException` 异常，如果不进行任何额外的操作，默认将返回 `{"code":1,"message":"AccessToken Is Not Provided"}`
- InvalidAccessTokenException

    当客户端提供了无效的 access\_token 时，抛出 `InvalidAccessTokenException` 异常，如果不进行任何额外的操作，默认将返回 `{"code":2,"message":"AccessToken Is Invalid"}`
- AccessTokenExpiredException

    当客户端提供的 access\_token 已过期时，抛出 `AccessTokenExpiredException` 异常，如果不进行任何额外的操作，默认将返回 `{"code":3,"message":"AccessToken Is Expired"}`
- GenerateAccessTokenException

    当服务端生成 access\_token 失败时，抛出 `GenerateAccessTokenException` 异常，如果不进行任何额外的操作，默认将返回 `{"code":4,"message":"xxxx"}`
- InvalidAppException

    当客户端提供了错误的 app\_id 或 app\_secret 时，抛出 `InvalidAppException` 异常，如果不进行任何额外的操作，默认将返回 `{"code":5,"message":"Invalid App Info"}`
- CreateAppException

    当服务端生成 app 失败时，抛出 `CreateAppException` 异常，如果不进行任何额外的操作，默认将返回 `{"code":6,"message":"xxxx"}`

*以上异常如果不想使用默认的信息，均可自行捕获更改相关信息*

License
-------

[](#license)

MIT

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

3005d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8762b660ee15e4d5000552eceaad37b42cb1f46bb67b29c9f07e7f31a3712250?d=identicon)[yansongda](/maintainers/yansongda)

---

Top Contributors

[![yansongda](https://avatars.githubusercontent.com/u/11869114?v=4)](https://github.com/yansongda "yansongda (34 commits)")

---

Tags

apilaravelaccess token

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/yansongda-laravel-api/health.svg)

```
[![Health](https://phpackages.com/badges/yansongda-laravel-api/health.svg)](https://phpackages.com/packages/yansongda-laravel-api)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[essa/api-tool-kit

set of tools to build an api with laravel

53386.5k](/packages/essa-api-tool-kit)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6783.6k5](/packages/hasinhayder-tyro)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[simplestats-io/laravel-client

Analytics for Laravel. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant, ad-blocker proof.

5019.3k](/packages/simplestats-io-laravel-client)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
