Invalid token format in Google API - php

there i found some error, when i want to make sure the session on Login with google account. And the error is :
Fatal error: Uncaught InvalidArgumentException: Invalid token format in C:\xampp\htdocs\google\googleAPI\src\Google\Client.php:434 Stack trace: #0 C:\xampp\htdocs\google\callback.php(5): Google_Client->setAccessToken(Array) #1 {main} thrown in C:\xampp\htdocs\google\googleAPI\src\Google\Client.php on line 434
and then this is my code :
<?php
require_once('config.php');
if (isset($_SESSION['accessToken'])){
$client->setAccessToken($_SESSION['accessToken']);
}
else if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['accessToken'] = $token;
}
else{
header("location: index.php");
}
$oAtuth = new Google_Service_Oauth2($client);
$user = $oAtuth->userinfo->get();
echo "<pre>";
print_r($user);
?>
Please tell me whats wrong with this code

You have wrong value of token in $_SESSION['accessToken'].

Related

Spotify request access token is not working when refresh url

Right now i am working on spotify api, When i hit url for first time it is giving me all playlist but when i refresh page again it is giving me exception error, here is my code,
require '../../../vendor/autoload.php';
$session = new SpotifyWebAPI\Session('******', '*******', 'http://localhost:8080/spotify/vendor/jwilsson/spotify-web-api-php/demo.php');
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$data = $api->setAccessToken($session->getAccessToken());
$artistData = $api->me();
$artistId = $artistData->id;
$playlists = $api->getUserPlaylists($artistId, array(
'limit' => 5
));
foreach ($playlists->items as $playlist) {
echo '' . $playlist->name . ' <br>';
}
} else {
$scopes = array(
'scope' => array(
'user-read-email',
'user-library-modify',
),
);
header('Location: ' . $session->getAuthorizeUrl($scopes));
}
Here is my exception error
Fatal error: Uncaught exception 'SpotifyWebAPI\SpotifyWebAPIException' with message 'Invalid authorization code' in D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Request.php:156 Stack trace: #0 D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Request.php(26): SpotifyWebAPI\Request->send('POST', 'https://account...', Array, Array) #1 D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Session.php(233): SpotifyWebAPI\Request->account('POST', '/api/token', Array) #2 D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\demo.php(31): SpotifyWebAPI\Session->requestAccessToken('AQAaVZvpXUExKg2...') #3 {main} thrown in D:\xampp\htdocs\spotify\vendor\jwilsson\spotify-web-api-php\src\Request.php on line 156
Can anyone please tell me why it cause error ? If anyone have experiance with spotify
Creator of the library here.
The only thing I can think of which would yield that error message is if you try to request a access token twice with the same code. Try visiting the URL to your PHP file again but remove any ?code=... parts.

USING OAUTH2 TO GET USER CONTACT LIST

