Google API - request for token from Oauth2 returns null token

↘锁芯ラ 提交于 2019-12-11 13:51:57

问题


For credentials, I have created an developer account on https://console.developers.google.com, I have created a project and then i have created credentials from API Manager. I use "google/apiclient": "1.1.*" package. I think it is a problem with credentials.

    $OAUTH2_CLIENT_ID = 'XXXXX-rvm1l9b1nvht9je1ic0bbe05ab5gvhbg.apps.googleusercontent.com';
    $OAUTH2_CLIENT_SECRET = 'XXXXXXP90L_DLD3Nrc_rT4zGD';

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


    $token = $client->getAccessToken();
    dd($token);

回答1:


I think the problem is you're not making the request to Google to authenticate and get back the token. You should do:

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

If the authentication succeeds, google will redirect you to the page you set with $client->setRedirectUri($redirect).

In that page you can:

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

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



回答2:


Tip:

Don't use:

$client->authenticate($authcode);
$token = $client->getAccessToken();

Use:

 $token = $client->fetchAccessTokenWithAuthCode($authcode);

This will at least allow you to see the error message if you dump $token. In the 'Don't use:' example, if the authenticate() step fails, getAccessToken() may return null. Bad job on the API here.



来源:https://stackoverflow.com/questions/35937293/google-api-request-for-token-from-oauth2-returns-null-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!