The service is currently unavailable Google api - php

I'm using google slide API to connect to my project account, the connection worked perfectly, but sometime I get this error :
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 503, "message": "The service is currently unavailable.", "errors": [ { "message": "The service is currently unavailable.", "domain": "global", "reason": "backendError" } ], "status": "UNAVAILABLE" } } in /vendor/google/apiclient/src/Google/Http/REST.php:118 Stack trace: #0 /vendor/google/apiclient/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 /vendor/google/apiclient/src/Google/Task/Runner.php(181): Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 /vendor/google/apiclient/src/Google/Http/REST.php(58): Google_Task_Runner->run in /vendor/google/apiclient/src/Google/Http/REST.php on line 118
This is my getClient function Google API:
function getClient(string $SCOPES,string $CLIENT_SECRET_PATH,string $CREDENTIALS_PATH,string $APPLICATION_NAME) {
$this->client->setApplicationName($APPLICATION_NAME);
$this->client->setScopes($SCOPES);
$this->client->setAuthConfig($CLIENT_SECRET_PATH);
$this->client->setAccessType('offline');
$this->client->setApprovalPrompt('force');
$credentialsPath = $this->expandHomeDirectory($CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$authUrl = $this->client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $this->client->fetchAccessTokenWithAuthCode($authCode);
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$this->client->setAccessToken($accessToken);
if ($this->client->isAccessTokenExpired()) {
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($this->client->getAccessToken()));
}
return $this->client;
}
This is the request the I send:
public function replaceAllShapesWithImage(array $data_images)
{
$requests =array();
if(isset($data_images)){
foreach ($data_images as $key => $value) {
$requests[] = new \Google_Service_Slides_Request(array(
'replaceAllShapesWithImage' => array(
'imageUrl' => $value['url'],
'replaceMethod' => $value['replaceMethod'],
'containsText' => array(
'text' => $value['text']
)
)
));
}
}
return $requests;
}
$data_image has this value:
'replaceAllShapesWithImage' => array(
0 => array(
'text'=>'{{LOGO}}',
'url'=>'http://www.16cafe.com/wp-content/themes/16cafe/css/images/logo.png',
'replaceMethod'=>'CENTER_INSIDE'
),
1 => array(
'text'=>'{{PHOTO}}',
'url'=>'http://localhost:9880/wp-content/uploads/2017/02/pla23.jpg',
'replaceMethod'=>'CENTER_INSIDE'
),
)

Every time I catch an API error my script waits 1 second. If the error occurs again the script waits 2 seconds. Then 4 seconds, 8 seconds, 16 seconds. In total I make 5 attempts. It works every time.
public function get_analytics_response()
{
$api_call_num_of_attempts = 5;
$api_call_attempts = 0;
$api_call_sleep = 1;
do {
try {
$response = $this->analytics->reports->batchGet();
}
catch (Google_Service_Exception $e) {
// Sleep 1s, 2s, 4s, 8s, 16s + random milliseconds
$sleep = ($api_call_sleep * 1000000) + rand(1000, 1000000);
usleep($sleep);
$api_call_attempts++;
$api_call_sleep = $api_call_sleep * 2;
$error_message_json = $e->getMessage();
$error_message = json_decode($error_message_json, true);
// Save errors...
continue;
}
break;
}
while ($api_call_attempts < $api_call_num_of_attempts);
return $response;
}

Slides can definitely give better error messaging, but I'm pretty sure the problem is that http://localhost:9880/wp-content/uploads/2017/02/pla23.jpg image URL you are trying to insert. I tried making a replaceAllShapesWithImage request with that image and also got a 503.
Slides downloads your images over the public internet, so a localhost domain wont work. Try hosting it on some publicly accessible URL, or you can use Google Drive to host the image.

I had the same error message (for a totally different reason).
For me, I waited 30 seconds and attempted the same thing again, and it worked.
Seems it may simply be a brief outage of the Google API.

Related

I'm getting an error in Amazon SP-API Orders API "Application do not have access to some or all requested resource"

