google-api-php-client-0.5.0 callbackurl? - php

I am new to integrating api and I am trying to working with the google-api-php-client-0.6.0 and I registered my app at Google and also configured them in simple.php in dev.siva.com virtual host
<?php
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once 'src/Google_Client.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/contacts/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
} else {
print "<a class=logout href='?logout'>Logout</a>";
}
I am able to login and I gave the redirect url to above code and I am being redirected but the problem is I am getting unable to connect page. Why?
The url is like this after redirection
https://dev.siva.com/simple.php?code=4/hqJo9FDtjcn46uuP6JXE
DuWLKTQn.Eo91flf65bgaXE-sT2ZLcbRbNNSqdQI

You can not use virtual host as redirect uri - refer https://developers.google.com/accounts/docs/OAuth2InstalledApp for more details. So you have two options - process it on {http://localhost} or get the code in title bar instead of query parameter. I would choose the first.

Related

Third Party Youtube API Video upload Skript stuck on authorize access

I'm trying to upload Videos via a PHP Script using the YouTube API V3 with a free third party Script. I have been through multiple Scripts including the YouTube code snippets but this one seems to be the one fitting my needs the most.
The Problem I have right now is, that the script seems stuck in a cycle of granting access, starting over and requesting access again without ever uploading a video.
Besides, this script specifically aims for only having to grant access once, which is exactly what I need.
I already asked for help on the 3rd party site, sadly got no response yet.
We have configured the Application, got the correct credentials, setup the redirct URI etc apparently correct, since we do get responses allowing us to authorize the Application to use the YouTube Account/Channel.
It seems the script cannot get an accessToken via the API method.
The original Code can be found at:
https://artisansweb.net/use-youtube-api-upload-video-youtube-channel/
What fails for seems to be this:
$client->getAccessToken();
There is an if else construct and the script always uses the else part.
if ($client->getAccessToken()) {...}
else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
The function getAccessToken() is provided by the youtube API.
I have been through the process of authorizing the App multiple times over the course of multiple days but still it wont work.
I can't figure out why and where this process fails and would appreciate any help regarding this. All I initially needed was a script to upload videos to YouTube , with only having to grant access once.
But as described the Script is stuck on the granting access part. I would appreciate it if anyone could point me to the Problem or could point me to another Script I could use to achieve this.
This is the code i use for authorization.
Oauth2Authentication.php
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* #return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* #return A google client object.
*/
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
oauth2callback.php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
For upload i would follow large-file-upload.php

Getting started wtih Google Management API (PHP - Web Server) - Error 500

Following the Google documentation for Web Server PHP flow located here, I was able to successfully prompt user login with oauth2callback.php. However, returning to the original site after authentication throws an internal server error 500 and does not display the GA results from profile obtained as intended.
How do I know what caused the issue?
Note: Code is taken directly from Google Documentation for Web Server PHP flow with minor adjustments to my own project's parameters.
testoauth.php
<?php
// Load the Google API PHP Client Library.
require_once '../application/third_party/vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfig('../application/views/dashboard/client_secret_file.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$results = getResults($analytics, $profile);
printResults($results);
}
else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '../application/views/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstProfileId($analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults($analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults($results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
?>
oauth2callback.php
<?php
// Load the Google API PHP Client Library.
require_once '../application/third_party/vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig('../application/views/dashboard/client_secret_file.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '../application/views/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '../application/views/testoauth.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
Its hard to know what could be wrong with your code without you debugging your way though it. It is possible that that code has not been updated and the library has changed. This is the code from my sample project it was generated recently. There is a Read men on how to use the samples here
Oauthcallback.php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Oauth2Authentication.php
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* #return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* #return A google client object.
*/
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Then you can check my sample project for more examples here is one on accountsummiries.list

OAuth 2.0 google

