Need assistance with PHP curl call - php

Hello: I am trying to do an API call using curl_init; have made some good progress but seem to be stuck...
we have an interface (swagger) that allows us to do the curl call and test it which works: here is the curl commands from that:
curl -X POST --header "Content-Type: application/x-www-form-urlencoded"
--header "Accept: application/json"
--header "Authorization: Bearer xxxxx-xxxxxx- xxxxx-xxxxxxx"
-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234" "http://xxxxxxxxx-xx-xx-201-115.compute-1.amazonaws.com:xxxx/api/users"
here is my attempt to do the same call in PHP code:
$json = '{
"username": "xmanxxxxxx%40gmail.com",
"password": "xxxx1234"
}';
$gtoken='xxxxxx-xxxxxx-xxx-xxxxxxxx';
$token_string="Authorization: Bearer ".$gtoken;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://exx-ccc-vvv-vvvv.compute-1.amazonaws.com:xxxx/api/users', //URL to the API
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HEADER => true, // Instead of the "-i" flag
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded','Accept: application/json',$token_string)
));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
$resp = curl_exec($curl);
curl_close($curl);
I am getting a response code "500" which makes me think that there is something wrong with my input. So I am wondering if anyone can help with this...

In your command line code, you post a standard URL encoded data string using -d "username=xxxxxxxx39%40gmail.com&password=xxxx1234" but in PHP you are creating a JSON string and sending it as a single post field (not properly URL encoded).
I think this is what you need:
$data = array(
'username' => 'xmanxxxxxx#gmail.com',
'password' => 'xxxx1234',
);
$data = http_build_query($data); // convert array to urlencoded string
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
As far as I can tell the rest of the code looks fine.
Also, you don't explicitly need to set the Content-Type header, cURL will do this for you when you pass a string to CURLOPT_POSTFIELDS. It will set it to multipart/form-data if you pass an array to CURLOPT_POSTFIELDS. But having it doesn't hurt anything either.

Related

Invalid value passed for JSONString Zoho inventory api

