How to send batch request with Google Indexing API - php

I'm following Google indexing API
And I want to send batch request with Google_Service_Indexing.
In PHP, please help me. How to do it.
In Google document, this is Google_Service_Books.
I tried with PHP like :
//set google client
$client = new Google_Client();
$client->setAuthConfig('my_key.json');
$client->addScope('https://www.googleapis.com/auth/indexing');
$client->setUseBatch(true);
//set batch
$batch = new Google_Http_Batch($client);
//set service
$service = new Google_Service_Indexing($client);
$postBody = new Google_Service_Indexing_UrlNotification();
$postBody->setType('URL_UPDATED');
$postBody->setUrl('https://my_job_detail');
$service->urlNotifications->publish($postBody);
$batch ->add($service);
$results = $batch->execute();
And I stuck in error :
Argument 1 passed to Google_Http_Batch::add() must implement interface Psr\Http\Message\RequestInterface, instance of Google_Service_Indexing_UrlNotification given, called in /Applications/MAMP/htdocs/Jukukoushi/src/Controller/ToppagesController.php on line 340
Request URL: /

I tried with PHP and completed.
//init google client
$client = new Google_Client();
$client->setAuthConfig('your_path_to_key.json');
$client->addScope('https://www.googleapis.com/auth/indexing');
$client->setUseBatch(true);
//init google batch and set root URL
$batch = new Google_Http_Batch($client,false,'https://indexing.googleapis.com');
//init service Notification to sent request
$postBody = new Google_Service_Indexing_UrlNotification();
$postBody->setType('URL_UPDATED');
$postBody->setUrl('https://your_job_detail');
//init service Indexing ( like updateJobPosting )
$service = new Google_Service_Indexing($client);
//create request
//$service->urlNotifications->createRequestUri('https://indexing.googleapis.com/batch');
$request_kame = $service->urlNotifications->publish($postBody);
//add request to batch
$batch ->add($request_kame);

Related

Undefined type 'Google_Service_Oauth2' intelephense(1009) PHP

I currently modify my php script using namespace. I've done with the scripts but there are problem with Google API package
// create Client Request to access Google API
$client = new \Google_Client(); => THIS ONE WORKS
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
$accessToken = $key;
// Get $id_token via HTTPS POST.
try{
$arrToken = $client->setAccessToken($accessToken);
// get profile info
$google_oauth = new \Google_Service_Oauth2($client); => IT DOESNT
$google_account_info = $google_oauth->userinfo->get();
$checkEmail = $google_account_info->email;
$name = $google_account_info->name;
$googleId = $google_account_info->id;
}
Here is the error
Undefined type 'Google_Service_Oauth2' intelephense(1009)
If I do not use namespace, it has no problem. This one really weird.

How to watch Google Calendar Push notifications channel using PHP

