BigQuery: error to fetch query results from PHP - php

I've changed some configurations on BigQuery and actually I can't fetch data anymore.
This is the flow:
$query = "select what i need to select";
$client = new Google_Client();
$client->setApplicationName('Google-BigQuery');
$client->useApplicationDefaultCredentials(); // running in app engine env
$client->addScope('https://www.googleapis.com/auth/bigquery');
$client->addScope('https://www.googleapis.com/auth/devstorage.read_write');
$bq = new Google_Service_Bigquery($client);
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$queryConfig->setQuery($query);
Then:
$job = $bq->jobs->insert($project, $job); // OK
$jr = $job->getJobReference(); // OK -> here i got jobid as $jr['jobId']
$queryResults = $bq->jobs->getQueryResults('my-project', 'job-id-from-jr'); // ERROR
If I run the query from BigQuery dashboard, it's work and I can get results.
Here I got a 404 error, "notfound", I've checked if the job id match with that on the dashboard, and it match.
{ "error": { "code": 404, "message": "Not found: Job my-project:job-id",
The only one difference is that on the job inside the dashboard is specified the location as
my-name:europe-west1.job-id
Can't find a way to specify directly the zone of execution, I've tried to add europe-west1 as a string before job-id, but got error about that (it can't be done).
There is a way to fix this? It's possible to specify the zone?
Thanks!

Ok, solved by passing an array as 3rd parameter
$arrLocation = array("location" => "europe-west1");
$queryResults = $bq->jobs->getQueryResults('my-project', 'job-id-from-jr', $arrLocation);

Related

Cloud Firestore Authentication not working using PHP

I am new to firebase. I am testing a web application using the Firestore Database and PHP. https://github.com/googleapis/google-cloud-php-firestore. I have created a database "cities" and want to fetch the data only for the login User. I have set a rule on the database
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /cities/{city} {
allow read, write: if request.auth != null
}
}
}
Now after login is successful using email and password, I want to fetch the population of a city. I have checked firebase auth and it is showing me logged in.
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
console.log("Logged In"+uid)
} else {
console.log("Please login");
}
});
I am using the following PHP code.
$firestore = new FirestoreClient([
'projectId' => 'XXXXXXXX',
]);
$collectionReference = $firestore->collection('cities');
$documentReference = $collectionReference->document('kolkata');
$snapshot = $documentReference->snapshot();
echo "Population is " . $snapshot['population'];
Now I am getting the following error:
Fatal error: Uncaught Google\Cloud\Core\Exception\ServiceException: {
"message": "Missing or insufficient permissions.", "code": 7,
"status": "PERMISSION_DENIED", "details": [] }
Now when I change the security rule to allow read and write for all users, data are fetching properly.
I have searched the document but have not found any suggestions about the error.
Also, when I am using the keyfile along with the project id, I can fetch the data, but there is another issue. The security rule is not working anymore. I can read the data without logging in.
How can I solve this issue. Thanks in advance and sorry for the bad English.
$firestore = new FirestoreClient([
'projectId' => 'XXXXXX',
'keyFile' => json_decode(file_get_contents(__DIR__.'/secret/XXXXXXXX.json'), true)
]);

Prestashop WebService API - Update order status

I have been trying for a long time to update the status of an order from php with the prestashop webService library.
First I have tried to download the order, modify the "current_state" attribute and upload it via edit, without positive result, I always get the error message "other error"
Now I have seen that you can add an entry in "order_histories" but I am also unable to make it work:
$estadoID = (int)$_POST['estadosSelect'];
$idPedido = $_GET['id'];
$tienda = $_GET['tienda'];
$webService = $this->webServiceTienda($tienda);
try{
$opt = [
'resource' => 'order_histories?schema=blank'
];
$xml = $webService->get($opt);
$resources = $xml->children()->children();
var_dump( $resources );
$resources->id_order = $idPedido;
$resources->id_employee = 0;
$resources->id_order_state = $estadoID;
var_dump( $resources );
$opt = [
'resource' => 'order_histories',
'postXml' => $xml->asXML()
];
$createdXml = $webService->add($opt);
var_dump( $createdXml );
}catch (PrestaShopWebserviceException $e){
$this->controlErrores($e);
}
I keep getting the error code "other error", I have seen several examples, but I don't get it, any help is welcome: D
var_dumps
UPDATE: Debug info, i have 403 Forbidden, Access to this resource on the server is denied!
All options marked in prestashop backoffice, webservice
DEBUG
https://i.stack.imgur.com/1qKDd.png
UPDATE:
I have managed to update the order status in 1 of the four stores that I have connected, I use the same code and three of them are in the same version of prestashop, 1.7.6.9.
I get the error code 403, the webservice permissions are in the 4 stores the same.
Any ideas?
Thanks

