I am creating a php script that will use curl to add a new row in my Parse database. I am having difficulty adding variables to my setopt statement. If anyone could lead me in the right direction, then I would greatly appreciate it.
This is my PHP code that is executing a curl statment:
//curl commands to send information to parse
$ch = curl_init('https://api.parse.com/1/classes/className');
curl_setopt($ch,CURLOPT_HTTPHEADER,
array('X-Parse-Application-Id:secret1',
'X-Parse-REST-API-Key:secret2',
'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"Name\":\"$deviceName\"}" );
echo curl_exec($ch);
curl_close($ch);
The response that I get back is:
{"code":107,"error":"invalid JSON"}
Thank you in advance!
Is there any reason you can't encode an array before sending the data?
For Example (untested):
$arr = [ "Name" => $deviceName ];
$arr_string = json_encode($arr);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($arr_string)
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr_string );
Related
Im trying to create a simple api that will post json to an endpoint using curl and php. its giving me an error whereby its saying unsupported media type and i need help seeing what it is i might be doing wrong, here is the code
<?php
$data = array("saleAmount"=>"2000","cashBack"=>"800","posUser"=>"John","tenderType"=>"SWIPE","currency"=>"RTGS","transactionId"=>'0001');
$payload = json_encode($data);
echo $payload;
// prepare curl
$ch = curl_init('http://localhost:9111/api/requests');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/jsonp',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
echo json_encode($result);
// Close cURL session handle
curl_close($ch);
?>
The issue is that your API is expecting a different media type than the one you are providing in your quest.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
Make sure that your API supports the content-type application/json
$url="";//path of api
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
$data = array("saleAmount"=>"2000","cashBack"=>"800","posUser"=>"John","tenderType"=>"SWIPE","currency"=>"RTGS","transactionId"=>'0001');
$data=json_encode($data);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$response=curl_exec($ch);
print_r($response);die;
curl_close($ch);
Append your url in $url and check this once.
I am trying to generate a token using OAuth 2.0
I redirect the user to the given URL,
User logs in, grants permission,
and then user is returned to my RETURN_URL
Below is the code for my RETURN_URL, and it gives following error:
{"code":400,"status":"Bad Request","timestamp":"2018-11-06T17:41:08+05:30","message":"Bad Request","error":{"reason":"Something wrong in request"}}
$code= $_GET[code];
$url = 'https://api.example.com/index/oauth/token';
$auth = $API_KEY.":".$API_SECRET ;
$header = array();
$header[] = 'Content-Type: application/json';
$header[] = 'x-api-key: '.$API_KEY;
$header[] = 'Authorization: Basic '. base64_encode($auth);
$data = array(
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $RETURN_URL
);
$data = trim(http_build_query($data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, $API_KEY.":".$API_SECRET );
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($curl, CURLOPT_USERPWD, "$API_KEY:$API_SECRET" );
curl_setopt($ch, CURLOPT_HEADER, 0);
$result= curl_exec($ch);
$error = curl_error($ch);
echo $result; exit;
curl_close($ch);
This is what their docs are saying for required parameters:
curl \
-u {your_api_key}:{your_api_secret} \
-H 'Content-Type: application/json' \
-H 'x-api-key: {your_api_key}' \
-d '{"code" : "{code_from_login_response}", "grant_type" : "authorization_code", "redirect_uri" : "{your_redirect_uri}"}' \
The reason you are getting a 400 bad request is because the API server that you are hitting is unable to understand the $data you sent and JSON decode it. Hence, below steps might help in sending a proper POST request with proper JSON-
Change $_GET[code] to $_GET['code']. It works without the single quotes but it does generate a notice of undefined constant 'code'. Also, you might want to filter this data for security reasons.
remove $data = trim(http_build_query($data));.
Change this line curl_setopt($ch, CURLOPT_POSTFIELDS, $data ); to curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) ); and you should be good to go.
The reason why this might be happening as far as I see is because probably API Server you are hitting is receiving your JSON data as $json = file_get_contents('php://input');, kind of like a webhook. So, when you made a request, it wasn't able to parse your data as JSON and hence sent you a bad request error.
I am talking to the Shutter Stock API. I am certain the problem is not SS but more the formatting of my PHP Curl post as if I send this request via terminal I get a proper response.
The Terminal curl comand is as follows:
curl "https://api.shutterstock.com/v2/images/licenses?subscription_id=$SUBSCRIPTION_ID" \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header "Content-Type: application/json" \
-X POST \
--data '{
"images": [
{ "image_id": "137111171" }
]
}
so I am playing with sending this as a PHP curl instead and here is what I have:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = new Object();
$params = {
'images' : {'image_id' : '137111171'}
};
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_decode($params));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
/*$json = json_decode($response, true);
if (json_last_error()) {
echo '<span style="font-weight:bold;color:red;">Error: ' . $response . '</span>';
} else {*/
return $response;
The response form Shutter Stock is "Decode body failure" which is a custom error response. I think the problem is in the $params variable and how it is formatted. Problem is that this is a post, I suspect that on the other side SS is decoding this in a specific way. The proper curl parameter is in the bash curl above as:
--data '{
"images": [
{ "image_id": "137111171" }
]
Does anyone have any suggestions about how to properly format this particular --data value so that I can send it as a POST?
Thanks
your PHP code contains invalid syntax, also PHP has no class named Object, but you're probably looking for StdObject, but even that doesn't make much sense here.. also you're not urlencoding $SUBSCRIPTION_ID . remove the invalid syntax parts, and use json_encode, not json_decode..
curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( array (
'images' => array (
array (
'image_id' => '137111171'
)
)
), JSON_OBJECT_AS_ARRAY ) );
(edit, going by the comments, the api requires applicable data to be an array instead of an object, thus i added the JSON_OBJECT_AS_ARRAY flag.)
I think you pass wrong CURLOPT_POSTFIELDS data. Try:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = [
'images' => ['image_id' => '137111171']
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;
I'm trying to write simple CURL request from server. Script looks like:
$ch = curl_init();
$url = 'http://URL/';
curl_setopt($ch, CURLOPT_URL, $url);
// ADD URL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Authorization: Basic Y291bn54adsASD78asd5LWFkbWlu'));
// ADD HEADER
curl_setopt($ch, CURLOPT_POST, 1);
// SAY IT'S POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response === false){
echo 'Curl error: ' . curl_error($ch);
}
else{
$sessionID = json_decode($response, true);
print_r($sessionID);
}
curl_close($ch);
Problem is that I need to add some x-www-form-urlencoded like: grant_type = value, login = value2, password=value3. But I just can't make it work.
Can somebody help please?
The values must be like they would be in an URL (hence the urlencoded), so:
grant_type=value&login=value2&password=value3
If values are not numbers, you will probably need to enclose them between quotes.
I have a web service that accepts GET, POST values as parameters. So far I used to call the data using a simple CURL script, as below:
http://localhost/service/API.php?key=some_password&request=some_request&p1=v1&p2=v2
This is successfully posted using "CURLOPT_POSTFIELDS":
$base_args = array(
'key' => 'some_password',
'request' => 'some_request',
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
The problem is, I need to also POST a JSON body to this service. I found out that this can be done by using "CURLOPT_POSTFIELDS", but also found out that I am not able to use both POST and JSON.
$data_string ="{'test':'this is a json payload'}";
$ch = curl_init('http://localhost/service/API.php');
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',
'Content-Length: ' . strlen($data_string)));
$result = curl_exec($ch);
echo ($result); // string returned by the service.
I can either set the POST values, OR set the JSON body, but not both. Is there a way I can push the two different types of values?
Try sending the json text via a variable:
$data = array('data' => "{'test':'this is a json payload'}", 'key' => 'some_password', 'request' => 'some_request');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
Then in your API you do:
var_dump(json_decode($_POST['data']));
You can still use the other key/request variables.
I could not find any way of sending both POST and JSON body at the same time. Therefore the workaround was to add the POST arguments as part of the JSON body.
$base_args = array(
'key' => '8f752Dd5sRF4p',
'request' => 'RideDetails',
'data' => '{\'test\',\'test\'}',
);
$ch = curl_init('http://localhost/service/API.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($base_args));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen(http_build_query($base_args)))
);
$result = curl_exec($ch);
echo ($result);
The full JSON can be returned by the API as below:
var_dump(json_decode(file_get_contents('php://input')));