I'm following these guides:
https://developers.google.com/calendar/quickstart/php
https://developers.google.com/calendar/v3/push
I'm using these libraries:
https://github.com/googleapis/google-api-php-client-services
https://github.com/googleapis/google-api-php-client
Here's my current code:
// Get the API client and construct the service object.
// this comes from the Quickstart example:
// https://developers.google.com/calendar/quickstart/php
$client = getClient();
$service = new Google_Service_Calendar($client);
// My code to start watching a channel:
$channel = new Google_Service_Calendar_Channel($client);
// where do I get this ID?
//$channel->setId('20fdedbf0-a845-11e3-1515e2-0800200c9a6689000');
$channel->setType("web_hook");
$channel->setToken('target=myApp-myCalendarChannelDest2');
$channel->setAddress("https://beta.example.com/incoming");
$timetoExpire = time()+360000;
$optParams = array(
'ttl' => $timetoExpire,
);
$channel->setParams($optParams);
$calendarId = 'developer#example.com';
$watchEvent = $service->events->watch($calendarId ,$channel);
Questions:
How do I start watching the channel for my calendar using those libraries?
Where do I get resourcePath for my calendar? (which is to be used in the above setId() method?

How to fetch auth token for service account using google API?

I have a Wordpress site (running PHP) that needs to display its own analytics data to visitors using the google-api. I want to create the charts in Javascript, so I need to fetch an auth token from the PHP code and then pass that to the Javascript code. I can't figure out how to get the auth token.
So far, I have code similar to this working using my service account:
https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
My code:
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");
$analytics = new Google_Service_Analytics($client);
$ga = $analytics->data_ga;
$start = date('Y-m-d', strtotime('-7 days'));
$end = date('Y-m-d');
$views = $ga->get('ga:'.$myAnalyticsId,
$start,
$end,
'ga:pageviews,ga:sessions,ga:newUsers',
array(
'dimensions' => 'ga:date',
'sort' => 'ga:date'
));
This all works, and I'm able to connect to Google_Service_Analytics and fetch analytics data. However, I can't figure out how to fetch a service access token using my credentials, that I can hand off to the Javascript code so I can use the Google Analytics API from Javascript.
This doesn't work:
$token = $client->getAccessToken();
Token just ends up being null. What do I need to do to fetch a token?
Here is the working code for me.
The service account has a different type of process for generating access token.
It is not following oauth client api.
//include_once 'vendor/autoload.php';
$credentialsFilePath = 'test.json';
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
print_r($token);
$accessToken = $token['access_token'];
Figured this out:
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
First answer still works in 2021 (Thanks!), but a used function is deprecated (still available though)
This worked for me
public function getToken() {
$client = new Client(); // use Google\Client;
$client->setAuthConfig('securejsonfile.json');
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$client->setApplicationName('appname');
$client->fetchAccessTokenWithAssertion();
return $client->getAccessToken(); //array
}

Batch request Google Calendar php API

I'm working on a google Calendar sync with my application.
I'm using the latest google-api-php-client
Now I want to update all my event, so i want to use the batch operation.
The example code of the php client api is:
$client = new Google_Client();
$plus = new Google_PlusService($client);
$client->setUseBatch(true);
$batch = new Google_BatchRequest();
$batch->add($plus->people->get(''), 'key1');
$batch->add($plus->people->get('me'), 'key2');
$result = $batch->execute();
So when I "translate" it to the calendar API, I become the following code:
$client = new Google_Client();
$this->service = new Google_CalendarService($client);
$client->setUseBatch(true);
// Make new batch and fill it with 2 events
$batch = new Google_BatchRequest();
$gEvent1 = new Google_event();
$gEvent1->setSummary("Event 1");
$gEvent2 = new Google_event();
$gEvent2->setSummary("Event 2");
$batch->add( $this->service->events->insert('primary', $gEvent1));
$batch->add( $this->service->events->insert('primary', $gEvent2));
$result = $batch->execute();
But when I run this code, I get this error:
Catchable fatal error: Argument 1 passed to Google_BatchRequest::add()
must be an instance of Google_HttpRequest, instance of Google_Event given
And I do not think that "$plus->people->get('')" is a HttpRequest.
Does anybody know what I do wrong, or what method / object I should use to add in the batch?
Or what the correct use of the batch operation for the calendar is?
Thanks in advance!
I had the same problem while working with inserts to the MirrorService api, specifically with timeline items. What is happening is that the the Google_ServiceRequest object is seeing that you've set the useBatch flag on the client and is actually returning returning Google_HttpRequest object before executing the call to Google but the insert statement in the calendar service doesn't properly handle it as such and ends up returning the calendar event object instead.
It also looks like your params to batch->add are backwards. Should be:
$batch->add( $this->service->events->insert($gEvent1, 'primary'));
Here is my modification to the insert method (you'll need to do this in the calendar service with the proper object input to the method). Just a few lines to make it check what class is coming back from the ServiceRequest class:
public function insert(google_TimelineItem $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
if(get_class($data) == 'Google_HttpRequest'){
return $data;
}else{
return new google_TimelineItem($data);
}
} else {
return $data;
}
}
you can use this code to insert events in batch:
public function addEventInBatch($accessToken, $calendarId, array $events)
{
$client = new Google_Client();
$client->setAccessToken($accessToken);
$client->setUseBatch(true);
$service = new Google_Service_Calendar($client);
$batch = $service->createBatch();
collect($events)->each(fn ($event) => $batch->add($service->events->insert($calendarId, $event)));
return $batch->execute();
}

Guzzle cookies handling

I'm building a client app based on Guzzle. I'm getting stucked with cookie handling. I'm trying to implement it using Cookie plugin but I cannot get it to work. My client application is standard web application and it looks like it's working as long as I'm using the same guzzle object, but across requests it doesn't send the right cookies. I'm using FileCookieJar for storing cookies. How can I keep cookies across multiple guzzle objects?
// first request with login works fine
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/123.php?a=b');
// second request where I expect it working, but it's not...
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);
$client->get('/another-test/456');
You are creating a new instance of the CookiePlugin on the second request, you have to use the first one on the second (and subsequent) request as well.
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
//First Request
$client = new Guzzle\Http\Client();
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/first');
//Second Request, same client
// No need for $cookiePlugin = new CookiePlugin(...
$client->get('/test/second');
//Third Request, new client, same cookies
$client2 = new Guzzle\Http\Client();
$client2->addSubscriber($cookiePlugin); //uses same instance
$client2->get('/test/third');
$cookiePlugin = new CookiePlugin(new FileCookieJar($cookie_file_name));
// Add the cookie plugin to a client
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);
// Send the request with no cookies and parse the returned cookies
$client->get($domain)->send();
// Send the request again, noticing that cookies are being sent
$request = $client->get($domain);
$request->send();
print_r ($request->getCookies());
Current answers will work if all requests are done in the same user request. But it won't work if the user first log in, then navigate through the site and query again later the "Domain".
Here is my solution (with ArrayCookieJar()):
Login
$cookiePlugin = new CookiePlugin(new ArrayCookieJar());
//First Request
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);
$request = $client->post('/login');
$response = $request->send();
// Retrieve the cookie to save it somehow
$cookiesArray = $cookiePlugin->getCookieJar()->all($domain);
$cookie = $cookiesArray[0]->toArray();
// Save in session or cache of your app.
// In example laravel:
Cache::put('cookie', $cookie, 30);
Other request
// Create a new client object
$client = new Client($domain);
// Get the previously stored cookie
// Here example for laravel
$cookie = Cache::get('cookie');
// Create the new CookiePlugin object
$cookie = new Cookie($cookie);
$cookieJar = new ArrayCookieJar();
$cookieJar->add($cookie);
$cookiePlugin = new CookiePlugin($cookieJar);
$client->addSubscriber($cookiePlugin);
// Then you can do other query with these cookie
$request = $client->get('/getData');
$response = $request->send();

Categories