I'm trying to create an authentication with google API. I always get my page refreshed I can't get access to the user information I see always the two alerts "here 1" and "here 2" any idea to help ?
<?php
/* GOOGLE LOGIN BASIC - Tutorial
* file - index.php
* Developer - Krishna Teja G S
* Website - http://packetcode.com/apps/google-login/
* Date - 28th Aug 2015
* license - GNU General Public License version 2 or later
*/
// REQUIREMENTS - PHP v5.3 or later
// Note: The PHP client library requires that PHP has curl extensions configured.
/*
* DEFINITIONS
*
* load the autoload file
* define the constants client id,secret and redirect url
* start the session
*/
require_once __DIR__.'/gplus-lib/vendor/autoload.php';
const CLIENT_ID = 'my code';
const CLIENT_SECRET = 'my code';
const REDIRECT_URI = 'http://www.servicebigdeals.com/google-login/';
session_start();
/*
* INITIALIZATION
*
* Create a google client object
* set the id,secret and redirect uri
* set the scope variables if required
* create google plus object
*/
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes('email');
$plus = new Google_Service_Plus($client);
/*
* PROCESS
*
* A. Pre-check for logout
* B. Authentication and Access token
* C. Retrieve Data
*/
/*
* A. PRE-CHECK FOR LOGOUT
*
* Unset the session variable in order to logout if already logged in
*/
if (isset($_REQUEST['logout'])) {
session_unset();
}
/*
* B. AUTHORIZATION AND ACCESS TOKEN
*
* If the request is a return url from the google server then
* 1. authenticate code
* 2. get the access token and store in session
* 3. redirect to same url to eliminate the url variables sent by google
*/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
else {
echo "<script>alert(\"here 1 \")</script>";
}
/*
* C. RETRIEVE DATA
*
* If access token if available in session
* load it to the client object and access the required profile data
*/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$me = $plus->people->get('me');
// Get User data
$id = $me['id'];
$name = $me['displayName'];
$email = $me['emails'][0]['value'];
$profile_image_url = $me['image']['url'];
$cover_image_url = $me['cover']['coverPhoto']['url'];
$profile_url = $me['url'];
}
else {
echo "<script>alert(\"here 2 \")</script>";
// get the login url
$authUrl = $client->createAuthUrl();
}
?>
<!-- HTML CODE with embedded PHP-->
<div>
<?php
/*
* If login url is there then display login button
* else print the retrieved data
*/
if (isset($authUrl)) {
echo "<a class='login' href='" . $authUrl . "'><img src='gplus-lib/signin_button.png' height='50px'/></a>";
} else {
print "ID: {$id} <br>";
print "Name: {$name} <br>";
print "Email: {$email } <br>";
print "Image : {$profile_image_url} <br>";
print "Cover :{$cover_image_url} <br>";
print "Url: {$profile_url} <br><br>";
echo "<a class='logout' href='?logout'><button>Logout</button></a>";
}
?>
</div>

(403) Daily Limit for Unauthenticated Use Exceeded when using google-api-php-client