I am trying to access a users contact list using google Oauth2 but seem to be running into an error insufficient permision. My code is as below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Google extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
require_once 'google-api-php-client/autoload.php'; // or wherever
autoload.php is located
$client = new Google_Client();
$scriptUri = "http://localhost/tcaller/google/";
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('Tcaller');
$client->setClientId('******');
$client->setClientSecret('****');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('******'); // API key
$client->setScopes(array('https://www.google.com/m8/feeds' , 'https://www.googleapis.com/auth/contacts.readonly'));
$plus = new Google_Service_Plus($client);
if (isset($_GET['logout'])) { // logout: destroy token
$this->session->unset_userdata("token");
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$tokenArr = array('token' => $client->getAccessToken());
$this->session->set_userdata($tokenArr);//gets valid access token
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //set into session storage
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if ($this->session->userdata('token')) { // extract token from session and configure client
$token = $this->session->userdata('token');
$client->setAccessToken($token);
try {
$me = $plus->people->get('me');
print_r($me);
} catch (apiServiceException $e) {
// Handle exception. You can also catch Exception here.
// You can also get the error code from $e->getCode();
echo 'error';
}
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die();
}
}
}
?>
I am getting the error
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https://www.googleapis.com/plus/v1/people/me?key=%2A%2A%2A%2A%2A%2A:
(403) Insufficient Permission' in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php:111
Stack trace: #0
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(63):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]:
Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request)) #2
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Task\Runner.php(172):
call_user_func_array(Array, Array) #3
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(47):
Google_Task_Runner->run() #4
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Client.php(564):
Google_Http_REST::execute(Object(Google_Client), Object(Google_H in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php
on line 111
Am i missing something
You should not need to use a separate API key and call $client->setDeveloperKey() as you're obtaining and using an OAuth 2.0 access token already with a client secret. Moreover, it seems that that is incorrect and/or not associated with the same project. So please try with that call removed.

How to store authenticated users access token from Instagram using PHP API

I'm creating a simple page to display my current photos from my Instragram account. I'm using cosenary's Instagram PHP API (instagram.class.php) from https://github.com/cosenary/Instagram-PHP-API
Upon successful login the success page displayed correctly. But when I refresh the page again, it displayed this error message:
Fatal error: Uncaught exception 'Exception' with message 'Error: _makeCall() | users/self/media/recent - This method requires an authenticated users access token.' in /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php:432
Stack trace: #0 /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php(148): Instagram->_makeCall('users/self/medi...', true, Array) #1 /home/teammond/public_html/projects/amacc/it321/final/success/index.php(40): Instagram->getUserMedia() #2 {main} thrown in /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php on line 432
I tried placing what I think were the tokens in PHP sessions but still to no avail.
This the PHP code from my success page (redirect_uri):
<?php
session_start();
require_once '../instagram.class.php';
// initialize class
$instagram = new Instagram(array(
'apiKey' => '010d47aaccf945559ae9ded9d0aa7459',
'apiSecret' => '{omitted}',
'apiCallback' => 'http://projects.teammondestars.com/amacc/it321/final/success'
));
// receive OAuth code parameter
$code = $_GET['code'];
if (!isset($_SESSION['oauth'])) {
$_SESSION['oauth'] = $code;
}
// check whether the user has granted access
if (isset($_SESSION['oauth'])) {
// receive OAuth token object
$data = $instagram->getOAuthToken($_SESSION['oauth'], true);
$username = $username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
if (!isset($_SESSION['token'])) {
$_SESSION['token'] = $instagram->getAccessToken();
}
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
?>

Google Analytics API - problems with refreshing token

I'm writing a Wordpress plugin which displays visits on a page. Everything's done and it works perfectly... for an hour. I can't refresh the token when it expires, so the end-user can't see Analytics results. I don't know what am I doing wrong, maybe I misunderstood the authentication process.
This is how I manage the first connection to the API:
$client->setClientId(get_option('client_ID'));
$client->setClientSecret(get_option('client_secret'));
$client->setRedirectUri(get_option('redirectURI'));
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline');
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'><button>Authorize Google</button></a>";
And then i do this:
try {
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
update_option('token', $_SESSION['token']);
$tok = json_decode($_SESSION['token']);
update_option('refresh_token', $tok->refresh_token);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
?><script type="text/javascript">
window.location="<?php filter_var($redirect, FILTER_SANITIZE_URL)?>";
</script><?php
}
if (isset($_SESSION['token'])) {
update_option('token', $_SESSION['token']);
$client->setAccessToken($_SESSION['token']);
}
} catch (Google_AuthException $e){
return FALSE;
}
This works fine. Now here's the part, where it should use the token thats stored as an option and if it expired, use refresh_token to get a new one automatically. Here's the code:
$client = new Google_Client();
$client->setApplicationName('AnalyticsPK Plugin for Wordpress');
$client->setClientId(get_option('client_ID'));
$client->setClientSecret(get_option('client_secret'));
$client->setRedirectUri(get_option('redirectURI'));
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline');
$client->setApprovalPrompt("force");
echo "Token: ".get_option('token')."<br>";
echo "Refresh token: ".get_option('refresh_token')."<br>";
$client->setAccessToken(get_option('token'));
if ($client->isAccessTokenExpired()){
echo "Token expired <br>";
$client->refreshToken(get_option('refresh_token'));
echo "New token: ".$client->getAccessToken();
}
//echo "Token: ".get_option('token');
//echo "Refresh token: ".get_option('refresh_token');
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
$analytics = new Google_AnalyticsService($client);
When the token expiration time passes, I get an error:
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error refreshing the OAuth2 token, message: '{ "error" :
"invalid_request", "error_description" : "Client must specify either
client_id or client_assertion, not both" }'' in
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/auth/Google_OAuth2.php:288
Stack trace: #0
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/auth/Google_OAuth2.php(248):
Google_OAuth2->refreshTokenRequest(Array) #1
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/Google_Client.php(311):
Google_OAuth2->refreshToken('1/XCyf8ofh6H3kL...') #2
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/AnalyticsPK.php(90):
Google_Client->refreshToken('1/XCyf8ofh6H3kL...') #3
/_wpsu/analytics/wp-includes/widgets.php(182):
AnalyticsPK->widget(Array, Array) #4 [internal function]:
WP_Widget->display_callback(Array, Array) #5
/_wpsu/analytics/wp-includes/widgets.php(895):
call_user_func_array(Array, Array) #6 /_wpsu/analytics/ in
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/auth/Google_OAuth2.php
on line 288
What am I doing wrong with refreshing the token?

Fatal error: Uncaught exception 'Google_IOException'

I am trying to make work a php code for listing the users of a google user. I have followed a youtube tutorial and tryed the solutions proposed in this one But I still get this annoying error when I call the authenticate method :
Fatal error: Uncaught exception 'Google_IOException' with message 'HTTP Error: (0) couldn't connect to host' in D:\xampp\htdocs\yac\proxy\lib\google-api-client\io\Google_CurlIO.php:128 Stack trace: #0 D:\xampp\htdocs\yac\proxy\lib\google-api-client\auth\Google_OAuth2.php(103): Google_CurlIO->makeRequest(Object(Google_HttpRequest)) #1 D:\xampp\htdocs\yac\proxy\lib\google-api-client\Google_Client.php(131): Google_OAuth2->authenticate(Array, NULL) #2 D:\xampp\htdocs\yac\proxy\contacts.php(36): Google_Client->authenticate() #3 {main} thrown in D:\xampp\htdocs\yac\proxy\lib\google-api-client\io\Google_CurlIO.php on line 128
here is my PHP code :
<?php
session_start();
require_once 'lib/google-api-client/Google_Client.php';
$client = new Google_Client();
$client->setApplicationName("Contactoos");
$client->setClientId('*************************************');
$client->setClientSecret('*********************************');
$client->setScopes(array('http://www.google.com/m8/feeds'));
$client->setRedirectUri('http://localhost/yac/proxy/contacts.php');
$client->setAccessType('online');
if(isset($_GET['code']))
{
echo "here";
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('location:http://localhost/yac/proxy/contacts.php');
}
if(!isset($_SESSION['token']))
{
$url = $client->createAuthUrl();
?>
List google contacts
<?php
}
else
{
$client->setAccessToken($_SESSION['token']);
}
?>
As I said, I tried the solutions proposed in the second tutorial but in vain.
Does anyone know how to fix this problem ?
Thanks.
It looks like your server is having issues connecting to www.googleapis.com. You will need to check your network connection.
See if you're able to visit https://www.googleapis.com/discovery/v1/apis from that machine.
If you are using a proxy then you need to add curl_setopt($ch, CURLOPT_PROXY, 'your-proxy-settings'); to Google_CurlIO.php.
I've added it on line 111, after curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());

Categories