Invalid json in service response - php

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)

Related

PHP Guzzle could not resolve host on localhost, but works on server

I have this Zend 2 application where I'm making use of this Azure AD library for authentication. Everything has been working fine for a few months, but all of a sudden it stopped working on my localhost. The strange part is that it still works fine on our server. I don't believe this is an issue with the library itself, which is why I'm asking for help here as well.
Whenever I try to get the Provider for oauth2 using the following code:
(This Azure class is simply an extention of League\OAuth2\Client\Provider)
private static function getAzureProvider(): Azure
{
$provider = new Azure([
'clientId' => self::$azure_client_id,
'clientSecret' => self::$azure_client_secret,
'redirectUri' => self::$post_login_redirect_uri,
'tenant' => self::$azure_tenant_id,
'defaultEndPointVersion' => Azure::ENDPOINT_VERSION_2_0
]);
$baseGraphUri = $provider->getRootMicrosoftGraphUri(null); // <-- This is what triggers the 'Could not resolve' error
$provider->scope = 'openid profile email offline_access ' . $baseGraphUri . '/User.Read';
return $provider;
}
I get the following error:
Error while obtaining AzureProvider: 'cURL error 6: Could not resolve host: login.microsoftonline.com (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)'.
Stacktrace:
#0 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(155): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
#1 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(105): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#2 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#3 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#4 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php(51): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#5 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php(37): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#6 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Middleware.php(29): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#7 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php(70): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#8 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Middleware.php(59): GuzzleHttp\RedirectMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#9 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/HandlerStack.php(71): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#10 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Client.php(351): GuzzleHttp\HandlerStack->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#11 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Client.php(112): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array)
#12 /var/www/hqcrs/vendor/guzzlehttp/guzzle/src/Client.php(129): GuzzleHttp\Client->sendAsync(Object(GuzzleHttp\Psr7\Request), Array)
#13 /var/www/hqcrs/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(608): GuzzleHttp\Client->send(Object(GuzzleHttp\Psr7\Request))
#14 /var/www/hqcrs/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(621): League\OAuth2\Client\Provider\AbstractProvider->getResponse(Object(GuzzleHttp\Psr7\Request))
#15 /var/www/hqcrs/vendor/thenetworg/oauth2-azure/src/Provider/Azure.php(76): League\OAuth2\Client\Provider\AbstractProvider->getParsedResponse(Object(GuzzleHttp\Psr7\Request))
#16 /var/www/hqcrs/vendor/thenetworg/oauth2-azure/src/Provider/Azure.php(163): TheNetworg\OAuth2\Client\Provider\Azure->getOpenIdConfiguration('[tenant id]', '2.0')
#17 /var/www/hqcrs/module/Auth/src/Auth/Utils/AzureAuthUtils.php(74): TheNetworg\OAuth2\Client\Provider\Azure->getRootMicrosoftGraphUri(NULL)
#18 /var/www/hqcrs/module/Auth/src/Auth/Utils/AzureAuthUtils.php(91): AzureAuthUtils::getAzureProvider()
#19 /var/www/hqcrs/module/Auth/src/Auth/Utils/AzureAuthUtils.php(125): AzureAuthUtils::azureLogin()
#20 /var/www/hqcrs/module/Auth/src/Auth/Controller/AuthController.php(15): AzureAuthUtils::doAzureLogin()
#21 /var/www/hqcrs/vendor/zendframework/zend-mvc/src/Controller/AbstractActionController.php(82): Auth\Controller\AuthController->loginAction()
#22 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#23 /var/www/hqcrs/vendor/zendframework/zend-eventmanager/src/EventManager.php(490): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#24 /var/www/hqcrs/vendor/zendframework/zend-eventmanager/src/EventManager.php(211): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#25 /var/www/hqcrs/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(118): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#26 /var/www/hqcrs/vendor/zendframework/zend-mvc/src/DispatchListener.php(93): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#27 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#28 /var/www/hqcrs/vendor/zendframework/zend-eventmanager/src/EventManager.php(490): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#29 /var/www/hqcrs/vendor/zendframework/zend-eventmanager/src/EventManager.php(211): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#30 /var/www/hqcrs/vendor/zendframework/zend-mvc/src/Application.php(314): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#31 /var/www/hqcrs/public/index.php(40): Zend\Mvc\Application->run()
#32 {main}
I have searched online for a full day at this point, but I can't seem to find any concrete solutions to this issue. Does anyone have an idea of what might be going on?
If I manually perform a curl command and go to https://login.microsoftonline.com it seems to work fine.
My cURL versions both on localhost and on server are 7.64.0, so there's no difference between the two. If I should provide some more info then let me know!
Edit: More of my source code is below:
public static function isLoggedInWithAzure(?string $code = null, ?string $state = null): bool
{
return !empty(self::getAzureAccessToken($code, $state);
}
public static function doAzureLogin(?string $code = null, ?string $state = null)
{
if (!self::isLoggedInWithAzure($code, $state)) {
self::azureLogin();
}
}
private static function azureLogin()
{
$azure_provider = self::getAzureProvider();
$oauth_session = new Container('oAuth2');
$authorizationUrl = $azure_provider->getAuthorizationUrl(['scope' => $azure_provider->scope]);
$oauth_session->state = $azure_provider->getState();
header('Location: ' . $authorizationUrl);
exit;
}
private static function getAzureAccessToken(?string $code = null, ?string $state = null): ?AccessToken
{
$oauth_session = new Container('oAuth2');
$access_token = null;
if ($code !== null && $state !== null && isset($oauth_session->state)) {
/*
* If code & state are set, try to get new accesstoken
*/
if ($state == $oauth_session->state) {
unset($oauth_session->state);
/**
* Try to get an access token (using the authorization code grant)
*
* #var AccessToken $access_token
*/
$azure_provider = self::getAzureProvider();
$access_token = $azure_provider->getAccessToken('authorization_code', [
'scope' => $azure_provider->scope,
'code' => $_GET['code'],
]);
} else {
self::writeToApplicationLog(CONST_APPLICATION_LOG_TYPE_ERROR, '[getAzureAccessToken] Invalid state returned.');
}
} else if (!empty($oauth_session->access_token)) {
/*
* Else if access token is set in session, verify if still valid
*/
$access_token = $oauth_session->access_token;
/**
* #var AccessToken $access_token
*/
if ($access_token->hasExpired()) {
if ($access_token->getRefreshToken() !== null) {
$azure_provider = self::getAzureProvider();
$access_token = $azure_provider->getAccessToken('refresh_token', [
'scope' => $azure_provider->scope,
'refresh_token' => $access_token->getRefreshToken()
]);
} else {
self::writeToApplicationLog(CONST_APPLICATION_LOG_TYPE_ERROR, '[getAzureAccessToken] Accesstoken has expired but does not have refreshtoken. Accesstoken: ' . print_r($access_token, true));
}
}
}
$oauth_session->access_token = $access_token;
return $access_token;
}
The error reads:
Could not resolve host: login.microsoftonline.com
As you said the application was working fine few months ago then, I think it will work fine if you clear all type of caches in Artisan. Run these following commands together and then restart your server again.
php artisan route:clear
php artisan config:clear
php artisan cache:clear
Try changing the code you used to initializes the oauth provider for Azure AAD. The following code snippet shows how you can do that.
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
'clientId' => 'c9e*****9ea',
'clientSecret' => 'AKX********',
'redirectUri' => 'http://localhost:90',
'tenant' => 'e2*******3d',
'urlAuthorize' => 'https://login.microsoftonline.com/e2*******3d/oauth2/v2.0/authorize',
'urlAccessToken' => 'https://login.microsoftonline.com/e2******3d/oauth2/v2.0/token',
'urlAPI' => 'b37*******b02',
'scope' => 'b37*******b02/.default'
]);
$provider->defaultEndPointVersion = TheNetworg\OAuth2\Client\Provider\Azure::ENDPOINT_VERSION_2_0;
And now you can now retrieve the access token with the following code.
$accessToken = $provider->getAccessToken('client_credentials', [
'scope'=> $provider->scope
]);
You should read this Accessing AAD OAuth2 protected API from PHP document for more information.
It has been solved.
We had pinpointed the issue to having something to do with the Docker DNS settings, but couldn't figure out what was needed exactly.
After updating docker to the latest updates, the error was gone.
I'm assuming the issue was within docker itself then.
Thank you for the help, in any case!

