Post the data with header in curl not working in php? - php

I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal
curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST
Same thing I have tried with php But it is giving the following error
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}
The following one I have tried
$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'name'=>'NEW USER',
'is_platform_access_only'=>'true',
));
//Adding Header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$developer_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.

I have rise the same question in Perl tag with Perl code. There I got answer by user #melpomene.
We should encode the data as JSON. It is working,
Then the final code is
$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);

Related

OAuth returns bad request message

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.

How to declare CURL body for CoinBase API call in php

I want use php curl to interact with coinbase api. Simple API calls that does not require data to be passed are successful. What I want to do is create address.
CLI curl works. The command line curl command sample is below:
curl https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' \
-d '{"name": "New receive address"}'
}
My php code excerpt
$apiurl = "https://api.coinbase.com";
$secret = "coinbase api secret";
$method = "POST";
$requestPath = "/v2/accounts/actualAccountID/addresses";
$body = "";
$url = $apiurl.$requestPath;
$data["name"] = "curl smj6 ary";
$body=json_encode($data);
$string = $timestamp.$method.$requestPath.$body;
$sig = hash_hmac('sha256', $string, $secret);
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if($method == "POST"){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$headers = [
"CB-ACCESS-KEY: xxx",
"CB-ACCESS-SIGN:$sig",
"CB-ACCESS-TIMESTAMP: $timestamp",
"CB-VERSION: 2018-03-21",
"accept: application/json;charset=utf-8"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
It returns
{"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Since it works with listing user. I guess th error occurs the way iam passing post data to curl.
Similar Questions that I found on SO but none solves my issue. Please help!
Invalid Signature Coinbase
CoinBase "invalid signature" PHP Buy API Request
How to declare CURL body for CoinBase API call
Api key authentication for coinbase
UPDATE:
$apiurl = "https://api.coinbase.com/v2/";
$requestPath = "accounts/$accountid/addresses";
returns same error
There are sites that convert the command line cURL syntax to PHP, like https://incarnate.github.io/curl-to-php/
I just pasted your command and:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
$headers[] = "CB-ACCESS-KEY: <your api key>";
$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Using cloudflare api to delete a file from cache not working

Here is my code for trying to delete a file a file via the api
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/<MY-ZONE-ID>/purge_cache");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = [
'X-Auth-Email: MYEMAIL',
'X-Auth-Key: MY-AUTH-KEY',
'Content-Type: application/json'
];
$data = json_encode(array("files" => "https://example.com/file/".$filename));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
The response i get is as follows
{
"success":false,
"errors":[
{
"code":1012,
"message":"Request must contain one of \"purge_everything\" or \"files\", or \"tags"
}
],
"messages":[
],
"result":null
}
Documentation says tag is optional so it should work
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
-H "X-Auth-Email: user#example.com" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"files":["http://www.example.com/css/styles.css"],"tags":["some-tag","another-tag"]}'
What am In doing wrong here ?
I maybe because your files property is not an array.
Try
$data = json_encode(array("files" => array("https://example.com/file/".$filename)));
This is a bit confusing. Post Data is usually sent in key value pairs.
Also when the post data is an array curl changes the content type to multipart/form-data
When post data is sent as a query string, it's in the format of key1=value1&key2=value2
It appears the json is the value with no key.
I would try it both as an array and string and look at the request header.
In the request header look at the content-type and the data.
To get the request header in the curl return add this option:
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
You may need to add:
curl_setopt($ch, CURLOPT_POST, true);
$data[] = json_encode(array('files'=>"https://example.com/file/$filename"));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$data = json_encode(array('files'=>"https://example.com/file/$filename"));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
PS: You do not need to use the . concatenation when using double quotes for $filename

Zoopla Sandbox with cURL http header error

I'm developing code for an estate agent to upload properties to Zoopla via their datafeed
I'm having problem adding a required profile to the http header that is required
The only example in the documentation is this test from linux:
echo '{ "branch_reference" : "test" }' |
curl --key /path/to/private.pem --cert /path/to/certificate.crt --data #-
--header "Content-type: application/json;
profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.1/schemas/listing/list.json"
https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list
I'm having a problem adding the profile to the http header in cURL
Here's my code:
$json['branch_reference']="test";
$json=json_encode($json);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSLKEY,'private.pem');
curl_setopt($ch, CURLOPT_SSLCERT,'zpg_realtime_listings_1468337696150754_20160712-20260710.crt');
curl_setopt($ch, CURLOPT_URL, "https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'profile: http://realtime-listings.webservices.zpg.co.uk/docs/v1.1/schemas/listing/list.json'
));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
if(curl_error($ch)){echo "CURL ERROR ".curl_error($ch)."<br>";}
$result = curl_exec($ch);
curl_close($ch);
echo $result;
The response I'm getting from Zoopla is:
{ "error_advice" : "The Content-Type header is missing the 'profile' parameter. Please supply 'profile', specifying the schema URL for the method you are calling: /sandbox/v1/listing/list", "error_name" : "missing_profile" }
Can anbody please advise on the correct way to add the profile to the header?
Thanx
From their example, it looks like you should be passing the whole string as a single Content-Type HTTP header, rather than two separate ones:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.1/schemas/listing/list.json'
);

PHP HTTP CURL PUT request for LIFX Power On/Off

I'm trying to power all of my Lifx bulbs on/off using PHP.
The API documentation, http://developer.lifx.com/, says to use a PUT request:
curl -u "c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192:" \
-X PUT \
-d "state=on" \
"https://api.lifx.com/v1beta1/lights/all/power"
Now using that curl command works in the command line. It prompts me for my password unless I add it after the colon in the "username".
The trouble is when I try to translate that command into PHP like so:
$authToken = 'c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192:myFakePassword';
$ch = curl_init('https://api.lifx.com/v1beta1/lights/all/power');
$headers = array("selector=all&state=on",'Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
This goes through, but I get a 404 Not Found which the Lifx documentation says is probably a malformed selector.
Note: I was able to make a successful call with PHP to toggle the power with this POST:
$authToken = 'c87c73a896b554367fac61f71dd3656af8d93a525a4e87df5952c6078a89d192';
$ch = curl_init('https://api.lifx.com/v1beta1/lights/all/toggle');
$headers = array("selector=all",'Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
But I don't want to just toggle the lights, I want to be able to specify on or off. What could be wrong with my PUT request?
Thank you for any suggestions.
Solved this by setting some other curl options:
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = "state=on";
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
$link is https://api.lifx.com/v1beta1/lights/all/power
$authToken is my api key

Categories