I am trying to use the zoho inventory api and converting thier sample curl code for use in php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://inventory.zoho.com/api/v1/salesorders");
$vars = array(
"authtoken" => "",
"organization_id" => "",
"JSONString" => '{
"customer_id": 4815000000044080,
}'
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Zoho-authtoken ',
'Content-Type: application/json;charset=UTF-8',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);
On the page I get this response
{"code":4,"message":"Invalid value passed for JSONString"}
The original code from the docs is
$ curl https://inventory.zoho.com/api/v1/salesorders?authtoken=ba4604e8e433g9c892e360d53463oec5&organization_id=10234695
-X POST
-H "Authorization: Zoho-authtoken ba4604e8e433g9c892e360d53463oec5"
-H "Content-Type: application/json;charset=UTF-8"
-d JSONString='{
"customer_id": 4815000000044080,
}'
I have tried various google searches and it seems that a lot of people have had this same issue and there is no answer given for it yet.
I believe I am trying to add the JSONString in the wrong way
What is the correct way to send the JSONString in php using curl?
Following is the C# code that will not give the following error:
"{"code":4,"message":"Invalid value passed for JSONString"}"` error.
I use a servise http://httpbin.org/post to look, how my post query looks for zoho.
and find an error with symbols \ufeff before JSONString, this is BOM encoding.
So, i change encoding and all right.
Look Example

Create HTTP GET Header Request

I am using php and I want to create a HTTP request to access some API data. I have a document that says, I need to place the following request
GET /abc/api/Payment HTTP/1.1
Content-Type: application/x-www-form-urlencoded
X-PSK: [App Key]
X-Stamp: [UTC Timestamp]
X-Signature: [HMACSHA256 base 64 string]
Body:
var1, var1
I have app key, I can get UTC Timestamp and I can create signature. I am not sure how to start creating this request? I am using codeingiter. If someone can help with example to set the header and body?
I also tried this url https://www.hurl.it/ to place requests but can't make it work. Any suggestions?
You want to use cURL's CURLOPT_HTTPHEADER option.
http://php.net/manual/en/function.curl-setopt.php
This should get you started
function request($url) {
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"X-PSK: [App Key]",
"X-Stamp: [UTC Timestamp]",
"X-Signature: [HMACSHA256 base 64 string]"
),
CURLOPT_FOLLOWLOCATION => true
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) die(curl_error($ch));
curl_close($ch);
return $answer;
}

Troubles "porting" cURL from bash to PHP

I'm trying to port this command to PHP:
curl -i -X POST http://website.com \
-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
-H "Accept: Application/json" \
-H "X-Requested-With: XMLHttpRequest" --data "var1=output1&var2=output2"
From bash it works.. I get this JSON output.
This is what I wrote in PHP to try to get the same result:
<?php
function blabla() {
$curl_parameters = array(
'var1' => "output1",
'var2' => "output2",
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://website.com");
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
"Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
"Accept" => "Application/json",
"X-Requested-With" => "XMLHttpRequest",
));
$output=curl_exec($ch);
curl_close($ch);
}
echo blabla();
?>
Unfortunately with this snippet I just get a 302 Found HTTP header as output (this).. seems like the variables are not passed (the --data part from the bash command).
The problem is with your CURLOPT_HTTPHEADER. It should be an array of strings like this:
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
'Accept: application/json',
'X-Requested-With: XMLHttpRequest',
));
How about just curl_setopt($ch,CURLOPT_POSTFIELDS, $curl_parameters);? I don't think you need to call http_build_query.
Try add curl follow 302 redirect
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Also make sure your http_build_query() function uses "&" as argument separator. On some PHP configurations it may be "& amp;" by default
$query = http_build_query($data, '', '&');

How to send json with curl to a url

I seek in stackoverflow a possible solution but any is good for me.
I will send the next json-rpc code to another file. This file contains a bottle server.
curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method":"leer_datos", "params": {"bd":"escuela","tabla":"secretaria"}}' http://localhost:8081/rpc/alchemy
Now, i have in a file the next code for use cURL:
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://localhost:8081/rpc/alchemy',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => "{'jsonrpc': '2.0','method':'leer_datos','params':{'bd':'escuela','tabla':'secretaria'}}"
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
I know the json is not well envoy.
How can i send the json to the url?
Sorry, my english is bad.
JSON data (key and value) must be only in "double quote".
{
"jsonrpc": "2.0",
"method": "leer_datos",
"params": {
"bd": "escuela",
"tabla": "secretaria"
}
}

How do I translate this command line curl into php curl?

I've got a command line curl bit of code that I want to translate into php. I'm struggling.
Here's the line of code
$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member
the big string would be a variable I'd pass into it.
What does this look like in PHP?
You first need to analyze what that line does:
$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member
It's not complex, you find all switches explained on curl's manpage:
-H, --header <header>: (HTTP) Extra header to use when getting a web page. You may specify any number of extra headers. [...]
You can add a header via curl_setopt_arrayDocs in PHP (all available options are explained at curl_setoptDocs):
$ch = curl_init('https://api.service.com/member');
// set URL and other appropriate options
$options = array(
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
);
curl_setopt_array($ch, $options);
curl_exec($ch); // grab URL and pass it to the browser
curl_close($ch);
In case curl is blocked, you can do that as well with PHP's HTTP capabilities which works even if curl is not available (and it takes curl if curl is available internally):
$options = array('http' => array(
'header' => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
));
$context = stream_context_create($options);
$result = file_get_contents('https://api.service.com/member', 0, $context);
1) you can use Curl functions
2) you can use exec()
exec('curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member');
3) you can use file_get_contents() if you only want the information as string...
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Authorization: 622cee5f8c99c81e87614e9efc63eddb"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.service.com/member', false, $context);
?>
You should look into the curl_* functions in php.
With curl_setopt() you can set the headers of the request.

Categories