Cloud Firestore add multiple document using REST API - PHP - php

I am trying to add multiple documents in one connection using google cloud firestore REST API. I can do this for single documant, but when I try to add more than one, I get an error.
The code I use to add a single document
$data = array(
'fields' => array(
'Field1' => array(
'stringValue' => 'deneme'
),
'Field2' => array(
'stringValue' => 'deneme2'
)
),
);
//$data = array_values($data);
$data_string = json_encode($data);
echo $data_string;
curl_setopt($ch, CURLOPT_URL, 'https://firestore.googleapis.com/v1beta1/projects/***/databases/(default)/documents/deneme/DEN6600011/TARIH');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$headers = [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Bearer (MY-API-KEY)'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$sonuc = curl_exec($ch);
curl_close($ch);
echo $sonuc;
I tried to do this by changing the data array like this but at that time I get an error.
$data = array(
"documents" => array(
array('fields' => array(
'Field1' => array(
'stringValue' => 'deneme'
),
'Field2' => array(
'stringValue' => 'deneme2'
)
)),
array('fields' => array(
'Field1' => array(
'stringValue' => 'deneme'
),
'Field2' => array(
'stringValue' => 'deneme2'
)
)),
));
Error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"documents\" at 'document': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "document",
"description": "Invalid JSON payload received. Unknown name \"documents\" at 'document': Cannot find field."
}
]
}
]
}
}
I tried it in other ways, but I got errors in all of them. How can I add multiple data using single JSON with REST API?

You could use update to create multiple document
the update operation will create the document that does not exist, you should also provide the document id.
A similar question was asked here
Alternatively, you could try using the PHP Library.
Using create or set you will be able to create multiple document in one request.
As for the issue with your current way, this most-likely due to the json request body not being well defined.

Related

Can't get data from Firestore using pure PHP and REST API

So, after spending ~4 hours trying to get data from a Firestore database, I've ended up with this code:
$firestoreUrl = 'https://firestore.googleapis.com/v1/projects/[MY-PROJECT-ID]/databases/(default)/documents/users';
$query = http_build_query([
"structuredQuery" => [
"select" => [
"fields" => [
"fieldPath" => "email"
]
],
"where" => [
"fieldFilter" => [
"field" => [
"fieldPath" => "email"
],
"op" => "EQUAL",
"value" => [
"stringValue" => "test#gmail.com"
]
]
],
"from" => [
"collectionId" => "users"
]
]
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $firestoreUrl . $query);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer [MY-ACCESS-TOKEN]']);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch);
and the response is:
{} with HTTP/2 200.
When I remove the $query from the curl url, I'm getting the whole records of the database.
I've also tried to use json_encode() on $query, but nothing happens as well. Still getting this {} with HTTP/2 200 response.
Any help?

Stripe API create SKU

I need to create a SKU via stripe API.
The problem is in inventory field.
Stripe api response is:
'error' => [
'message' => 'Invalid hash',
'param' => 'inventory',
'type' => 'invalid_request_error'
]
My php code is:
$endPoint = 'https://api.stripe.com/v1/skus';
$APIKEY_TEST = 'my_api_key';
$headers = array('Authorization: Bearer '.$APIKEY_TEST);
$sku = [
'active' => 'true',
'inventory' => ['quantity' => 10000000 ,'type' => 'infinite', 'value' => null],
"currency" => "eur",
"price" => $price,
"product" => $stripe_product_id
];
$array_string ='';
foreach($sku as $key => $value) {
$array_string .= $key.'='.$value.'&';
}
rtrim($array_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $endPoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
In stripe api docs inventory is hash type field.
I have tried json_encode() without luck.
Maybe the problem is in sending an array instead of a hash.
In $sku array, inventory field is also an nested associative array.
Maybe the problem resides there as well.
Is there a way to send CURLOPT_POSTFIELDS containing inventory so that stripe accepts it?
EDIT:
In Stripe dashboard i can see my request:
{
"active": "true",
"inventory": "Array",
"currency": "eur",
"price": "3",
"product": "prod_F6ipvfYFvOxxQq"
}
Inventory field has no data, but instead "Array".
After trying a lot of possible solutions, i found the answer:
$post_array = http_build_query($sku);
And know stripe accepts the $sku array with nested inventory array.
It worth notice that stripe does not accept JSON in requests.
The request has to be url encoded.

Clarifai search (curl) how to get more images per call

I am trying to get more than 20 images with the searches endpoint:
$data = '{
"query": {
"ands": [
{
"output": {
"input": {
"data": {
"image": {
"url": "' . $url . '"
}
}
}
}
}
]
}
}';
$ch = curl_init('https://api.clarifai.com/v2/searches?
page=1&per_page=30');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Key " . self::$clarify_user_apikey,
"Content-Type: application/json")
);
$output = curl_exec($ch);
curl_close($ch);
The images are initialized above in the $data variable.
Does the image search not have pagination and per_page attributes, or what am I doing wrong?
However I change the two attributes, I always get a max of 20 images back. The App / Project in question has more than 70k images, and the explorer app shows more images as well.
Thanks!
I found the answer.
For easier understanding I formatted the JSON part into an array.
$data = array(
"query" => array(
"ands" => array(
array(
"output" => array(
"input" => array(
"data" => array(
"image" => array(
"url" => $url
)
)
)
)
)
)
),
"pagination" => array(
"page" => 1,
"per_page" => 100
),
);
This code gives 100 images back. I haven't seen an upper limit yet, but it seems to work fine with 500 images as well. The request call gets slow then, though.

