首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Google oauth getAccessToken() null

Google oauth getAccessToken() null
EN

Stack Overflow用户
提问于 2018-08-21 05:15:21
回答 1查看 1.3K关注 0票数 1

我想将google oauth添加到我的web应用程序中,我已经遵循了google文档中关于google oauth与php客户端库的说明,但我遇到了问题

下面是我的代码

代码语言:javascript
运行
AI代码解释
复制
public function googleOauth() {
        $client = new Google_Client();
        $client->setAuthConfig(base_path('google_client.json'));
        //$client->setAccessType("offline");
        $client->setIncludeGrantedScopes(true); 
        $client->addScope(Google_Service_Blogger::BLOGGER);
        $client->setRedirectUri(route('googleOauthCallback'));

        return redirect($client->createAuthUrl());
    }

    public function googleOauthCallback(Request $params) {
       if ($params->code) {
          $client = new Google_Client();
          $client->authenticate($params->code);

          dd($client->getAccessToken());
       }

但是$client->getAccessToken()返回null

如何修复它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-21 08:49:45

我认为问题是你没有向谷歌提出认证和取回令牌的请求。您应该执行以下操作:

代码语言:javascript
运行
AI代码解释
复制
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = url('/');
$client->setRedirectUri($redirect);

//redirect to google server to get the token 
return Redirect::to( $client->createAuthUrl() );

如果认证成功,谷歌会将你重定向到你用$client->setRedirectUri($redirect)设置的页面。

在该页面中,您可以:

代码语言:javascript
运行
AI代码解释
复制
//authenticate using the parameter $_GET['code'] you got from google server
$client->authenticate( $request->input('code') );

//get the access token
$tokens = $client->getAccessToken();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51941974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文