My objective is to create the simplest SQL query on Goolge Funsion tables API.
To do that, I installed the google-api-php-client and I tried this code below:
$client_id = '<client_id>';
$client_secret = '<client_secret>';
$redirect_uri = '<redirecti_uri>';
$client = new \Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
//$client->setScopes('email');
$client->setScopes(
array(
'https://www.googleapis.com/auth/fusiontables',
'https://www.googleapis.com/auth/fusiontables.readonly',
)
);
$service = new \Google_Service_Fusiontables($client);
$sql = 'select name from <my_table>';
$result = $service->query->sql($sql);
return $this->render("MinnAdsBundle:Motors:test3.html.twig",
array('result'=> var_dump($result)));
I got this error:
Error calling POST https://www.googleapis.com/fusiontables/v1/query: (403) Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
500 Internal Server Error - Google_Service_Exception
Any ideas to get auth for the query?
Thanks
You cant query the service at this time, the authentication hasn't been finished there(you've ommitted the complete authentication-process in your code).
modified user-example.php(there are 2 comments starting with //!!! to mark the notable changes):
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include_once "templates/base.php";
session_start();
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Fusiontables.php';
/************************************************
ATTENTION: Fill in these values! Make sure
the redirect URI is to this page, e.g:
http://localhost:8080/user-example.php
************************************************/
$client_id = '<YOUR_CLIENT_ID>';
$client_secret = '<YOUR_CLIENT_SECRET>';
$redirect_uri = '<YOUR_REDIRECT_URI>';
/************************************************
Make an API request on behalf of a user. In
this case we need to have a valid OAuth 2.0
token for the user, so we need to send them
through a login flow. To do this we need some
information from our API console project.
************************************************/
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(
array(
'https://www.googleapis.com/auth/fusiontables',
'https://www.googleapis.com/auth/fusiontables.readonly',
)
);
/************************************************
When we create the service here, we pass the
client to it. The client then queries the service
for the required scopes, and uses that when
generating the authentication URL later.
************************************************/
//!!!here only create the service
$service = new Google_Service_Fusiontables($client);
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
/************************************************
If we're signed in and have a request to shorten
a URL, then we create a new URL object, set the
unshortened URL, and call the 'insert' method on
the 'url' resource. Note that we re-store the
access_token bundle, just in case anything
changed during the request - the main thing that
might happen here is the access token itself is
refreshed if the application has offline access.
************************************************/
if ($client->getAccessToken() ) {
//!!!here send the query and do something with $result
$sql = 'select * from <my_table>';
$result = $service->query->sql($sql);
$_SESSION['access_token'] = $client->getAccessToken();
}
echo pageHeader("User Query - Fusiontables");
if (
$client_id == '<YOUR_CLIENT_ID>'
|| $client_secret == '<YOUR_CLIENT_SECRET>'
|| $redirect_uri == '<YOUR_REDIRECT_URI>') {
echo missingClientSecretsWarning();
}
?>
<div class="box" style="width:80%">
<div class="request">
<?php if (isset($authUrl)): ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php endif ?>
</div>
<?php if (isset($result)): ?>
<pre style="overflow:auto;height:500px;">
<?php echo htmlentities(print_r($result,true)); ?>
</pre>
<?php endif ?>
</div>

Uncaught exception 'Google_Auth_Exception' with message 'Could not json decode the token'

I am using the user-example.php in the google-api-client-php library and it is throwing up the error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Could not json decode the token' in /Applications/XAMPP/xamppfiles/htdocs/Calendar/google-api-php-client/src/Google/Auth/OAuth2.php:174 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/Calendar/google-api-php-client/src/Google/Client.php(196): Google_Auth_OAuth2->setAccessToken('[]') #1 /Applications/XAMPP/xamppfiles/htdocs/calendar/google-api-php-client/examples/user-example.php(80): Google_Client->setAccessToken('[]') #2 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/Calendar/google-api-php-client/src/Google/Auth/OAuth2.php on line 174
the code of the example is
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include_once "templates/base.php";
session_start();
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Urlshortener.php';
/************************************************
ATTENTION: Fill in these values! Make sure
the redirect URI is to this page, e.g:
http://localhost:8080/user-example.php
************************************************/
$client_id = '<XXXXX>';
$client_secret = '<XXXXX>';
$redirect_uri = '<XXXXXX>';
/************************************************
Make an API request on behalf of a user. In
this case we need to have a valid OAuth 2.0
token for the user, so we need to send them
through a login flow. To do this we need some
information from our API console project.
************************************************/
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/urlshortener");
/************************************************
When we create the service here, we pass the
client to it. The client then queries the service
for the required scopes, and uses that when
generating the authentication URL later.
************************************************/
$service = new Google_Service_Urlshortener($client);
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
/************************************************
If we're signed in and have a request to shorten
a URL, then we create a new URL object, set the
unshortened URL, and call the 'insert' method on
the 'url' resource. Note that we re-store the
access_token bundle, just in case anything
changed during the request - the main thing that
might happen here is the access token itself is
refreshed if the application has offline access.
************************************************/
if ($client->getAccessToken() && isset($_GET['url'])) {
$url = new Google_Service_Urlshortener_Url();
$url->longUrl = $_GET['url'];
$short = $service->url->insert($url);
$_SESSION['access_token'] = $client->getAccessToken();
}
echo pageHeader("User Query - URL Shortener");
if (
$client_id == '<YOUR_CLIENT_ID>'
|| $client_secret == '<YOUR_CLIENT_SECRET>'
|| $redirect_uri == '<YOUR_REDIRECT_URI>') {
echo missingClientSecretsWarning();
}
?>
<div class="box">
<div class="request">
<?php if (isset($authUrl)): ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php else: ?>
<form id="url" method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="url" class="url" type="text">
<input type="submit" value="Shorten">
</form>
<a class='logout' href='?logout'>Logout</a>
<?php endif ?>
</div>
<?php if (isset($short)): ?>
<div class="shortened">
<?php var_dump($short); ?>
</div>
<?php endif ?>
</div>
<?php
echo pageFooter(__FILE__);
Can anyone shed any light as to why i might be receiving this error? I'm sure i have all my access tokens set up correctly. I had a problem in my own code, but I can't seem to get Google's own example working.
I have encountered the same problem. It seems that the latest Google API PHP library is expecting a json encoded token in the setAccessToken method. So what I did as a work around was encoded the tokens to json.
// $token could be retrieved from your SESSION cookie or from your DB.
$token = array(
'access_token' => 'XXXXXXX',
'refresh_token' => 'XXXXXXX');
$json_token = json_encode($token);
$client->setAccessToken($json_token);
Hope this helps.
Could you Copy-paste your $_SESSION['access_token']?
Try with this:
http://php.net/manual/es/function.json-last-error.php
In your code, change:
json_decode($_SESSION['access_token']);
if (isset($_SESSION['access_token']) && $_SESSION['access_token'] && !json_last_error()) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}

Categories