I'm getting an error "Application do not have access to some or all requested resource" when calling the method getOrders()/getOrder() from the Orders API.
I taken the code entirely from https://github.com/jlevers/selling-partner-api. I installed the composer require jlevers/selling-partner-api and followed the instruction to connect to the Selling Partner API.
In addition, I also tried calling $result = $apiInstance>getMarketplaceParticipations() which works without any particular error, so I don't think it's an error in the configurations.
Can anybody point me in the right direction to resolve this?
Code
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$token = "<TOKEN>";
use SellingPartnerApi\Api\SellersV1Api as SellersApi;
use SellingPartnerApi\Configuration;
use SellingPartnerApi\Endpoint;
$config = new Configuration([
"lwaClientId" => "amzn1.applica..",
"lwaClientSecret" => "<clientSecret>",
"lwaRefreshToken" => $token,
"awsAccessKeyId" => "<accessKey>",
"awsSecretAccessKey" => "<secretAcessKey>",
"endpoint" => Endpoint::FE
]);
$apiInstance = new SellingPartnerApi\Api\OrdersV0Api($config);
$marketplace_ids = array('A1############');
$created_after = '2022-07-27';
try {
$result = $apiInstance->getOrders($marketplace_ids);
print "<pre>";
print_r($result);
print "</pre>";
} catch (Exception $e) {
echo 'Exception when calling OrdersV0Api->getOrders: ', $e->getMessage(), PHP_EOL;
}
Error Message
Exception when calling OrdersV0Api->getOrders: [400] { "errors": [ { "code": "InvalidInput", "message": "Application do not have access to some or all requested resource", "details": "" } ] }
Put created after in this format:
$created_after = new \DateTime("2021-10-01");
$after_str = $created_after->format('Y-m-d\TH:i:s\Z');

I want review from my google business account

I am using google API php client and getting below error. This code is working fine before a week. Current its not working and passing error. may be some deprecated by google after that its not working. Please help me out as soon as possible because its affect on live product and can't able to show review.
$http = new GuzzleHttp\Client([
'verify' => false
]);
$client = new Google_Client();
$client->setHttpClient($http);
$client->setApplicationName('Magic Minds WEB');
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setRedirectUri(redirectUri);
$client->setScopes("https://www.googleapis.com/auth/business.manage");
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$mybusinessService = new Google_Service_MyBusiness($client);
$credentialsPath = tokenJson;
// Load previously authorized credentials from a file.
$accessToken = (array)json_decode(file_get_contents($credentialsPath));
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
// For testing purposes, selects the very first account in the accounts array
$accounts = $mybusinessService->accounts;
// echo "<pre>";
//print_r($accounts);
$accountsList = $accounts->listAccounts()->getAccounts();
print_r($accountsList);
$account = $accountsList[2];
// For testing purposes, selects the very first location in the locations array
$locations = $mybusinessService->accounts_locations;
$locationsList = $locations->listAccountsLocations($account->name)->getLocations();
$location = $locationsList[0];
// Lists all reviews for the specified location
$reviews = $mybusinessService->accounts_locations_reviews;
$listReviewsResponse = $reviews->listAccountsLocationsReviews($location->name);
$reviewsList = $listReviewsResponse->getReviews();
Getting below error
Fatal error: Uncaught Google\Service\Exception: { "error": { "code": 400, "message": "Request contains an invalid argument.", "errors": [ { "message": "Request contains an invalid argument.", "domain": "global", "reason": "badRequest" } ], "status": "INVALID_ARGUMENT", "details": [ { "#type": "type.googleapis.com/google.mybusiness.v4.ValidationError", "errorDetails": [ { "message": "This API will soon be deprecated. Please migrate all the usages to My Business Account Management API - https://developers.google.com/my-business/reference/accountmanagement/rest" } ] } ] } } in /var/www/html/magicmind/magicmindsweb/backend/vendor/google/apiclient/src/Http/REST.php:128 Stack trace: #0 /var/www/html/magicmind/magicmindsweb/backend/vendor/google/apiclient/src/Http/REST.php(103): Google\Http\REST::decodeHttpResponse() #1 [internal function]:
efforts will be appreciated. Thanks in advance
Google is shutting down that api as stated in the error message. They have stated
Starting April 30, 2022, the following four API methods will return errors with increasing frequency, ramping up to 100% shut down within 30 days.
As today is June 07, 2022 You are past the 30 day grace period. So the error message you are getting is the result of that.
This API will soon be deprecated. Please migrate all the usages to My Business Account Management API - https://developers.google.com/my-business/reference/accountmanagement/rest"
I would just start to migrate to the new api as they have directed, This is not something you can fix as that API no longer exists.
See accounts management api

