Category: access token

HTTPS to HTTP Ajax Request, Same Origin Policy.

Often there are times where we need to make a request that might not obey the Same Origin Policy . So here I am going to address Different Protocal issue in Same Origin Policy. Suppose we are making a http request from a server with HTTPS protocol in the following way.

$.ajax({
        url: 'http://MyAjaxHTTP Path',
        type: 'POST',
        data: 'param1=value1&param2=value',
        header: "application/x-www-form-urlencoded",

The above request cannot be made because it violates same origin policy. So we have to write a layer code between JavaScript and the HTTP server that directly interacts with HTTP. So first we have to choose a server side language for this. I am choosing PHP.

In PHP (phplayer.php):

$param1 = $_POST["param1"];
$param2 = $_POST["param2"];
$data = array(“param1”=>$param1, "$param2"=>$param2);

$data = http_build_query($data);
header('content-type: application/json');
$context_options =  array(
        'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $data
        ));
$context  = stream_context_create($context_options);

//notice that our actual HTTP URL is called here
$result = file_get_contents("http://MyAjaxHTTPPath", false, $context);
echo $result;

In JavaScript everything remains same except that we have to make a call to our layer PHP code that will actually make a HTTP request and get back the response.

$.ajax({
        url: 'phplayer.php',
        type: 'POST',
        data: "param1=value1&param2=value",
        header: "application/x-www-form-urlencoded",

How to build a basic facebook messenger bot using Nodejs ?

To build a facebook bot, you may choose any server side technology like php, nodejs, python, ruby. I am choosing Nodejs, as it is simple and has built in libraries that would ease in building a bot.

To start building a bot, you need to install Nodejs on your computer. You may install nodejs from link below:

https://nodejs.org/en/download/

Let’s start of  with building that would say hello on your input.

step 1:

The front end API is provided by facebook which can be accessed through a facebook page. To accomplish this you’ll have to create a facebook page.

step 2:

In order to have your bot communicate with the page, facebook provides a unique token which is to be included in your code. To generate a token, you will have to create a facebook app here. Once you are done creating the app, click on “Messenger” and select your page from the drop down which generates a random token. Have this token saved for later use in the code. Then click on “Add Products” and select webhooks.

step 3:

Now that we have token ready, lets write the code say file name is server.js. Note that the above generated token needs to be replaced in the below code 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    const http = require('http')
    const Bot = require('messenger-bot')
    var bot = new Bot({
     token: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
     verify: 'VERIFY_TOKEN'
    })
    bot.on('error', (err) => {
     console.log(err.message)
    })
    bot.on('message', (payload, reply) => {
     var text = payload.message.text;
     text = text.toLowerCase();
     text = text.replace(/[.,/#!$%^&*;:{}=-_`~()?'"@|+<>[]]/g,"");
     text = text.replace(/s{2,}/g," ");
     console.log(text);
     if(typeof text === "undefined" || text == "")
     {
     text = "Oops! we couldn't find this word in our database. Try other.";
     console.log("Sorry! we couldn't find this word in our database. Try other.");
     }
    else if(text == "hi" || text == "hello"){
     text= "Hi. I am hello bot.";
     reply({ text }, (err, info) => {
     });
    else if(text == "bye"){
     text= "Bye. See ya!.";
     reply({ text }, (err, info) => {
     });
     else if(text == "How are you?"){
     text= "Am fine thanks.";
     reply({ text }, (err, info) => {
     });
     bot.getProfile(payload.sender.id, (err, profile) => {
      if (err) throw err
      reply({ text }, (err) => {
       if (err) throw err
       console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
      })
     })
    });
    http.createServer(bot.middleware()).listen(3000);
    console.log("chat bot up and running..");
step 4:

Now that we are done with the code, its time to run our bot. To run the server, type node server.js.

step 5:

Since, the facebook API communicates through secure tunnel, we need a secure server to establish the connection between facebook and our node server. Ngrok comes to the rescue in this case. Ngrok provides a secure tunnel which allows our server to connect to facebook API.  Install and run Ngrok which generates a secure link. Copy the generated secure link(looks like https://localhost:XXX).

step 6:

In the facebook Developers page, click on “Webhooks” and paste the above secure link in callback url field and enter the verify token from code in “Verify Token” section, click “Verify and save”. To activate the tunnel, click on “Messenger”  and select your page and click on “Subscribe” to subscribe it.

step 7:

Finally, we are done with setup and our bot is ready to talk. In the created facebook page, click on Message and type “Hi” and boom you’ll get the response.

This is a basic chat bot which simply sends text message. Similarly, you can use different templates available in Messenger platform to make your own bot.