Translate php curl to node js request - php

I have the following php code:
//Create url
$url = "https://pci.zcredit.co.il/WebControl/RequestToken.aspx";
$post = "TerminalNumber=$TerminalNumber"
."&Username=$UserName&PaymentSum=$PaymentSum&PaymentsNumber=$PaymentsNumber&Lang=$Lang"
."&Currency=$Currency&UniqueID=$UniqueID&ItemDescription=$ItemDescription&ItemQtty=$ItemQtty"
."&ItemPicture=$ItemPicture&RedirectLink=$RedirectLink&NotifyLink=$NotifyLink"
."&UsePaymentsRange=$UsePaymentsRange&ShowHolderID=$ShowHolderID&AuthorizeOnly=$AuthorizeOnly"
."&HideCustomer=$HideCustomer&CustomerName=$CustomerName&CssType=$CssType&IsCssResponsive=$IsCssResponsive";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // Create the request url
curl_setopt($ch, CURLOPT_POSTFIELDS,$post); //Set post value
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Not return data in brower
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$page = curl_exec($ch); // Get the response
Which I'm trying to use in node js, with Request:
let url = "https://pci.zcredit.co.il/WebControl/RequestToken.aspx";
let post = `TerminalNumber=${TerminalNumber}`
+`&Username=${UserName}&PaymentSum=${PaymentSum}&PaymentsNumber=${PaymentsNumber}&Lang=${Lang}`
+`&Currency=${Currency}&UniqueID=${UniqueID}&ItemDescription=${ItemDescription}&ItemQtty=${ItemQtty}`
+`&ItemPicture=${ItemPicture}&RedirectLink=${RedirectLink}&NotifyLink=${NotifyLink}`
+`&UsePaymentsRange=${UsePaymentsRange}&ShowHolderID=${ShowHolderID}&AuthorizeOnly=${AuthorizeOnly}`
+`&HideCustomer=${HideCustomer}&CustomerName=${CustomerName}&CssType=${CssType}&IsCssResponsive=${IsCssResponsive}`;
const request = require('request');
request(url +'/' + post, { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
});
But should I just add the post parameters to the original url? Is it secure?
Thanks in advance!

The syntax for posting URL-encoded forms with Request is simple as:
request.post(url).form({ key: value })
Of course, you can choose to send the request with the parameters in the url, using template literals variables, and that will change nothing in a security point of view, but it will be more readable.
Your code will be secure if you sanitize the parameters and if you use encryption (https), the same way you should do in any language, as main.c says in his comment.

Related

PHP to Typescript conversion