Updating spreadsheet data with Google Spreadsheet api and php suddenly not working with authentication error

In a form which takes input and updates the value in a spreadsheet. It was working fine before but suddenly stopped working with this error message:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 403, "message": "The caller does not have permission", "errors": [ { "message": "The caller does not have permission", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } ' in /google-api-php-client-2.2.2/src/Google/Http/REST.php:118
Stack trace:
#0 /google-api-php-client-2.2.2/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#2 /google-api-php-client-2.2.2/src/Google/Task/Runner.php(176): call_user_func_array(Array, Array)
#3 /google-api-php-client-2.2.2/src/Google/Http/REST.php(58): Google_Task_Runner->run()
#4 /html/form in /google-api-php-client-2.2.2/src/Google/Http/REST.php on line 118
According to other questions and answers it is because of authentication problem, but the form was working for 5 years with the same authentication so it is confusing. Is there any other reason for which the form is not updating?
here is the code included
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);
date_default_timezone_set("US/Central");
// Autoload Composer.
if (file_exists(__DIR__ . "/google-api-php-client-2.2.2/vendor/autoload.php")) {
require_once __DIR__ . "/google-api-php-client-2.2.2/vendor/autoload.php";
$spreadsheetId = "********"; // TODO: Update placeholder value.
// The A1 notation of a range to search for a logical table of data.
// Values will be appended after the last row of the table.
$range = "A2"; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
$values = [
[
date("Y-m-d H:i:s"),
$_POST["prop_type"],
$_POST["pstreet"],
$_POST["pcity"],
$_POST["pzip"],
],
];
$service_account_file = "service-account.json";
$client = new Google_Client();
$service = new Google_Service_Sheets($client);
if ($client) {
$client->setApplicationName("Google Sheet Update");
$client->setAuthConfig($service_account_file);
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAccessType("online");
$redirect_uri =
"http://" . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"];
$client->setRedirectUri($redirect_uri);
$guzzle = new GuzzleHttp\Client([
"verify" => false,
]);
$client->setHttpClient($guzzle);
$requestBody = new Google_Service_Sheets_ValueRange([
"values" => $values,
]);
$params = [
"valueInputOption" => "RAW",
];
$response = $service->spreadsheets_values->append(
$spreadsheetId,
$range,
$requestBody,
$params
);
//echo '<pre>', var_export($response, true), '</pre>', "\n";
} else {
echo "Not Valid Client";
echo "<pre>CLIENT", var_dump($client), "</pre>", "\n";
}
} else {
echo "Client File do not exist";
}
?>
The caller does not have permission
means exactly that. Which ever user you used to authorize this code does not have permission to access that sheet. Authorize your application with a user that has access or grant that user access.
Service accounts need to be preauthorized. The most common way to do that is to take the service account client id and share the file with it though the google drive web application. If someone removed the service accounts access to the file. The service account will no longer have access.
I would double check that it still has access.

Google Cloud Translate: cryptic error 400 invalid value

I am using Google Translate (basic version) to translate some string. It was working fine a couple of minutes ago, but now it just returns error 400. The code is very simple:
function translatePhrase($text, $target, $source = 'it') {
$sourceLanguage = $source;
$targetLanguage = $target;
$translate = new TranslateClient();
$result = $translate->translate($text, [
'source' => $sourceLanguage,
'target' => $targetLanguage,
]);
$output = $result['text'];
return $output;
}
It returns:
Uncaught Google\Cloud\Core\Exception\BadRequestException: {
"error": {
"code": 400,
"message": "Invalid Value",
"errors": [
{
"message": "Invalid Value",
"domain": "global",
"reason": "invalid"
}
]
}
}
in \vendor\google\cloud-core\src\RequestWrapper.php:362
Stack trace:
#0 \vendor\google\cloud-core\src\RequestWrapper.php(206): Google\Cloud\Core\RequestWrapper->convertToGoogleException(Object(GuzzleHttp\Exception\ClientException))
#1 \translate\vendor\google\cloud-core\src\RestTrait.php(95): Google\Cloud\Core\RequestWrapper->send(Object(GuzzleHttp\Psr7\Request), Array)
#2 \translate\vendor\google\cloud-translate\src\V2\Connection\Rest.php(83): Google\Cloud\Translate\V2\Connection\Rest->send('translations', 'translate', Array)
#3 \translate\vendor\google\cloud-translate\src\V2\TranslateClient.php(248): Google\Cloud\Translate\V2\Connection\Rest->listTra
in [\translate\vendor\google\cloud-core\src\RequestWrapper.php riga 362]
Any thoughts ?
As one can see, it bugs out exactly here ...so the options array is at fault. It should rather look alike this (because no single example passes a source language-code, but instead an auto-detected $result['source'] is being returned):
function translatePhrase($text, $target) {
$translate = new TranslateClient();
$result = $translate->translate($text, [
'target' => $target
]);
return $result['text'];
}
I got the reason.
Basically, I was forcing a wrong source language. When I specified the correct source language it worked again.

