PHP CURL syntax for WIX - php

I'm using Wix's API to query products. I've made progress converting their examples to PHP but am stumped with their filtering method. For example, this basic query:
curl -X POST \
'https://www.wixapis.com/stores/v1/products/query' \
--data-binary '{
"includeVariants": true
}' \
-H 'Content-Type: application/json' \
-H 'Authorization: <AUTH>'enter code here
works fine when rewritten as:
public function getProducts($code){
$curl_postData = array(
'includeVariants' => 'true'
);
$params = json_encode($curl_postData);
$productsURL = 'https://www.wixapis.com/stores/v1/products/query';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $productsURL);
curl_setopt($ch, CURLOPT_HEADER, false);
$headers = [
'Content-Type:application/json',
'Authorization:' . $code
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
But I'm having trouble filtering to a specific collection. Here's their example:
curl 'https://www.wixapis.com/stores/v1/products/query' \
--data-binary '{
"query": {
"filter": "{\"collections.id\": { \"$hasSome\": [\"32fd0b3a-2d38-2235-7754-78a3f819274a\"]} }"
}
}' \
-H 'Content-Type: application/json' \
-H 'Authorization: <AUTH>'
And here's my interpretation of it ($collection is my variable to replace the fixed value in Wix's example):
public function getProducts($code, $collection){
$curl_postData = array(
'filter' => array(
'collections.id' => array(
'$hasSome' => $collection
)
)
);
$params = json_encode($curl_postData);
$productsURL = 'https://www.wixapis.com/stores/v1/products/query';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $productsURL);
curl_setopt($ch, CURLOPT_HEADER, false);
$headers = [
'Content-Type:application/json',
'Authorization:' . $code
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);
return $output;
}
The response is identical to the first example--I get all the products instead of just one collection. The problem is almost certainly my interpretation of their example. I think it's meant to be a multidimensional array, but I could be reading it wrong. I'd appreciate any suggestions.

In the second code block, the value of the filter property is not an object, but a JSON-encoded object. I'm not sure why the API requires that, but it means you have to use nested json_encode() in PHP.
$curl_postData = array(
'filter' => json_encode(array(
'collections.id' => array(
'$hasSome' => $collection
)
))
);

Thanks, Barmar. Your answer was correct with a minor change. Here's the final code segment that works properly.
$curl_postData = array(
'query' => array(
'filter' => json_encode(array(
'collections.id' => array(
'$hasSome' => $collection
)
))
)
);

Related

PHP run a curl command

I have this curl code
curl -X POST https://url.com -H 'authorization: Token YOUR_Session_TOKEN' -H 'content-type: application/json' -d '{"app_ids":["com.exmaple.app"], "data" : {"title":"Title", "content":"Content"}}
that is used for push notification from web service to a mobile application. How can I use this code in PHP? I can't understand the -H and -d tags
You can use this website to convert any of such:
https://incarnate.github.io/curl-to-php/
But basically d is the payload (the data which you send with the request: usually POST or PUT); H stands for headers: each entry is another header.
So the most 1-to-1 example would be:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://url.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"app_ids\":[\"com.exmaple.app\"], \"data\" : {\"title\":\"Title\", \"content\":\"Content\"}}");
$headers = array();
$headers[] = 'Authorization: Token YOUR_Session_TOKEN';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
but you can make it more dynamic and easy to manipulate based PHP variables by first creating an array with the attributes and then encoding it:
$ch = curl_init();
$data = [
'app_ids' => [
'com.example.app'
],
'data' => [
'title' => 'Title',
'content' => 'Content'
]
];
curl_setopt($ch, CURLOPT_URL, 'https://url.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers = array();
$headers[] = 'Authorization: Token YOUR_Session_TOKEN';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
I suggest reading the manual of php-curl:
https://www.php.net/manual/en/book.curl.php
You may also do it in the following way:
<?php
$url = "http://www.example.com";
$headers = [
'Content-Type: application/json',
'Authorization: Token YOUR_Session_TOKEN'
];
$post_data = [
'app_ids' => [
"com.exmaple.app"
],
'data' => [
'title' => 'Title',
'content' => 'Content'
],
];
$post_data = json_encode($post_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
// For debugging
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($response);

curl to php to post a json and audio

I'm trying to convert a curl command to be used in a php script
curl -k -F "request={'timezone':'America/New_York','lang':'en'};type=application/json" -F "voiceData=#d8696c304d09eb1.wav;type=audio/wav" -H "Authorization: Bearer x" -H "ocp-apim-subscription-key:x" "http://example.com"
and here is my php script
<?
$data = array("timezone" => "America/New_York", "lang" => "en", "voiceData" => "d8696c304d09eb1.wav");
$data_string = json_encode($data);
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer x',
'ocp-apim-subscription-key:x')
);
$result = curl_exec($ch);
?>
I understand that the send audio file bit is not right but i cant find an example how to post it.
I have edited this in response to the post fields but if I include $ch i get no output if don't include the output complains that no post request. Any ideas?
<?
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer x',
'ocp-apim-subscription-key:x')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
'voicedata' => new CURLFile("d8696c304d09eb1.wav")
)
);
$result = curl_exec($ch);
echo $result;
?>
You're missing the request= in your POST fields. Also, sending files using #filename is deprecated, you should use the CURLFile class.
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
'voicedata' => new CURLFile("d8696c304d09eb1.wav")
)
);

PHP Curl to form this Post Request

