refreshTokenWithAssertion Permission Denied - google-oauth

I am trying to use google-api-client in PHP for a project.
I got a "permission denied" response while at this statement:
$client->getAuth()->refreshTokenWithAssertion();
Google_IO_Exception, Message:Failed to connect to 74.125.193.84: Permission denied
File: /home/www/blah.com/restful/libs/Google/IO/Curl.php
Line:81
/home/www/blah.com/restful/libs/Google/IO/Abstract.php(125): Google_IO_Curl->executeRequest(Object(Google_Http_Request))
#1 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(326): Google_IO_Abstract->makeRequest(Object(Google_Http_Request))
#2 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(306): Google_Auth_OAuth2->refreshTokenRequest(Array)
#3 /home/www/blah.com/restful/v2/index.php(122): Google_Auth_OAuth2->refreshTokenWithAssertion()
I checked all my credentials and they look correct, what could be the problem?
Thanks,
John
code:
$client_id = '1234blahblahblah.apps.googleusercontent.com'; //Client ID
$service_account_name = '1234blahblah#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'blahblah-1234.p12'; //key.p12
$client = new Google_Client();
$client->setApplicationName("test");
$service = new Google_Service_Calendar($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
print_r($cred);
$client->setAssertionCredentials($cred);
$client->setClientId($client_id);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
}
$_SESSION['service_token'] = $client->getAccessToken();
echo $_SESSION['service_token'];
}

Hi John I´ve the same problem and finally this works for me:
Before the lines:
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
}
I put a try catch and that returns me that I had a writtin permissions problem:
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
I could do 2 things:
1) Go to Google/src/Config.php and change line 94: 'directory' => sys_get_temp_dir() . '/Google_Client'and change the directory to save cache temp files
2) or like me, made a echo sys_get_temp_dir(); before the try catch and give a chmod 777 permission to that dir
This solution works for me, I hope also for you. Anyway made an try/catch waiting for the exception message

See the service-account.php sample in the examples/ directory of the Google APIs Client Library for PHP on Github.com:
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred); // set credentials there
}

Related

cookies on localhost and hosting

My code is running smoothly on localhost. But it doesn't work on the web server; cookies are not saved.
if (isset($_POST['user-login-form'])) {
$user_mail = strip_tags(trim($_POST['l_email']));
$user_password = strip_tags(sha1(md5($_POST['l_password'])));
$usercontrol=$db->prepare("SELECT * FROM users where user_mail=:user_mail and user_password=:user_password");
$usercontrol->execute(array( 'user_mail' => $user_mail, 'user_password' => $user_password ));
$userresult=$usercontrol->rowCount();
if ($userresult==1) {
$_SESSION['user_mail']=$user_mail;
$_SESSION['user_password']=$user_password;
if(isset($_POST['checkremember'])){
setcookie("user_remember",$user_mail,strtotime("+10 week"));
} else {
setcookie("user_remember",$user_mail,strtotime("-10 week"));
}
echo "2";
exit;
} else {
echo "1";
exit;
}
}
Previously it worked without problems. I installed an SSL certificate and made several changes to the .htaccess file.
But when you type this on a blank page, the cookie is registered.
Code:
setcookie("user_remember", "deneme", time() + (86400 * 30), "/");
echo $_COOKIE["user_remember"];
my problem is solved.
the problem is that the php file is utf-8 BOM.

Magento Soap API 1.9 - failed to load external entity

when i tried to connect to Soap Api, i'm getting this error :
SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl' : failed to load external entity "https://www.lignedublanc.fr/index.php/api/soap/?wsdl
i tried with soap UI and same errors.
i tried everything on the net but nothing helped.
Maybe someone here can help me ?
<?php
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$url = 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl=1';
$MagentoAPILogin = '';
$MagentoAPIPass = '';
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
try {
echo "Connecting to : $url\n";
//$client = new SoapClient($url);
$client = new SoapClient($url, ['stream_context' => $context]);
echo $client->login($MagentoAPILogin, $MagentoAPIPass)."\n";
echo 'Login successful';
} catch (Exception $e) {
echo 'Login fail'."\n";
echo $e->getMessage()."\n";
echo $e->getTraceAsString()."\n";
}
I believe the problem is caused by the server not being able to access the API from the local machine. It is actually the .htaccess file that blocking any hosts except the development machines. Hence, it results in a 403 Forbidden error which is actually the SOAP error. For more reference, have a look:
Unable to connect to Magento SOAP API v2 due to "failed to load external entity"

how to handle error 500 when requesting a distant server with guzzle?

i am requesting a webservice using :
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
try {
$client = new Client();
$response = $client->request('GET', $url); //it crashes at this line
$content = json_decode($response->getBody(), true);
}
catch (ConnectException $e) {
\Drupal::logger('amu_hal')->error('incorrect_url'.$url);
}
today the distant server return a error 500.
How can i modify my code not to crash my site when it happens?
I assume that by distant server you mean a server that takes a long time to connect. You can specify a timeout for the request.
Or perhaps the server returned error 500 and it fails during json_decode? You can check the status code returned by the request.
Or even perhaps the code is failing the line that you indicate but the exception ConnectException is not being caught? Try using Exception as a catch-all to debug this situation.
Instead of using Guzzle directly, I recommend that you use the Drupal wrapper (which uses Guzzle under the hood).
$client = Drupal::httpClient();
$request = $client->get($uri, ['connect_timeout' => 5]);
if ($request->getStatusCode() === 200) {
echo 'Connection Success';
} else {
echo sprintf('Error %d occurred', $request->getStatusCode());
}

