Home » Php » php – Wrong number of segments in token (OAuth Google Api)

php – Wrong number of segments in token (OAuth Google Api)

Posted by: admin July 12, 2020 Leave a comment


My end goal is to send email to myself via Google Gmail API.

And here is my problem.

When i’m getting my access token an error pops up

 Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Wrong number of segments in token: '

I read here Cloud endpoints oauth2 error that “This DOES NOT mean your token was invalid”, but i’m getting a fatal error that interrupting my script.

My access token looks like this 4/MqiIIl5K4S3D4iiieHshQt5D4M79oo07SbhMn22oe2o.cswa8t9ZuDAfJvIeHux6iLYXpNQmlAI

If I refresh the page with this token i’d get another error, which is

'Error fetching OAuth2 access token, message: 'invalid_grant: Invalid code.'

Here is my code


include_once "templates/base.php";
echo pageHeader("Simple API Access");

require_once realpath(dirname(__FILE__) . '/../autoload.php');

$client = new Google_Client();

$client_id = '114600397795-j5sn0gvsdrup0s8dcmsj49iojp3m9biu.apps.googleusercontent.com';
$client_secret = 'm3Dzankql_rs1OGICsA3Hbtc';
$redirect_uri = 'http://alupa.com/gmail/examples/simple-query.php';



$apiKey = "AIzaSyCWXxrTshKsotxEYNZZCXxdVXhLeku55cw"; 

if (isset($_GET['code'])) {
  $_SESSION['access_token'] = $client->getAccessToken();
  //$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  //header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));



if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
} else {
  $authUrl = $client->createAuthUrl();

if ($client->getAccessToken()) {
  $_SESSION['access_token'] = $client->getAccessToken();
  $token_data = $client->verifyIdToken()->getAttributes();

<div class="box">
  <div class="request">
if (isset($authUrl)) {
  echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
} else {
  echo "<a class='logout' href='?logout'>Logout</a>";

alupa.com is my local domain and I don’t see any problems with that

I’m using original library from google https://github.com/google/google-api-php-client

How to&Answers:


$token_data = $client->verifyIdToken()->getAttributes();


$tuan = $client->getAccessToken();
$token_data = $client->verifyIdToken($tuan->id_token);


You need to add the scope openid and then you get an id_token as well as the access token. You then use the id token with $client->verifyIdToken