How to decode pagination in JSON? - php

I am trying to populate my website with products using the API of chinavasion.com. I've successfully fetch a list of products under a certain category but the response JSON only gives 10 products and a pagination which I literally don't know how to use, I'm guessing that it might be the one limiting the list of products echo'd?
Here is the sample JSON response:
{
"products": [
{
"product_id": 19433,
"model_code": "CVABR-C405",
"short_product_name": "13.3 Inch Roof Mounted Car Monitor ",
"product_url": "http://www.chinavasion.com/china/wholesale/Car_Video/Roof_Monitors/13.3-Inch-Roof-Mounted-Car-Monitor/",
"category_name": "Car Video",
"category_url": "http://www.chinavasion.com/china/wholesale/Car_Video/",
"subcategory_name": "Roof Monitors",
"status": "In Stock"
},
.... and 9 more.
"pagination": {
"start": 0,
"count": 10,
"total": 53
}
}
And here is my PHP so far, I just want to echo all the short product name of all the item, thing is I only get 10 items but there is a total of 53 items. (which can be seen on the sample JSON response pagination total)
<?php
$API_KEY = '4rxVx5-bxo7ldVQ5GcPSmX8XeqcSZoTnJnxF7xhRr8g.';
$url = "https://secure.chinavasion.com/api/getProductList.php";
$data = array(
'key' => $API_KEY,
'categories' => array('Car Video')
);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
foreach($response['products'] as $res)
{
echo $res['short_product_name'],'<br />';
}
?>
So is there a way to fetch the other remaining 43 products at this point? I am not pretty sure if its possible or not as I am really pretty new to programming and haven't done JSON before, hope you guys can help me.

That pagination array is there to indicate that there are more items. You just got to pass a start variable to get the next 10. Think of it as an offset in SQL.

next 10 items:
$API_KEY = '4rxVx5-bxo7ldVQ5GcPSmX8XeqcSZoTnJnxF7xhRr8g.';
$url = "https://secure.chinavasion.com/api/getProductList.php";
$data = array(
'key' => $API_KEY,
'categories' => array('Car Video'),
'pagination' => array('start' => 10)
);
$content = json_encode($data);
changing the 'pagination' => 'start' parameter you can set the starting item index.
EDIT:
you must insert the 'start' parameter inside the 'pagination' array.
An alternative way is to set the 'count' parameter to a big number. This way,you'll receive all items on a single call
$API_KEY = '4rxVx5-bxo7ldVQ5GcPSmX8XeqcSZoTnJnxF7xhRr8g.';
$url = "https://secure.chinavasion.com/api/getProductList.php";
$data = array(
'key' => $API_KEY,
'categories' => array('Car Video'),
'pagination' => array('count' => 999)
);

Related

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.

PHP sending JSON list of dictionaries as POST data

Hi i am trying to send a post request to an API, using PHP.
I have the following code. The API expects products to be a list of dictionaries like
[{"id":1, "name": "nyan"}, {"id": 2, "name": "cat"}]
I have the following code, which seems to be sending it correctly, but the API doesn't accept it, i am supposing that it is to do with the way PHP arrays are encodede, but can't really figure it out, any help is appreciated.
<?php
$data = array(
key => "API_KEY",
private_key => "PRIVATE_API_KEY",
products => array(array(id => 73,
name => "A nice t-shirt",
description => "A nice t-shirt with a picture of a cat",
price => 9.95,
brand => "Cat t-shirts",
category => 11,
rating => 5))
);
$data_string = json_encode($data);
$ch = curl_init('http://api.clerk.io/v2/product/add');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: application/json');
$result = curl_exec($ch);
echo $result;
You don't need to convert it to JSON String,
So remove following line,
$data_string = json_encode($data);
And update following line,
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
http_build_query() generates URL-encoded query string from Array.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
Add Content length in your header
$data = array(
key => "API_KEY",
private_key => "PRIVATE_API_KEY",
products => array(
array(id => 73,
name => "A nice t-shirt",
description => "A nice t-shirt with a picture of a cat",
price => 9.95,
brand => "Cat t-shirts",
category => 11,
rating => 5
)
)
);
$data_string = json_encode($data);
echo '<br>'.$data_string;
you will get the products dictionaries from 'products' key. so you just have to pass 'products' key data to API.

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.

zendesk geckoboard custom widget

We are making use of Geckoboard.com and Zendesk.
I am in the process of creating a custom widget for Geckoboard to get some info (The top ticket solvers) and list them.
For now, I am just trying to push some dummy/hard-coded info to the widget.
My code is as follows:
<?php
$curl = curl_init('https://COMPANY_SUBDOMAIN.zendesk.com/api/v2/views/MY_ZD_VIEW_ID/execute.json');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, 'USER_EMAIL/token:MY_UNIQUE_KEY');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$values = array(
"api_key" => "MY_UNIQUE_KEY",
"data" => array(
"item" => array(
"title" => "hello",
"text" => "Some text here"
)
)
);
$v = json_encode($values);
curl_setopt_array($ch = curl_init(), array(
CURLOPT_URL => "https://push.geckoboard.com/v1/send/MY_WIDGET_ID",
CURLOPT_POSTFIELDS => $v,
)
);
curl_exec($ch);
curl_close($ch);
?>
All the data in CAPS is my own info.
The message I get when I execute the file:
{"message":"The property 'text' is not defined "}
Any help will be greatly appreciated.
Sorry I am still relatively new to JSON & CURL
I have managed to solve this. Working code below:
<?php
$curl = curl_init('https://{YOUR ZENDESK SUBDOMAIN}.zendesk.com/api/v2/views/{VIEW ID}/execute.json');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, '{EMAIL}/token:{TOKEN}');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$responseToday = curl_exec($curl);
$resultsToday = json_decode($responseToday, true);
$values = array(
"item" => array(
"type" => 1,
"text" => "Some text here"
)
);
$v = json_encode($values);
//Simply print this out for the client to consume
echo $v;
/* We don't need this if we're not pushing the widget
curl_setopt_array($ch = curl_init(), array(
CURLOPT_URL => "https://push.geckoboard.com/v1/send/{UNIQUE ID}",
CURLOPT_POSTFIELDS => $v
));
curl_exec($ch);
curl_close($ch);
*/
?>

Categories