Insert Task in Google Task API , Error: 403, message: Request had insufficient authentication scopes

I am trying to insert a new task into TaskList.
here is my code:
$client = getClient();
$service = new Google_Service_Tasks($client);
$optParams = array('maxResults' => 10);
$serviceTasklist = $service->tasklists->listTasklists($optParams);
$serviceTask = $service->tasks->listTasks("#default", $optParams);
try {
$task = new Google_Service_Tasks_Task();
$task->setTitle("here is new task");
$task->setNotes("this is note of new task");
$result = $service->tasks->insert("#default", $task);
return $result->getId();
} catch (Google_Exception $ggex) {
echo "\n Error: " . $ggex->getMessage();
}
I had tried to change scope from Google_Service_Task::TASK_READONLY to Google_Service_Task::TASK, included google task document also do a samething, but I tried then it not work . Can someone give my suggest or tell me know where am I wrong? Thank You !.
For documentation purpose:
The problem was in the token file itself. When you change the scopes you need to make sure to get a new updated token. If you still use the previous token is like haven't changed your code at all.

How to use Google MyBusiness API in php

I am using Google MyBsiness API for fetching all business reviews.
But I am unable to familer with PHP syntax and GET, POST method use in MYBusiness.
After Oath here are code i am using to fetch review
$mybusinessService = new Google_Service_Mybusiness($client);
$accessToken = file_get_contents($credentialsPath);
$reviews = $mybusinessService->accounts_locations_reviews;
echo '<pre>';print_r($reviews->get('ArtechDev'));exit;
But i am getting error 404 (Fatal error: Uncaught exception 'Google_Service_Exception' with message)
I am sure that I don't know how to pass param and which things needed for it. I am logged in as account which having Location 'ArtechDev' also please
let me know that where can i call
https://mybusiness.googleapis.com/v3/accounts/account_name/locations/location_name/reviews
Thanks
I hope you had found the answer to your question a long time ago, anyway I'll leave this hoping help someone else.
/*$accounts previusly populate*/
/*(GMB - v4)*/
$credentials_f = "google_my_business_credentials_file.json";
$client = new Google_Client();
$client->setApplicationName($aplicattion_name);
$client->setDeveloperKey($developer_key);
$client->setAuthConfig($credentials_f);
$client->setScopes("https://www.googleapis.com/auth/plus.business.manage");
$client->setSubject($accounts->email);
$token = $client->refreshToken($accounts->refresh_token);
$client->authorize();
$locationName = "accounts/#######/locations/########";
$mybusinessService = new Google_Service_Mybusiness($client);
$reviews = $mybusinessService->accounts_locations_reviews;
do{
$listReviewsResponse = $reviews->listAccountsLocationsReviews($locationName, array('pageSize' => 100,
'pageToken' => $listReviewsResponse->nextPageToken));
$reviewsList = $listReviewsResponse->getReviews();
foreach ($reviewsList as $index => $review) {
/*Accesing $review Object
* $review->createTime;
* $review->updateTime;
* $review->starRating;
* $review->reviewer->displayName;
* $review->reviewReply->comment;
* $review->getReviewReply()->getComment();
* $review->getReviewReply()->getUpdateTime();
*/
}
}while($listReviewsResponse->nextPageToken);
$acounts comes from:
$mybusinessService = new Google_Service_MyBusiness(...);
$accounts = $mybusinessService->accounts;

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

Categories