Google oauth getAccessToken()null

时间:2018-08-21 05:15:21

标签: php laravel laravel-5 google-api

我想将google oauth添加到我的Web应用程序中,我已经使用php客户端库遵循有关google oauth的google文档,但是我遇到了问题

这是我的代码

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

如何修复?

1 个答案:

答案 0 :(得分:1)

我认为问题在于您没有向Google提出要求以进行身份​​验证并取回令牌。您应该这样做:

$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() );

如果身份验证成功,则Google会将您重定向到您使用$client->setRedirectUri($redirect)设置的页面。

在该页面中,您可以:

//authenticate using the parameter $_GET['code'] you got from google server
$client->authenticate( $request->input('code') );

//get the access token
$tokens = $client->getAccessToken();