Script dies when trying to use $model->save()

I am trying to use $model->save() .. but i can't get the error messages like the documentation instead the error message appears with trace error then the script dies.
for example i am trying to use this code:
$user = new Users();
$user->name = "Name";
if(!$user->save()){
//do stuff if there is an error
}
the problem is that i always get the validation error like this and the script dies and never returns false to enter the if condition :
password is required
#0 ..../UsersController.php(106): Phalcon\Mvc\Model->save()
#1 [internal function]: ....\UsersController->createAction()
#2 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(....\UsersController), 'createAction', Array)
#3 [internal function]: Phalcon\Dispatcher->_dispatch()
#4 [internal function]: Phalcon\Dispatcher->dispatch()
#5 ....\public\index.php(41): Phalcon\Mvc\Application->handle()
#6 {main}**
I Finally found the solution, I found that somewhere in the services.php
this line was enabled and that what caused the exception to be thrown
Phalcon\Mvc\Model::setup(['exceptionOnFailedSave' => true] and after turning it to false,i can easily add my conditions and check the errors message using this code.
if ($model->save() === false) {
$messages = $model->getMessages();
foreach ($messages as $message) {
echo $message, "\n";
}
}
you can send flash error using
$this->flash->error("too bad! the form had errors");
$this->flash->success("yes!, everything went very smoothly");
$this->flash->notice("this a very important information");
$this->flash->warning("best check yo self, you're not looking too good.");
see documentation
https://docs.phalconphp.com/en/latest/reference/flash.html

Google adsense api (403) User does not have an AdSense account

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/

Creating an Invoice with Paypal-Php-SDK fails with "Can not deserialize instance of java..." error

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));

Insufficient Permission in Mirror API Insert Account using PHP

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

Categories