Google API OAuth in php 401 Login Required

I'm trying to use google api for shopping (merchants) and I'm stuck with this problem.
I'm not very familiar with php, but to me the code seems fine, all I wanna do is try to fetch items from my shop. I've set the client id and client secret in the developer console following the suggested steps by google, but still after logging I get the error.
Here the code I'm using:
<?php
/*
* Uses google API to make an authorized request trough a google dev console project.
*/
require_once __DIR__ . '/../../google-api-php-client-master/vendor/autoload.php';
//require_once 'Google/Client.php';
//require_once 'Google/Service/ShoppingContent.php';
require_once '../Config.php';
$redirect_uri = $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; //this is used during the auth process
//$merchantId = $_POST['merchantId'];
$merchantId = Config::MERCHANT_ID;
$service;
$client = Config::getGoogleClient();
$client->setRedirectUri($redirect_uri);
doOAuth($client);
echo "TOKEN : " + $client->getAccessToken() . " " . $_SESSION['oauth_access_token'];
//after authentication we can create a service object
$service = new Google_Service_ShoppingContent($client);
$products = $service->products->listProducts($merchantId);
$parameters = array();
while (!empty($products->getResources())) {
foreach ($products->getResources() as $product) {
printProduct($product);
}
if (!empty($products->getNextPageToken())) {
break;
}
$parameters['pageToken'] = $products->nextPageToken;
$products = $service->products->listProducts($merchantId, $parameters);
}
printf("\nEnd");
////////////////////////
//$_SESSION['oauth_access_token'] = null;
function doOAuth(&$client) {
if (isset($_SESSION['oauth_access_token'])) {
$client->setAccessToken($_SESSION['oauth_access_token']);
} elseif (isset($_GET['code'])) {
// $client->setAccessType("offline"); //IMPORTANT
$token = $client->authenticate($_GET['code']);
$_SESSION['oauth_access_token'] = $token;
} else {
header('Location: ' . $client->createAuthUrl());
exit;
}
}
function printProduct($product) {
printf("%s %s\n", $product->getId(), $product->getTitle());
}
And I get the following error:
0 Array Fatal error: Uncaught exception 'Google_Service_Exception'
with message '{ "error": { "errors": [ { "domain": "global", "reason":
"required", "message": "Login Required", "locationType": "header",
"location": "Authorization" } ], "code": 401, "message": "Login
Required" } } ' in C:\Program Files (x86)\Apache Software
Foundation\Apache24\htdocs\google-api-php-client-master\src\Google\Http\REST.php:123
Stack trace: #0 C:\Program Files (x86)\Apache Software
Foundation\Apache24\htdocs\google-api-php-client-master\src\Google\Http\REST.php(82):
Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal
function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 C:\Program
Files (x86)\Apache Software
Foundation\Apache24\htdocs\google-api-php-client-master\src\Google\Task\Runner.php(181):
call_user_func_array(Array, Array) #3 C:\Program Files (x86)\Apac in
C:\Program Files (x86)\Apache Software
Foundation\Apache24\htdocs\google-api-php-client-master\src\Google\Http\REST.php
on line 123
Thanks for any help
EDIT: further information
I was able to detect this error inside the $token object
[error] => redirect_uri_mismatch [error_description] => Bad Request
Blockquote
/**
* IMPORTANT: this url is used during both two phases of OAuth.
* If a mistmatch of the redirect uri occours during the two phases, the login
* fails. Must ignore the code (get) parameter in the second phase.
**/
$redirect_uri = "http://localhost/gshop/action/list.php";
the old uri was dynamic and with the code parameter

Categories