项目作者: fmwww

项目描述 :
Wechat Oauth Grant For Passport
高级语言: PHP
项目地址: git://github.com/fmwww/passport-wechat-oauth-grant.git
创建时间: 2018-03-25T08:31:37Z
项目社区:https://github.com/fmwww/passport-wechat-oauth-grant

开源协议:

下载


passport-wechat-oauth-grant

增加一个可以通过微信Oauth授权code登录passport的Grant

安装

通过Composer安装

  1. $ composer require fmwww/passport-wechat-oauth-grant

如果你的Laravel版本 < 5.5, 你需要在 config/app.php 的providers数组中增加:

  1. Fmwww\PassportWechatOauthGrant\WechatOauthGrantServiceProvider::class,

配置

使用之前需要先配置好微信的 app_idapp_secret
使用下面的命令拷贝配置文件到 config :

  1. $ php artisan vendor:publish --provider="Fmwww\PassportWechatOauthGrant\WechatOauthGrantServiceProvider"
  1. return [
  2. /*
  3. * 微信app_id
  4. */
  5. 'app_id' => env('WECHAT_OAUTH_GRANT_APP_ID', ''),
  6. /*
  7. * 微信app_secret
  8. */
  9. 'app_secret' => env('WECHAT_OAUTH_GRANT_APP_SECRET', ''),
  10. ];

推荐使用 .env 文件进行配置

用法

  • 使用POST方法去请求https://your-site.com/oauth/token
  • POST请求体里的需要将grant_type设置为wechat_oauth,同时将code设置为微信返回的授权code
  • 系统将会根据 config/auth.php里面的 api guard 设置的用户模型去寻找用户,如果用户模型定义了 findForWechatOauth 方法,那么就会使用这个方法返回的用户进行认证,否则就会根据openid字段去寻找用户进行认证。
  • 如果用户存在,就会成功返回 access_tokenrefresh_token

    例子

    请求方法

    ```php
    $http = new GuzzleHttp\Client;

$response = $http->post(‘http://your-app.com/oauth/token‘, [
‘form_params’ => [
‘grant_type’ => ‘wechat_oauth’,
‘client_id’ => ‘client-id’,
‘client_secret’ => ‘client-secret’,
‘code’ => ‘001qJKS42a3r3N0wrDU42IHrS42qJKSN’, #微信的授权code
‘scope’ => ‘’,
],
]);

return json_decode((string) $response->getBody(), true);

  1. #### 自定义 `findForWechatOauth`方法
  2. ```php
  3. public function findForWechatOauth($tokens)
  4. {
  5. // 获取openid
  6. $openid = $tokens->openid;
  7. // 获取access_token
  8. $access_token = $tokens->access_token;
  9. // 获取expires_in
  10. $expires_in = $tokens->expires_in;
  11. // 获取refresh_token
  12. $refresh_token = $tokens->refresh_token;
  13. // 获取scope
  14. $scope = $tokens->scope;
  15. // 通过openid查找,如果这个方法没有定义,默认就是这样查找
  16. $user = $this->where('openid', $openid)->first();
  17. // 你也可以自己创建用户然后返回
  18. if (empty($user)) {
  19. $this->openid = $openid;
  20. $this->save();
  21. }
  22. // 返回用户
  23. return $user ?: $this;
  24. }