Uncaught exception 'apiServiceException' with message 'Error calling GET ....'

I have a small card game for Google+ which needs the visitor's name, avatar, gender and city.
It works for myself, but in the error_log I see a lot of PHP-exceptions:
[28-Jan-2012 19:06:33] PHP Fatal error: Uncaught exception 'apiServiceException' with message 'Error calling GET https://www.googleapis.com/plus/v1/people/me?alt=json&key=AIzaSyAgQl0UeNM553PfLnPmP0jTtcJ8ZIQ3q0g: (404) Not Found' in /var/www/html/preferans.de/google/google-api-php-client/src/io/apiREST.php:86
Stack trace:
#0 /var/www/html/preferans.de/google/google-api-php-client/src/io/apiREST.php(56): apiREST::decodeHttpResponse(Object(apiHttpRequest))
#1 /var/www/html/preferans.de/google/google-api-php-client/src/service/apiServiceResource.php(151): apiREST::execute(Object(apiServiceRequest))
#2 /var/www/html/preferans.de/google/google-api-php-client/src/contrib/apiPlusService.php(207): apiServiceResource->__call('get', Array)
#3 /var/www/html/preferans.de/google/index.php(33): PeopleServiceResource->get('me')
#4 {main}
thrown in /var/www/html/preferans.de/google/google-api-php-client/src/io/apiREST.php on line 86
Here is my script:
<?php
require_once('google-api-php-client/src/apiClient.php');
require_once('google-api-php-client/src/contrib/apiPlusService.php');
session_start();
$client = new apiClient();
$client->setApplicationName('Video-Preferans');
$client->setClientId('XXX.apps.googleusercontent.com');
$client->setClientSecret('XXX');
$client->setRedirectUri('http://preferans.de/google');
$client->setDeveloperKey('XXX');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new apiPlusService($client);
if (isset($_REQUEST['logout']))
unset($_SESSION['access_token']);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token']))
$client->setAccessToken($_SESSION['access_token']);
if ($client->getAccessToken()) {
$me = $plus->people->get('me'); # XXX line 33 XXX
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
printf('
<!doctype html>
<html>
<head>
<body>
<p>Play Preferans</p>
</body>
</html>
', $client->createAuthUrl());
exit();
}
$viewer_id = $me['id'];
list($first_name, $last_name) = explode(' ', $me['displayName']);
$city = $me['placesLived'][0]['value'];
$female = ($me['gender'] == 'male' ? 0 : 1);
$avatar = $me['image']['url'];
....skipped some html code....
Does anybody please know, why the apiServiceException is being thrown?
Or how and where at least catch it, so that I can debug it better?
I'm using the latest Google+ SDK 0.4.8.3 and also I'm requesting very basic user information and as I've written - it works for me and also for my wife's account.
You can wrap $me = $plus->people->get('me') within a try/catch block.
The plus/v1/people/me API returns a 404 Not Found when the user hasn't registered for Google+, and you can catch this case with the following:
try {
$me = $plus->people->get('me')
} catch (apiServiceException $e) {
// Handle exception. You can also catch Exception here.
// You can also get the error code from $e->getCode();
}
I have the same problem, only difference is I'm trying to use the Calendar API. I get the exact same error response as you did in the first place, tried the try/catch-block and it kind of worked. If I print the error response it says "403", but I also get the JSON-response I want. Do you know why?
my code:
if ($client->getAccessToken()) {
try{
$activities = $plus->activities->listActivities('me', 'public');
print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
// The access token may have been updated.
$_SESSION['token'] = $client->getAccessToken();
} catch (apiServiceException $e) {
// Handle exception. You can also catch Exception here.
// You can also get the error code from $e->getCode();
echo $e->getCode();
print_r($activities);
}
}

RackSpace Cloudfiles api error 'Undefined offset: 8'

When trying to upload files to rackspace cloudfiles, I am getting this error.
I tried to trace the source of error and I assume that it is coming from this line of code:
$container = $conn->get_container('test');
This is the complete error that I am getting:
Notice
Undefined offset: 8
File: /dm/cloudfiles/cloudfiles.php, Line: 1588
And this is the code for upload:
<?php
// include the Cloud API.
require('cloudfiles/cloudfiles.php');
// Rackspace Connection Details;
// cloud info
$username = "tariehk"; // username
$key = ""; // api key
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
//Set the Container you want to use
$container = $conn->get_container('dm');
//Temp store the file
$localfile = $_FILES['uploadfile']['tmp_name'];
$filename = $_FILES['uploadfile']['name'];
//exit();
//Uploading to Rackspace Cloud
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
echo "Your file has been uploaded";
?>
This problem has been fixed in their repo but it still exists in the download version.
The fixes can be found here
https://github.com/towynlin/php-cloudfiles/commit/02a8c658db7e9969b35bb57c47ede232521a6617
and
https://github.com/towynlin/php-cloudfiles/commit/78c5d612fb5a7037e92f61acfaf10b59e09239e8
bug report is here
https://github.com/rackspace/php-cloudfiles/pull/23
Its just a few lines, I just patched it myself.