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
Related
I am creating a web site to interact with Google Calendars and watching resources and I want to stop them, but I can't seem to do that, so Google sends the headers "X-Goog-Channel-Id" and "X-Goog-Resource-Id" with the webhook request which from the documentation seems like that's all that's needed to send back to stop them, but I just keep getting a:
Google\Service\Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Channel '0PAA4Z9RXJYMA7YMAV6O' not found for project '309331158475'"
}
],
"code": 404,
"message": "Channel '0PAA4Z9RXJYMA7YMAV6O' not found for project '309331158475'"
}
}
But they should be found as that's what Google has just sent in the header of the webhook. What am I doing wrong?
$headers = getallheaders();
try{
$client = new Google_Client();
$client->setAccessToken(get_google_accesstoken());
$service = new Google_Service_Calendar($client);
$channel = new Google_Service_Calendar_Channel($service);
$channel->setId($headers['X-Goog-Channel-Id']);
$channel->setResourceId($headers['X-Goog-Resource-Id']);
$service->channels->stop($channel);
}catch(Exception $e){
echo $e->getMessage();
}
So the steps I have currently are registering the watch event for the calendar, all good here. Then when the calendar changes Google loads the URL /webhook/google/ on my site and just for concept on that page I have the code above to stop the webhook from happening again, but it shows the error.
I'm generating the watch event with the code below if that helps
$expire = time()+86400;
try {
$client = new Google_Client();
$client->setAccessToken(get_google_accesstoken());
$service = new Google_Service_Calendar($client);
$channel = new Google_Service_Calendar_Channel($client);
$channel->setId(generaterandomstring(20));
$optParams = array('ttl' => $expire);
$channel->setParams($optParams);
$channel->setType('web_hook');
$channel->setAddress($site_url.'/webhook/google/');
$watchEvent = $service->events->watch('email#mysite.com', $channel);
}catch(Exception $e) {
}
I'd guess it's because the channel has already expired.
The $expire = time()+86400 line makes it seem like you're making it expire in 86.4 seconds. Could it be that you're trying to stop the channel watch more than 86 seconds after it was created?
I wish to develop one restful app where users will upload video to youtube via some admin interface. Since users will only upload on behalf of my name and in one channel I want to make authentication only once and then use refresh token to get access token.
So what I did is the following
I have visited https://developers.google.com and select and authorize all Youtube data API v3 API's with my email
Exchange authorization code for tokens (so now I have Authorization code, refresh and access token)
Code implementation (stuck here, can't imagine huh?)
$client = new Google_Client();
$client->setApplicationName('myApp');
$client->setClientId('<client-id>');
$client->setClientSecret('<client-secret>');
$client->setDeveloperKey('<dev-key>'); // <- do I really need that
$client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube.readonly');
$client->refreshToken('<my-refresh-token>');
$client->setAuthConfig('client_secrets.json'); // <- is that the same as setting clientId and ClientSecret???
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$accessToken = $client->getAccessToken();
if (is_null($accessToken) || $client->isAccessTokenExpired()) {
// How to refresh token with REFRESH token?
dd($_GET);
}
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $video object, which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video();
// Add 'snippet' object to the $video object.
$videoSnippet = new Google_Service_YouTube_VideoSnippet();
$videoSnippet->setCategoryId('1');
$videoSnippet->setChannelId('<my-channel-id>');
$videoSnippet->setDescription('Description of uploaded video.');
$videoSnippet->setTags(['tag', 'tag2', 'tag3']);
$videoSnippet->setTitle('Test video upload.');
$video->setSnippet($videoSnippet);
// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus();
$videoStatus->setEmbeddable(true);
$videoStatus->setLicense('youtube');
$videoStatus->setPrivacyStatus('private');
$video->setStatus($videoStatus);
$queryParams = [
'stabilize' => false
];
// TODO: For this request to work, you must replace "YOUR_FILE"
// with a pointer to the actual file you are uploading.
// The maximum file size for this operation is 64GB.
$response = $service->videos->insert(
'snippet,status',
$video,
$queryParams,
array(
'data' => file_get_contents($fullFilePath),
'mimeType' => 'video/*',
'uploadType' => 'multipart'
)
);
print_r($response);
So now I have several problems, which I don't know how to tackle.
Which $client->.... functions must be present if I'm already authorized (via OAuth playground)
How to refresh token with refresh token?
So far the only response I get is Google_Service_Exception
Message: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
It's my second day of trying to upload video via api with PHP and it's driving me nuts. I hope you guys will help me out.
If you need any additional informations, please let me know and I will provide. Thank you!!
UPDATE
After adding following code
$client->setAccessToken('<ACCESS_TOKEN>');
I get following errors
div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>An uncaught Exception was encountered</h4>
<p>Type: Google_Service_Exception</p>
<p>Message: {
"error": {
"errors": [
{
"domain": "youtube.quota",
"reason": "quotaExceeded",
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
],
"code": 403,
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
}
</p>
<p>Filename: /home/vagrant/workspace/spot-scouting-adminpage/rest/vendor/google/apiclient/src/Google/Http/REST.php</p>
<p>Line Number: 118</p>
Which is of course not true, since I have never made a single successful request to google. Here is prof:
Maybe the problem is that a have generated access key via developers.google.com???
You have missed just a small step to set access token.
Once you get the access token set it with google client :
$client->setAccessToken($accessToken);
And then use youtube service:
$service = new Google_Service_YouTube($client);
I am trying to build a very simplified piece of code that is to simply upload a local file from server to my personal drive account. Right now I am struggling with authentication issues, and not sure what kind of credential type I need.
Importantly, since this is only accessing my own private drive, I want to upload my credentials once and not have it ask in future. I am not trying to use oAuth to access my user's drives at all. It seems most documentation is for if we are trying to authenticate and access OTHER users drives?
I think I can manage the upload code once I can authenticate, but right now I can't even list my existing files.
Here is my code so far:
<?php
require_once 'google-api-php-client/vendor/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient($credentialsPath = ''){
$client = new Google_Client();
$client->setApplicationName('Google Drive API');
$client->setAuthConfig($credentialsPath); // saved some credentials from console, but not sure which ones to use?
$client->setScopes(Google_Service_Drive::DRIVE);
return $client;
}
// Get the API client and construct the service object.
$client = getClient($credentialsPath);
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
}
}
When I run this code I get the following error code:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "usageLimits", "reason": "dailyLimitExceededUnreg", "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "extendedHelp": "https://code.google.com/apis/console" } ], "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." }
The few things I looked at suggest this code is not about daily limit, but in fact incorrect usage of credentials. Any idea how I can fix this?
I'm trying to create an automation script with php which adds a new row of information to a google sheet that I've shared. I've been scouring tutorials all morning trying to figure this out but each method is different and doesn't seem to be exactly what I need to do. Essentially this script will be triggers when a form is submitted on my site. Its going to take the form data and drop is into my google sheet.
I've created a service account under my project, which is stored inside the json file that was downloaded. Here's the script I have now. It's giving me the following error
{ "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"
}
and here's the code I'm running. (yes its incomplete because I can't get past the auth)
public function index()
{
$this->load->helper("url");
require APPPATH . 'third_party/GoogleAPI/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . APPPATH . 'third_party/GoogleAPI/bdgsheets.json');
$client = new Google_Client;
$client->useApplicationDefaultCredentials();
$client->setApplicationName("Is this working");
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
$client->setAccessType('offline');
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
$sheets = new Google_Service_Sheets($client);
$data = [];
$current_row = 2;
$spreadsheet_id = "{my spreadsheet id here}";
$range = 'A1:H';
$rows = $sheets->spreadsheets_values->get($spreadsheet_id, $range, ['majorDimension' => 'ROWS']);
}
Thanks in advance for the help
Have you put the right scope when adding creating the access token. If you had used the scope value
"https://www.googleapis.com/auth/spreadsheets.readonly" instead of
"https://www.googleapis.com/auth/spreadsheets" you won't have write permission to the google sheet.
If you can share the code piece which creates the bdgsheets.json file it is easy to understand whether you have the "write" permission.
Also, try changing this piece of code
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
to
$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']);
and give it a shot
I'm trying to set publish permissions for gmail to a pubsub topic in google cloud.
The application where I implemented this code is running in AWS.
It's a PHP application and I'm using version 2.0.0-RC7 of the google PHP api client.
In code, I implemented the flow as described in the documentation:
Create a topic (Works)
Create a subscription (works)
Grant publish rights to gmail (here I get stuck)
The first two actions are done with the same google client instance, that is authenticated with the service account credentials.
The code:
$scopes = [
'https://www.googleapis.com/auth/pubsub',
'https://mail.google.com',
];
$pushEndpoint = 'https://some.url/google_notifications/';
$client = new Google_Client();
$client->setScopes($scopes);
$client->setAuthConfig($serviceAccountInfo);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$service = new Google_Service_Pubsub($client);
// This part works
$topicObject = new Google_Service_Pubsub_Topic();
$topicObject->setName($this->getTopicName());
$service->projects_topics->create($this->getTopicName(), $topic);
// This part also works
$push = new Google_Service_Pubsub_PushConfig();
$push->setPushEndpoint($pushEndpoint);
$subscription = new Google_Service_Pubsub_Subscription();
$subscription->setName($this->getSubscriptionName());
$subscription->setTopic($this->getTopicName());
$subscription->setPushConfig($push);
$service->projects_subscriptions->create($this->getSubscriptionName(), $subscription);
// This part gives the error
$binding = new Google_Service_Pubsub_Binding();
$binding->setRole('roles/pubsub.publisher');
$binding->setMembers(['serviceAccount:gmail-api-push#system.gserviceaccount.com']);
$policy = new Google_Service_Pubsub_Policy();
$policy->setBindings([$binding]);
$setRequest = new Google_Service_Pubsub_SetIamPolicyRequest();
$setRequest->setPolicy($policy);
try {
$result = $service->projects_topics->setIamPolicy($this->getTopicName(), $setRequest);
var_dump($result);
} catch (\Exception $e) {
echo $e->getMessage();
}
The result is always:
{
"error": {
"code": 403,
"message": "User not authorized to perform this action.",
"errors": [
{
"message": "User not authorized to perform this action.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
Can someone tell me what I'm doing wrong ?
It's really annoying to set those permissions by hand all the time.
Thanks.
To use projects.topics.setIamPolicy method your service account must have a "Pub/Sub Admin" role. You can change a role of the account by visiting "IAM & admin" page for your project: https://console.cloud.google.com/iam-admin/iam