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.
Related
This question already has answers here:
Axios Http client - How to construct Http Post url with form params
(5 answers)
Closed 2 years ago.
This might seem really silly but I'm trying to get some data from an API (WHMCS). In the docs they have code something like this:
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $whmcsUrl . 'includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
// Dump array structure for inspection
var_dump($jsonData);
I've written code in nodejs using axios which aims to do the same thing:
axios.get(whmcsUrl + `includes/api.php?accesskey=${apiAccessKey}`, postFields)
.then(res => console.log(res))
.catch(err => console.log(err))
Don't have a deep knowledge of either PHP or Node, please help! I'm getting a 403 Forbidden when I execute this request in node? What am I doing wrong.
Update: Instead of passing an object (postFields), I'm now passing things like username or pw in the url itself:
axios.post(whmcsUrl + `includes/api.php?action=${apiAction}&username=${apiIdentifier}&password=${apiSecret}&accesskey=${apiAccessKey}&responsetype=json`)
.then(res => console.log(res))
.catch(err => console.log(err))
Its still giving me 403 Forbidden error.
The axios equivalent of CURLOPT_POSTFIELDS, http_build_query($postfields) is twofold - first stringify the params and pass them as the post body and secondly specify application/x-www-form-urlencoded as the content type in the headers.
Something like this:
const axios = require('axios')
const qs = require('qs')
const data = qs.stringify(postFieldsObject)
const config = {
method: 'post',
url: `${whmcsUrl}includes/api.php`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data : data
}
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data))
})
.catch(function (error) {
console.log(error)
})
I made a post request for an api using ajax. I wonder how I can do the same in php.
<script type="text/javascript">
var cbIntegrationId = "xxxxxx"; // I have it
var clientId = "xxxxxxx"; //I have it
var clientSecret = "xxxxx"; //I have it
var tableName = "Test_Database";
//Get access token
$.post(
"https://" + cbIntegrationId + ".caspio.com/oauth/token",
{
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret
},
function(cbAuth){
//Run POST call
$.ajax({
url: "https://" + cbIntegrationId + ".caspio.com/rest/v2/tables/" + tableName + "/records?response=rows",
type: 'POST',
'data': JSON.stringify({"UniqueID":"988"}), //Define record values
headers: {
"Authorization": "Bearer " + cbAuth.access_token, //Extracts the access token from the initial authorization call
"Content-Type": "application/json", //Required, otherwise 415 error is returned
"Accept": "application/json"
},
dataType: 'json',
success: function (data) {
console.log(data.Result); //Check the console to view the new added row
},
error: function(data) {
console.log(data.responseJSON); //Check the console to view error message if any
}
});
}
);
</script>
I did some research but couldn't find anything that would solve my problem. I really need your help.
You can use cURL to call an API using PHP.
So according to your case you are sending data using POST method. So, we can use cURL as follows with some headers,
$apiURL = "https://yourURL";
$uniqueID = "UniqueID:988";
$postData = json_encode($uniqueID); // Encode the data into a JSON string
$authorization = "Authorization: Bearer " . $token; // Prepare the authorization token
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authorization, 'Content-Type: application/json', 'Accept : application/json')); // Inject the token into the header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // To get actual result from the successful operation
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Specify HTTP protocol version to use;
curl_setopt($curl, CURLOPT_POST, 1); // Specify the request method as POST
curl_setopt($curl, CURLOPT_URL, $apiURL); // Pass the API URL
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); // Set the posted fields
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
$response = curl_exec($curl); // Here you will get the response after executing
$error = curl_error($curl); // Return a string containing the last error for the current session
curl_close($curl); // Close a cURL session
Hope this helps you!
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.
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');
}
Im trying to send a GET or POST request from PHP (CLI), to a Node.js/Sockets.IO application, using only basic cURL. This is what i have so far, i can see the response coming in to node.js (from the cli), but can not get any farther. Currently i only want the parameters sent to the console. (I can expand on that later)
Any help would be great!
(FYI: I did look at this, Socket.io from php source, but need more help. Exact code would be great)
PHP
$qry_str = "?msg_from_php=This_is_a_test123&y=20";
$ServerAddress = 'http://10.1.1.69/socket.io/1/websocket/TICWI50sbew59XRE-O';
$ServerPort = '4000';
$TimeOut = 20;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ServerAddress. $qry_str);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_PORT, $ServerPort);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $TimeOut);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
// not sure if it should be in an array
//$data = array('msg_from_php' => 'simple message!');
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$content = trim(curl_exec($ch));
curl_close($ch);
echo " Sent! Content: $content \r\n";
Node.JS
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.configure('production', function(){
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('log level', 1);
io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
io.set("polling duration", 30);
});
server.listen(4000); // 80,443, 843, 4000, 4001
io.sockets.on('connection', function (socket) {
socket.on('msg_from_php, function (data) {
console.log(data);
});
});
You're trying to make an ordinary HTTP connection to a socket.io server, but socket.io doesn't speak plain HTTP; it uses at the very least a specialized handshaking protocol, and if it uses websocket transport it won't be using HTTP at all. AFAIK there's no PHP implementation of a socket.io client.
Fortunately, it looks like your PHP application needs to send to your node application on its own terms, not the other way around, so all you need to do is use express to define a couple routes to implement a RESTful interface; your PHP app can then use cURL to POST to the URL corresponding to the appropriate route.