Can someone help me in forming this following POST request in PHP CURL ?
As mentioned in this URL : https://developer.amazon.com/public/apis/experience/cloud-drive/content/nodes
curl -v -X POST --form
'metadata={"name":"testVideo1","kind":"FILE"}' --form
'content=#sample_iTunes.mp4'
'https://content-na.drive.amazonaws.com/cdproxy/nodes?localId=testVideo1&suppress=deduplication'
--header "Authorization: Bearer
Atza|IQEBLjAsAhQ5zx7pKp9PCgCy6T1JkQjHHOEzpwIUQM"
this is what am trying... i want to form the above mentioned type curl request to the amazon server so i can upload a file into it. as there is no examples available am struck in this... can someone helps on this ?
$fields = array(
'multipart' => array(
'name' => 'testupload',
'content' => array(
'kind' => 'FILE',
'name' => 'hi.jpg',
'parents' => $parents
)
)
);
$fields_string = json_encode($fields);
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $contenttype);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
$httpstatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
You're almost there.
Add this on the curl code.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
This will able to access the url using SSL/HTTPS.

Azure API - PHP Request

Im trying to get this API working in PHP
The API documentation is here
https://studio.azureml.net/apihelp/workspaces/3e1515433b9d477f8bd02b659428cddc/webservices/aca8dc0fd2974e7d849bbac9e7675fda/endpoints/cb1b14b17422435984943d41a5957ec7/score
Im really stuck and im so close to getting it to work. Below is my current code if anyone can spot any errors. I have also included my API key as it will be changed once working.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14b17422435984943d41a5957ec7/execute?api-version=2.0&details=true';
$api_key = '5ve72/xxLuzaexQu7LyRBl1iRdGqAQiQ1ValodnS7DG+F0NzgHkaLyk1J30MXrlWFovzPzlurui/o5jeH7RMiA==';
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => ['Client_ID'],
'Values' => [ [ '0' ], [ '0' ], ]
),
),
'GlobalParameters' => array()
);
$body = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$api_key, 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo 'Curl error: ' . curl_error($ch);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
im still getting no error from curl_error and the var dump just says bool(false)
You had an issue with the element GlobalParameters, declare it as a StdClass instead of an empty array. Try this :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14b17422435984943d41a5957ec7/execute?api-version=2.0&details=true';
$api_key = '5ve72/xxLuzaexQu7LyRBl1iRdGqAQiQ1ValodnS7DG+F0NzgHkaLyk1J30MXrlWFovzPzlurui/o5jeH7RMiA==';
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => ['Client_ID'],
'Values' => [ [ '0' ], [ '0' ], ]
),
),
'GlobalParameters' => new StdClass(),
);
$body = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$api_key, 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $body . PHP_EOL . PHP_EOL;
echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
var_dump($response);
You have to run curl_error() after curl_exec() because curl_error() does return a string containing the last error for the current session. (source : php.net)
So go this way
$response = curl_exec($ch);
echo 'Curl error: ' . curl_error($ch);
And you should have a error telling you what is wrong.

Convert Terminal cURL Call to PHP cURL Request

I am trying to send a cURL request from PHP to ExpressPigeon.com RESTFUL API.
The documentation says that this is how to create contact in a list using cURL command:
curl -X POST -H "X-auth-key: 00000000-0000-0000-0000-000000000000" \
-H "Content-type: application/json" \
-d '{"list_id": 11,
"contacts": [
{"email": "john#doe.net",
"first_name":"John",
"last_name": "Doe"
},
{"email": "jane#doe.net",
"first_name":"Jane",
"last_name": "Doe"
}] }' \
https://api.expresspigeon.com/contacts
Here's what I did:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.expresspigeon.com/contacts');
$fields = array(
'list_id' => $this->list_code,
'contacts' => array('email' => $param['email'], 'first_name' => $param['first_name'], 'last_name' => $param['last_name'])
);
$this->http_build_query_for_curl($fields); //This generates the $this->post_data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $this->post_data);
$headers = array(
'X-auth-key: '.$this->api_key,
'Content-type: application/json',
'Content-Length: '.strlen(serialize($post))
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$res = (array) json_decode(curl_exec($ch));
curl_close($ch);
print_r($res);
function http_build_query_for_curl( $arrays, $prefix = null )
{
if ( is_object( $arrays ) ) {
$arrays = get_object_vars( $arrays );
}
foreach ( $arrays AS $key => $value ) {
$k = isset( $prefix ) ? $prefix . '['.$key.']' : $key;
if ( is_array( $value ) OR is_object( $value ) ) {
$this->http_build_query_for_curl( $value, $k );
} else {
$this->post_data[$k] = $value;
}
}
}
I have this as a result though:
Array
(
[status] => error
[code] => 400
[message] => required Content-type: application/json
)
you need to add one more level of array nesting to achieve the desired JSON output so that contacts is an array instead of an object:
$fields = array(
'list_id' => $this->list_code,
'contacts' => array(array('email' => $param['email'], 'first_name' => $param['first_name'], 'last_name' => $param['last_name']))
);
and then use json_encode on that; you add debug printouts and compare against what you need
Support just replied and this is the working code. I've tried it and it works! The only thing I did not do is the the SSL parameters on cURL. Thanks to Hans Z for his revision on my contacts array.
$fields = array(
'list_id' => $this->list_code,
'contacts' => array(array('email' => $param['email'], 'first_name' => $param['first_name'], 'last_name' => $param['last_name']))
);
$requestBody = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.expresspigeon.com/contacts");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','X-auth-key:'.$this->api_key));
$result = curl_exec($ch);
curl_close($ch);

Categories