I am trying to create an API using cURL & JSON.
Now In my first PHP file I am sending data as JSON data, Like below:
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
But on my SERVER where I get this request when I show (using var_export()) the values:
public function login()
{
$client_data = $this->input->post();
var_export($client_data);
}
Error:
array ( '"{\u201cRequest\u201d:\u201cLogin\u201d,\u201cUsername\u201d:\u201cBIZRTC\u201d,\u201cAPIAccessKey\u201d:\u201cAW342FFGRTR56RTH\u201d,\u201cGMT-Timestamp\u201d:_\u201c1489670000\u201d}"' => '', 0 => '', )
Even if I decode it there I still get \u. Also I dont understand how are these values appended : at starting : '"{\\u201c and this \\u201d}"' => '', 0 => '', at the back.
What are these values?
How do I decode this JSON?
Am I Posting right data to Server?
Updated code
Client.php
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
Server.php
public function login()
{
var_export($_POST);
}
You need to give array in json_encode, Instead of string.
Replace:
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
To:
$field_string= '{
"Request": "Login",
"Username": "anonymous",
"APIAccessKey": "AW342FFGRTR56RTH",
"GMT-Timestamp": "1489670000"
}';
Problems in code:
Incorrect json.
Invalid quotes(”) in json.
Passing string in json_encode.
if you are storing json string in variable then you don't need the json_encode() because it is used to convert array to json string.
$field_string = '{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}';
$json = $field_string;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
it is because of below line
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
suppose to be like this
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);
Related
Not going to succeed when trying to send data using post method. Never used it before.
This is code of executing curl:
$url = LICENSE_URL."validate_system_key/validate_key/";
//url-ify the data for the POST
$data['system_key']='A8Z0-X1N7-S1V2-Y1I5';
$data['domain']='http://example.com';
$fields_string = '';
foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10); # timeout after 10 seconds, you can increase it
//curl_setopt($ch,CURLOPT_HEADER,false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); # Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$result=json_decode($result,TRUE);
And this is the Code On Client Url:
public function validate_key(){
$system_key=$_POST['system_key'];
$domain=$_POST['domain'];
$result['error']=3;
echo json_encode($result);
}
Note: When I am not using POST method (sending data through url) evrything is fine. Its all about POST method, not getting the mistake! Any kind of help will be appreciated! Thanks.
Use array instead of String in data passed to string like below:
foreach($data as $key=>$value) {
$data[$key] = $value;
}
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
I hope this will work.
I currently have an API script that returns JSON. It has worked up until I tried to add in a curl php POST script before it. The curl script is working on it's own, and it is also working in the API script. However the JSON code is not being returned.
Is there something fundamentally wrong with this approach below?
Thanks in advance.
EDIT: The curl script works 100% on its own.
Said script is also working inside the below, it's just that the JSON does not return.
$name = "foo";
$age = "bar";
//set POST variables
$url = 'https://www.example.com';
$fields = array(
'name' => urlencode($name),
'age' => urlencode($age)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return json_encode(
array(
"status" => 1,
"message" => "Success!",
"request" => 10
)
);
You need to do the following use echo and also use CURLOPT_RETURNTRANSFER if not the output would be transferred directly to the page instead of $result
$name = "foo";
$age = "bar";
$url = 'http://.../a.php';
$fields = array('name' => urlencode($name),'age' => urlencode($age));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
header('Content-type: application/json');
echo json_encode(array("status" => 1,"message" => "Success!","request" => 10));
I want to process payments through my website and wanted to use sagepay for that purpose. I have gone through the guideline for sagepay go direct integration mentioned here:
http://www.sagepay.com/sites/default/files/pdf/user_guides/sagepaydirectprotocolandintegrationguidelines_0.pdf
Now,
I have created a script made necessary changes needed for the fields to process http request. here is the code:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp';
$txcode = 'prefix_' . time() . rand(0, 9999);
$fields = array(
'VPSProtocol'=>urlencode("2.23"),
'TxType'=>urlencode("PAYMENT"),
'Vendor'=>urlencode("myvendorname"),
'VendorTxCode'=>urlencode($txcode),
'Amount'=>urlencode("2.00"),
'Currency'=>urlencode("GBP"),
'Description'=>urlencode("payment for my site"),
'CardHolder'=>urlencode('DELTA'),
'CardNumber'=>urlencode(4929000000006),
'ExpiryDate'=>urlencode(1213),
'CV2'=>urlencode(123),
'CardType'=>urlencode('VISA'),
'BillingSurname'=>urlencode('surname'),
'BillingFirstnames'=>urlencode('name'),
'BillingAddress1'=>urlencode(' clifton'),
'BillingCity'=>urlencode('Bristol'),
'BillingPostCode'=>urlencode('BS82UE'),
'BillingCountry'=>urlencode('United Kingdom'),
'DeliverySurname'=>urlencode('surname'),
'DeliveryFirstnames'=>urlencode('name'),
'DeliveryAddress1'=>urlencode(' clifton'),
'DeliveryCity'=>urlencode('Bristol'),
'DeliveryPostCode'=>urlencode('bs82ue'),
'DeliveryCountry'=>urlencode('united kingdom'),
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
print_r($result);
echo "end";
//close connection
curl_close($ch);
?>
But I am not getting any response back.. what could be the problem? Its in wamp server and non https url.
This code works for me. I added a few CURL functions and removed one and that did the trick.
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp';
$txcode = 'prefix_' . time() . rand(0, 9999);
$fields = array(
'VPSProtocol'=>urlencode("2.23"),
'TxType'=>urlencode("PAYMENT"),
'Vendor'=>urlencode("myvendorname"),
'VendorTxCode'=>urlencode($txcode),
'Amount'=>urlencode("2.00"),
'Currency'=>urlencode("GBP"),
'Description'=>urlencode("payment for my site"),
'CardHolder'=>urlencode('DELTA'),
'CardNumber'=>urlencode(4111111111111111),
'ExpiryDate'=>urlencode(1213),
'CV2'=>urlencode(123),
'CardType'=>urlencode('VISA'),
'BillingSurname'=>urlencode('surname'),
'BillingFirstnames'=>urlencode('name'),
'BillingAddress1'=>urlencode(' clifton'),
'BillingCity'=>urlencode('Bristol'),
'BillingPostCode'=>urlencode('BS82UE'),
'BillingCountry'=>urlencode('United Kingdom'),
'DeliverySurname'=>urlencode('surname'),
'DeliveryFirstnames'=>urlencode('name'),
'DeliveryAddress1'=>urlencode(' clifton'),
'DeliveryCity'=>urlencode('Bristol'),
'DeliveryPostCode'=>urlencode('bs82ue'),
'DeliveryCountry'=>urlencode('united kingdom'),
);
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute post
$result = curl_exec($ch);
print_r($result);
echo "end";
//close connection
curl_close($ch);
?>
FYI, using http_build_query() is great for building query_strings.
$fields_string = http_build_query($fields);
This code will work if you add field
Crypt='Your encryption password in your account setting in sagepay test';
But it returns null string if you use curl to post and it will be redirected to
https://test.sagepay.com/gateway/service/cardselection?vpstxid={BDBF098F-9BB5-3822-8CAE-AC0645A2CC57}
if you use Http POST.
Goodluck
I'm trying to construct a PHP POST request that includes some binary data, following on from a previous StackOverflow question. The data is being submitted to this API call: http://www.cyclestreets.net/api/#addphoto
This is my PHP code:
$file = $_FILES['mediaupload'];
$file_field="#$file[tmp_name]";
$fields = array(
'mediaupload'=>$file_field,
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);
This is what my PHP file outputs:
FIELDS STRING: mediaupload=%40%2Fprivate%2Fvar%2Ftmp%2FphpHjfkRP&username=testing&password=testing&latitude=auto&longitude=auto&datetime=auto&category=cycleparking&metacategory=good&caption=
API RESPONSE: {"request":{"datetime":"1309886656"},"error":{"code":"unknown","message":"The photo was received successfully, but an error occurred while processing it."},"result":{}}
I believe this means that everything else about the request is OK, apart from the format of the binary data. Can anyone tell me what I am doing wrong?
CURL can accept a raw array of key=>value pairs for POST fields. There's no need to do all that urlencode() and http_build_query() stuff. Most likely the # in the array is being mangled into %40, so CURL doesn't see it as a file upload attempt.
$fields = array(
'mediaupload'=>$file_field,
'username'=> $_POST["username"),
etc...
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
The http_build_query function generates a URL encoded query string which means that the "#file.ext" is URL encoded in the output as a string and cURL doesn't know that you're trying to upload a file.
My advice would be not to include the file to upload in the http_build_query call and included manually in the CURLOPT_POSTFIELDS.
$file = $_FILES['mediaupload'];
$file_field="#$file[tmp_name]";
$fields = array(
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, 'mediaupload=' . $file_field . '&' . $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);
Im trying to shorten a url using ggole api's.Here is my php code .It gives a blank page when i load
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
My html file:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">
<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">
</FORM>
</body>
</html
I think I have found a solution to your problem. Since you are connecting to a URL that uses SSL, you will need to add some extra parameters to your code for CURL. Try the following instead:
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// extra parameters for working with SSL URL's; eypeon (stackoverflow)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
I think it's coming form your html. You didn't put the form methode, so it send data by get.
And you show something only if you have post.
Try to do in the form method="post"
Edit
Bobby the main problem is that you don't have one problem but several in this code.
First if you don't do
<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">
the if (isset($_POST['url'])) will never return true, because the variable send by the form will be GET (or do a if (isset($_GET['url']))).
Secondly you call the function with { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. So your variable $longUrl is always '$url'.
Thirdly you don't use sprintf like you should.
echo sprintf(
$response['longUrl'],
$response['id']
);
Sprintf need to take a string format:
echo sprintf("%s %s" // for example
$response['longUrl'],
$response['id']
);
But do you know that you can do directly
echo $response['longUrl'] . ' ' . $response['id'];
You can concatenate string directly with . in php
curl_exec() returns boolean false if something didn't go right with the request. You're not testing for that and assuming it worked. Change your code to:
$result = curl_exec($ch);
if ($result === FALSE) {
die("Curl error: " . curl_error($ch);
}
As well, you need to specify CURLOPT_RETURNTRANSFER - by default curl will write anything it receives to the PHP output. With this option set, it'll return the transfer to your $result variable, instead of writing it out.
You need to set CURLOPT_RETURNTRANSFER option in your code
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);