DEV Community

loading...

HTTPS server with NojeJS

ab0nilla profile image Alejandro Bonilla ・2 min read

Hi :D

This week I write a little bot for messenger ( Facebook chat). I have not had fb for some years.

I re-discover the facebook social network and join in developer.facebook.com, the documentation in this site is big confused.

well...

You need run your webhook over HTTPS server, and Facebook check your certs; if you run nodejs over local https; with self-generated certificates Facebook says: "..." I don't remember xD, but Facebook don't accept your "insecure" connection with your self-generated certificates with openssl.

I try install my self-generated certificates with openssl, and not found :(

But!.. in my post

I use "certbot" and in this project I used an online service: zerossl.com they also use let's Encrypt.

Go to Zerossl.com and get your certificates, search the "Service FAQ" and "How-To Videos" in the website and get yours CA, CERT and Key archives.

Copy your download files in your workspace folder.

Ok, you have your files, generated in zerossl.com, now write the daily code for simple NodeJS; and add this require.

var https = require("https");]
Enter fullscreen mode Exit fullscreen mode

add your download files (the zerossl.com certificates)

const options = {
  key: fs.readFileSync("/dir/key.key"),
  cert: fs.readFileSync("/dir/crt.crt"),
  ca: fs.readFileSync("/dir/ca.ca"),
}; 
Enter fullscreen mode Exit fullscreen mode

Finally replace your

app.listen(3000); 
Enter fullscreen mode Exit fullscreen mode

for this:

https.createServer(options, app).listen(port,console.log("webhookk listen")).
Enter fullscreen mode Exit fullscreen mode

Complete example:

'use strict';

THE REQUIRES AND process.env.PORT AND BLAH BLAH cons and other magic trick

var https = require("https");
var  fs = require("fs");

const options = {
  key: fs.readFileSync("YOURDIR/key.key"),
  cert: fs.readFileSync("YOURDIR/crt.crt"),
  ca: fs.readFileSync("YOURDIR/ca.ca"),
};

app.post('/webhook', (req, res) => {  
 yourcode
});


app.get('/webhook', (req, res) => {
   yourcode
  });

function handleMessage(sender_psid, received_message) {
   yourcode
}

function handlePostback(sender_psid, received_postback) {
  yourcode
  callSendAPI(sender_psid, response);
}

function callSendAPI(sender_psid, response) {
  yourcode
}
https.createServer(options, app).listen(port,console.log("webhookk listen"));

Enter fullscreen mode Exit fullscreen mode

Now, Facebook accept your secure connection :D

remember that the certificates expire, you must renew them.

remember 2: Https use the port 443, configure your firewall and move your others server (apache , nginx).

Discussion (0)

Forem Open with the Forem app