I'm trying to build a function for firebase to call a url on command via a POST method. I've currently implemented GET methods just fine but the POST method has me scratching my head.
I've got some sample code for calling via fetch but I'm not sure where the parameters in this following snippet need to go:
<?php
$url = 'https://profootballapi.com/schedule';
$api_key = '__YOUR__API__KEY__';
$query_string = 'api_key='.$api_key.'&year=2014&week=7&season_type=REG';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
Here's what my sample code for the POST request looks like:
const apiKey = "myAPIkey";
const url = "https://profootballapi.com/schedule";
const response = await fetch(url, {
method: 'POST',
body: 'api_key'= apiKey, '&year=2018&week=7&season_typeRG';
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}});
if (!response.ok) {/* Handle */}
// If you care about a response:
if (response.body !== null) {
functions.logger.log(response.body);
}
You're pretty close. You just have some syntax level issues in your TypeScript:
curl_setopt($ch, CURLOPT_URL, $url);
You passed in the url correctly.
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
This is just providing an HTTP body to the request You've already attempted this in the fetch, but you have some syntax issues. You should replace the body with this:
body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This is free. fetch automatically returns the response in response.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Assuming this code will run on the browser, you won't be able to disable this. It's telling the client to verify the server's SSL certificate. you should avoid disabling this if you can help it.
I tested this code and got somewhat reasonable results in Chrome's debugging tools:
const foo = async function () {
const apiKey = "myAPIkey";
const url = "https://profootballapi.com/schedule";
const response = await fetch(url, {
method: 'POST',
body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
return response;
}
foo().then(response => console.log(response));
It produces a 500 error, but I suspect this has to do with not having a valid API key. I'll leave it to you to sort out how to submit a valid API request.

HTTP Post request from PHP to NodeJs Server

I tried to make a request to my nodeJS using CURL from PHP.
Here is my code:
$host = 'http://my_ip:8080/ping';
$json = '{"id":"13"}';
$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
$data = curl_exec($ch);
var_dump($data);
But it doesn't work. I received bool(FALSE) in data var.
NodeJS:
app.use(router(app));
app.post('/ping', bodyParser, ping);
port = 8080;
app.listen(port, webStatus(+port));
function* ping() {
console.log(this.request.body);
this.body = 1;
}
I tried with NodeJS Http-post and it works:
http.post = require('http-post');
http.post('http://my_ip:8080/ping', { id: '13' }, function (res) {
res.on('data', function (chunk) {
console.log(chunk);
});
});
Is it something wrong with PHP code?
PS: The CURL is included in PHP.
Your ping function is not well implemented I think.
Also, you need to call the send method in order to send the HTTP response.
You should declare the function like this :
app.use(bodyParser); // You can use a middleware like this too.
app.post('/ping', ping);
function ping (req, res) {
console.log(req.body); // Since you use `bodyParser` middleware, you can get the `body` directly.
// Do your stuff here.
res.status(200).send('toto');
}

php+curl to send a post request with fields

trying to send post request to api, to get an image back.
example url:
https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php?user=1003123&format=png&cloudid=asdasdasd&pass=123123123
the above url works fine in the browser,
the api doesnt care if the request is get/post,
result of my code is always 'invalid input'.
code:
$url='https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php';
$u = rand();
$p = rand();
$fields = array(
'user'=> urlencode($u),
'pass'=> urlencode($p),
'format'=> urlencode('jpg'),
'cloudid' => urlencode('test')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
on a side note: is there a way to debug the request in order to see what is being sent ?
The URL provided isn't working for POST request. Here is resulting screenshot (I tried using Advance Rest Client)
However Its working perfectly with GET method. So you can continue using GET request method to generate QR code.
I agree that GET isn't much secure compare to POST method but in your case while requesting from curl user won't get to know about such URL parameters (userid, password). Because curl request will be sending from your web server and not from client/user's browser.
Later you can just output the response image you got from the api.

sending xml string using php curl but not as post parameter

:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.

Send Post request to Node.js with PHP cURL

I am trying to send a post request through PHP cURL to my node.js server to then emit a message to the client. The server is working and setup as follows:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, qs = require('querystring')
app.listen(8000);
function handler(req, res) {
// set up some routes
switch(req.url) {
case '/push':
if (req.method == 'POST') {
console.log("[200] " + req.method + " to " + req.url);
var fullBody = '';
req.on('data', function(chunk) {
fullBody += chunk.toString();
if (fullBody.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function() {
// Send the notification!
var json = qs.stringify(fullBody);
console.log(json.message);
io.sockets.emit('push', { message: json.message });
// empty 200 OK response for now
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.end();
});
}
break;
default:
// Null
};
}
and my PHP is as follows:
$curl = curl_init();
$data = array('message' => 'simple message!');
curl_setopt($curl, CURLOPT_URL, "http://localhost:8000/push");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
The console says that json.message is undefined. Why is it undefined?
You're using querystring.stringify() incorrectly. See the documentation on querystring's methods here:
http://nodejs.org/docs/v0.4.12/api/querystring.html
I believe what you want is something like JSON.stringify() or querystring.parse(), as opposed to querystring.stringify() which is supposed to serialize an existing object into a query string; which is the opposite of what you are trying to do.
What you want is something that will convert your fullBody string into a JSON object.
If your body simply contains a stringified version of the JSON blob, then replace
var json = qs.stringify(fullBody);
With
var json = JSON.parse(fullBody);
try this code
<?php
$data = array(
'username' => 'tecadmin',
'password' => '012345678'
);
$payload = json_encode($data);
// Prepare new cURL resource
$ch = curl_init('https://api.example.com');
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);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
// Close cURL session handle
curl_close($ch);

Categories