Slack sends invalid, mal-formed JSON data after Dialog interaction

I am working on a slash command that'll invoke a dialog.
$dialog = [
'callback_id' => 'ryde-46e2b0',
'title' => 'Request a Ride',
'submit_label' => 'Request',
'elements' => [
[
'type' => 'text',
'label' => 'Pickup Location',
'name' => 'loc_origin'
],
[
'type' => 'text',
'label' => 'Dropoff Location',
'name' => 'loc_destination'
]
]
];
// get trigger ID from incoming slash request
$trigger = filter_input(INPUT_POST, "trigger_id");
// define POST query parameters
$query = [
'token' => 'XXXXXXXXX MY TOKEN XXXXXXXXX',
'dialog' => json_encode($dialog),
'trigger_id' => $trigger
];
// define the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
var_export($response);
When I issue the slash command, my test dialog opens successfully
I then fill two test values test1 and test2 in the fields and submit the request. My endpoint is being hit with the dialog data payload correctly, but the data sent is not valid JSON:
The value of $_POST is: (I've masked all identifying tokens/IDs with xxx)
{"payload":"{\\\"type\\\":\\\"dialog_submission\\\",\\\"token\\\":\\\"XXX\\\",\\\"action_ts\\\":\\\"1536603864.688426\\\",\\\"team\\\":{\\\"id\\\":\\\"xxx\\\",\\\"domain\\\":\\\"ourdomain\\\"},\\\"user\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"my_name\\\"},\\\"channel\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"directmessage\\\"},\\\"submission\\\":{\\\"loc_origin\\\":\\\"test1\\\",\\\"loc_destination\\\":\\\"test2\\\"},\\\"callback_id\\\":\\\"ryde-46e2b0\\\",\\\"response_url\\\":\\\"https:\\\\/\\\\/hooks.slack.com\\\\/app\\\\/XXX\\\\/XXX\\\\/XXX\\\",\\\"state\\\":\\\"\\\"}"}
This is an invalid JSON, even when the "\\" instances are removed. Why is this happening?
Here is the code that handles the POST from Slack:
error_log(" -- dialog response: " . json_encode($_POST) . "\n", 3, './runtime.log');
Which results in the output above.
I'm not sure why you are calling json_encode($_POST). The documentation is very clear on the format that will be sent:
$payload = filter_input(INPUT_POST, 'payload');
$decoded = json_decode($payload);
var_dump($decoded);

Square API Create Item working code now returning an error

After creating about 1000 inventory items with code, Square suddenly started returning an error.
The error returned was:
{"type":"bad_request","message":"'name' is required"}
Example code:
$postData = array(
'id' => 'test_1433281486',
'name' => 'test',
'description' => 'test',
'variations' => array(
'id' => 'test_v1433281486',
'name' => 'Regular',
'price_money' => array(
'currency_code' => 'USD',
'amount' => '19800',
),
),
);
$json = json_encode($postData);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $access_token, 'Content-Type: application/json', 'Accept: application/json'));
curl_setopt($curl, CURLOPT_URL, "https://connect.squareup.com/v1/me/items");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
$json = curl_exec($curl);
curl_close($curl);
Here is the json_encoded string:
{
"id":"test_1433281486",
"name":"test",
"description":"test",
"variations": {
"id":"test_v1433281486",
"name":"Regular",
"price_money": {
"currency_code":"USD",
"amount":"19800"
}
}
}
I have tried everything I know to do a simple Create Item with code now, but it no longer works. Always returns the message "name" is required. My code to update images, fees, categories etc still works perfectly - just can't create.
I still have 100's of new inventory items to add, so getting this to work is imperative to business.
Variations needs to be passed in as an array. Here is how the JSON should look:
{
"id":"test_1433281486",
"name":"test",
"description":"test",
"variations": [{
"id":"test_v1433281486",
"name":"Regular",
"price_money": {
"currency_code":"USD",
"amount":"19800"
}
}]
}
Thanks for the report! We will update our error messaging to send the proper message if variations is not passed in as an array.
This is for all the PHP developers. Here is an updated Create Item PHP array that is compatible with Square. Notice the nested "variations" arrays.
Square now (6/15) requires brackets in JSON arrays - PHP json_encode() does not produce them unless you add nested arrays.
$postData = array(
'id' => 'test_1433281487',
'name' => 'test2',
'description' => 'test2',
'variations' => array(array(
'id' => 'test_v1433281487',
'name' => 'Regular',
'price_money' => array(
'currency_code' => 'USD',
'amount' => '19800',
),
)),
);
$json = json_encode($postData);
Here's another example of JSON brackets in PHP.
Here is the PHP json_encode() documentation.

Categories