I have PHP code that Google PHP Mirror API to insert user account.
if(isset($_GET['userToken'])){
$userToken=$_GET['userToken'];
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
'service-email-here',
array('https://www.googleapis.com/auth/glass', 'https://www.googleapis.com/auth/glass.thirdpartyauth'),
$key
);
$client->setAssertionCredentials($cred);
$mirrorService = new Google_Service_Mirror($client);
$_SESSION['access_token'] = $client->getAccessToken();
insert_account($mirrorService, $userToken, $email, $api_email);
exit();
}
function insert_account($service,$userToken, $email, $api_email)
{
$accountType='package-name-here';
$accountName='service-email-here';
$authtoken=null;
$postBody = new Google_Service_Mirror_Account();
$postBody->setAuthTokens($authtoken);
$userdata=array("email"=>$email);
$postBody->setUserData($userdata);
try {
$account = $service->accounts->insert($userToken, $accountType, $accountName, $postBody);
return $account;
} catch (Exception $e) {
echo "exception: ".$e;
return null;
}
}
I get an error which says:
exception: exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/mirror/v1/accounts/usertokenhere/package-name-here/service-email-here: (403) Insufficient Permission' in app-path/Google/Http/REST.php:79
Stack trace:
#0 app-path/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 app-path/Google/Client.php(508): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 app-path/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 app-path/Google/Service/Mirror.php(409): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 app-path/util.php(52): Google_Service_Mirror_Accounts_Resource->insert('8ce7d2ffbe6f693...', 'com.tenpearls.l...', '568533774877-an...', Object(Google_Service_Mirror_Account))
#5 app-path/add-your-own-camera.php(59): insert_account(Object(Google_Service_Mirror), '8ce7d2ffbe6f693...', 'safdar.tp#gmail...', '568533774877-an...')
#6 {main}
Why am I getting the insufficient permission error? I added the scope https://www.googleapis.com/auth/glass.thirdpartyauth which is required to add accounts using mirror api.
I need to insert user account using mirror API.
You do not need the scope https://www.googleapis.com/auth/glass. In fact, this is not a valid scope at all.
The only scope you need for adding an account on the device using a service account is https://www.googleapis.com/auth/glass.thirdpartyauth.
Calling insert account method required separate service client object. Code can be viewed here: http://goo.gl/DVggO6
Related
I am just trying to connect my PHP with Google API. My aim is to fetch a particular folder's content and show them as feeds in my site. So for a base I am trying to pull the kind of file of my drive. I am struck. Here is my code.
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_DriveService.php';
$client = new Google_Client(); $client->setApplicationName("My Application");
$client->setDeveloperKey("<mykey>");
$service = new Google_DriveService($client);
$optParams = array('fields' => 'kind'); $results = $service->files->listFiles($optParams);
foreach ($results['files'] as $item) {
print($item['kind'].'<br>');
}
?>
When I execute this, I get the following error,
Fatal error: Uncaught exception 'Google_ServiceException' with message
'Error calling GET
https://www.googleapis.com/drive/v2/files?fields=kind&key=:
(403) Insufficient permissions for this file' in
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\io\Google_REST.php:66
Stack trace: #0
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\io\Google_REST.php(36):
Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\service\Google_ServiceResource.php(177):
Google_REST::execute(Object(Google_HttpRequest)) #2
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\contrib\Google_DriveService.php(465):
Google_ServiceResource->__call('list', Array) #3
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\test.php(12):
Google_FilesServiceResource->listFiles(Array) #4 {main} thrown in
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\io\Google_REST.php
on line 66
I gave proper key. Kindly help me. Thank you
it have been 4 hours trying to troubleshoot this problem,it always return with (403) User does not have an AdSense account , I am trying to get report of my adsense on my website,
Ps:it's server to server connection
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
require_once '../src/Google/Client.php';
require_once '../src/Google/Service/AdSense.php';
$client_email = 'xxx#xxx-1220.iam.gserviceaccount.com';
$private_key = file_get_contents('adsense-xxxxx.p12');
$scopes = array('https://www.googleapis.com/auth/adsense.readonly');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret'
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_AdSense($client);
Error Log:
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/adsense/v1.4/accounts?maxResults=50: (403) User does not have an AdSense account.' in /var/www/geturl/ad/src/Google/Http/REST.php:110
#0 /var/www/geturl/ad/src/Google/Http/REST.php(62): 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 /var/www/geturl/ad/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /var/www/geturl/ad/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /var/www/geturl/ad/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /var/www/geturl/ad/src/Google/Service/Resource.php(240): Google_Client->execute(Object(Google_Http_Request))
#6 /var/www/geturl/ad/src/Google/Service/AdSense.php(1106): Google_Service_Resource->call('list', Array, 'Google_Servic in /var/www/geturl/ad/src/Google/Http/REST.php on line 110
Did you wait for 24 hours after enabling the api?
Try testing the account to make sure that it works outside of code. Use the APIs explorer:
https://developers.google.com/adsense/management/v1.4/reference/accounts/list#try-it
Authenticate and try to fetch accounts list.
If that works, make sure you are connecting to the API using that account credentials.
Edit:
Perhaps one of these can help:
https://github.com/googleads/googleads-adsense-examples/tree/master/php-clientlib-1.x/v1.x
https://developers.google.com/adsense/management/libraries
http://www.binarytides.com/php-get-adsense-earnings-and-reports/
I'm trying to get my profile info using the PHP API, yet it doesn't seem to be working in the last couple days.
My code is as follows:
<?php
try {
$client_id = '****************.apps.googleusercontent.com';
$client_secret = '*********************';
$redirect_uri = '**********************';
$google_key = '***************';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($google_key);
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
$plus = new Google_Service_Plus($client);
if(isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$accessToken = $client->getAccessToken();
$refreshToken = json_decode($accessToken)->refresh_token;
setcookie('refresh_token', $refreshToken, (time()+60*60*24*30));
setcookie('access_token', $accessToken, (time()+60*60*24*30));
header('Location: ./');
exit();
}
if(isset($_COOKIE['access_token']) && $_COOKIE['access_token']) {
$refreshToken = json_decode($_COOKIE['access_token'])->refresh_token;
$accessToken = $_COOKIE['access_token'];
setcookie('access_token', $accessToken, (time()+60*60*24*30));
$client->setAccessToken($_COOKIE['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
if($client->getAccessToken()) {
$accessToken = $client->getAccessToken();
setcookie('access_token', $accessToken, (time()+60*60*24*30));
if(isset($plus)){
$userInfo = $plus->people->get('me');
}
}
if($client->isAccessTokenExpired() && isset($userInfo)){
$refreshToken = $_COOKIE['refresh_token'];
$client->refreshToken($refreshToken);
$newtoken = $client->getAccessToken();
setcookie('access_token', $newtoken, (time()+60*60*24*30));
header('Location: ./');
exit();
}
} catch (Google_Service_Exception $gse){
error_log($gse, 0);
} catch (Google_Auth_Exception $gae){
error_log($gae, 0);
}
?>
I will be using a database soon, but i'd like to get it working with cookies first. The error I'm getting is as follows:
[05-Aug-2015 20:40:36 Europe/London] exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/plus/v1/people/me?key=**********************: (403) ‹' in /home5/commodit/public_html/workflow/src/Google/Http/REST.php:110
Stack trace:
#0 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(62): 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 /home5/commodit/public_html/workflow/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /home5/commodit/public_html/workflow/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /home5/commodit/public_html/workflow/src/Google/Service/Resource.php(237): Google_Client->execute(Object(Google_Http_Request))
#6 /home5/commodit/public_html/workflow/src/Google/Service/Plus.php(562): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#7 /home5/commodit/public_html/workflow/includes/head.php(87): Google_Service_Plus_People_Resource->get('me')
#8 /home5/commodit/public_html/workflow/index.php(4): include('/home5/commodit...')
#9 {main}
I also get a "Response not valid json" if i try to use OAuth2 instead of Google Plus as the service.
[05-Aug-2015 20:46:02 Europe/London] exception 'Google_Service_Exception' with message 'Invalid json in service response: ‹' in /home5/commodit/public_html/workflow/src/Google/Http/REST.php:125
Stack trace:
#0 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(62): 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 /home5/commodit/public_html/workflow/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /home5/commodit/public_html/workflow/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /home5/commodit/public_html/workflow/src/Google/Service/Resource.php(237): Google_Client->execute(Object(Google_Http_Request))
#6 /home5/commodit/public_html/workflow/src/Google/Service/Oauth2.php(175): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#7 /home5/commodit/public_html/workflow/includes/head.php(89): Google_Service_Oauth2_Userinfo_Resource->get()
#8 /home5/commodit/public_html/workflow/index.php(4): include('/home5/commodit...')
#9 {main}
Thanks for any help!
Bethany
P.S - I have also tried the "opt_params" variable but it still says invalid JSON :(
I suggest to check the Google/Config.php file, there are several default parameters that can be adjust to get solution for different problems.
In my case i was also receiving an invalid-json-in-service-response, i was sure of correct credential settings, i tryed to run the URL that was passed to Google API with GET protocol and query string, and always had full plain text in json format answer, so i looked at "disable_gzip" parameter and modifiy it to see what was the behaviour if changed.
'Google_Http_Request' => array(
// Disable the use of gzip on calls if set to true. Defaults to false.
'disable_gzip' => self::GZIP_DISABLED, //self::GZIP_ENABLED,
// We default gzip to disabled on uploads even if gzip is otherwise
// enabled, due to some issues seen with small packet sizes for uploads.
// Please test with this option before enabling gzip for uploads in
// a production environment.
'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED,
),
You may set different values for a Google_Client Config, Class Attribute invoking the defined method.
public function setClassConfig($class, $config, $value = null)
I'm trying to create an invoice with Paypal-Php-Sdk, everything's okay, but when I try to set Billing Info something goes wrong and I get this error:
{"name":"VALIDATION_ERROR","message":"Invalid request - see details.","debug_id":"2d34973f0cfef","details":[{"field":"billing_info","issue":"Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at line:1, column:2"}]}exception 'PayPal\Exception\PayPalConnectionException' with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/invoicing/invoices.' in /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:176
Stack trace:
#0 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(74): PayPal\Core\PayPalHttpConnection->execute('{"billing_info"...')
#1 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(103): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/invoicing/i...', 'POST', '{"billing_info"...', NULL)
#2 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Invoice.php(736): PayPal\Common\PayPalResourceModel::executeCall('/v1/invoicing/i...', 'POST', '{"billing_info"...', NULL, Object(PayPal\Rest\ApiContext), NULL)
#3 var/www/admin/data/www/****/application/controllers/store.php(487): PayPal\Api\Invoice->create(Object(PayPal\Rest\ApiContext))
#4 [internal function]: Store->payment()
#5 /var/www/admin/data/www/****/system/core/CodeIgniter.php(359): call_user_func_array(Array, Array)
#6 /var/www/admin/data/www/****/index.php(202): require_once('/var/www/admin/...')
#7 {main}
Here's the code I use:
$client_id = "****";
$secret = "****";
$apiContext = new ApiContext(new OAuthTokenCredential(
$client_id, $secret));
$merchantInfo = new PayPal\Api\MerchantInfo();
$merchantInfo->setEmail("****");
$merchantInfo->setWebsite("****");
$billingInfo = new PayPal\Api\BillingInfo();
$billingInfo->setEmail("****");
$invoice = new PayPal\Api\Invoice();
$invoice->setMerchantInfo($merchantInfo);
$invoice->setBillingInfo($billingInfo);
try
{
$invoice->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
Here's what I've received from Paypal support:
Change these two lines to this:
$invoice->setMerchantInfo(array($merchantInfo));
$invoice->setBillingInfo(array($billingInfo));
Both billing info and merchant info takes in array of objects, not an object directly.
It's strange but it started to work when I changed this only for Billing Info, so the right code for me was:
$invoice->setMerchantInfo($merchantInfo);
$invoice->setBillingInfo(array($billingInfo));
I want to fetch Google Analytics data for my website via Google Analytics API.
First, I went to developers console, I enabled Analytics API, then under credentials section I created new ClientID (Service account).
Now, this is my code
include "assets/src/templates/base.php";
require_once 'assets/src/Google/autoload.php';
$client_id = 'xxx.apps.googleusercontent.com'; //Client ID
$service_account_name = 'yyy#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'zzz/key.p12'; //key.p12
echo pageHeader("Service Account Access");
if (strpos($client_id, "googleusercontent") == false
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
exit;
}
$client = new Google_Client();
$client->setApplicationName("app");
$service = new Google_Service_Analytics($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/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$result = $service->data_ga->get(
'ga:AAA',
'2015-03-03',
'2015-03-03',
'ga:sessions');
?>
where AAA is my ViewID.
So, my problem is this: When I access this script on server it says
*"Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A91249839&start-date=2015-03-03&end-date=2015-03-03&metrics=ga%3Asessions:
(403) User does not have any Google Analytics account.' in
C:\xampp\htdocs\test\assets\src\Google\Http\REST.php:110 Stack trace:
0 C:\xampp\htdocs\test\assets\src\Google\Http\REST.php(62): 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\test\assets\src\Google\Task\Runner.php(174):
call_user_func_array(Array, Array) #3
C:\xampp\htdocs\test\assets\src\Google\Http\REST.php(46):
Google_Task_Runner->run() #4
C:\xampp\htdocs\test\assets\src\Google\Client.php(590):
Google_Http_REST::execute(Object(Google_Client),
Object(Google_Http_Request)) #5
C:\xampp\htdocs\test\assets\src\Google\Service\Resource.php(231):
Google_Client->execute(Object(Google_Htt in
C:\xampp\htdocs\test\assets\src\Google\Http\REST.php on line 110"*
Any suggestions?
Thank you in advance!
Regards,
golobich
Edit: I've tried Google Books api and auth is working ok. (I've changed that link in $cred ofcourse.
The key error is this:
(403) User does not have any Google Analytics account
You are logging in with a service account. You need to grant the service account access to your Google analytics account.
Solution:
Go to the google analytics website. On the admin section add a new user using the service account email address, at the ACCOUNT LEVEL it must be the ACCOUNT LEVEL give this new user read access only that's all it really needs.
Then try your script again.