Messages

Parameters

Obtain your API KEY and submit your MESSENGER PAGE ACCESS TOKEN,PAUSE WEBHOOK prior to integration

Rate Limits

The test version of Waylo API is limited to 3 requests/second and 50,000 requests/day

Request

In order to send incoming/out-going messages to Waylo, make a POSTcall tohttps://wayloapi.herokuapp.com/webhook

Example

         
curl  "https://wayloapi.herokuapp.com/webhook?apikey=[YOUR KEY]&paused=[pausedState=true/false]" \
-X POST \
-H 'Content-Type: application/json' \
-d
'{
    "message": see below incoming/out-going message structures.
}'             

Fields

Field Name Description Type Required
message Message JSON Yes

Simple Node.js code example

     
var request = require('request');

/******************** Waylo function with the API endpoint       **************/

function wayloapi(message){

  // Extract userid from message
  
  const userid = message.entry[0].id===message.entry[0].messaging[0].sender.id? message.entry[0].messaging[0].recipient.id : message.entry[0].messaging[0].sender.id;
  
  // Retrieve the paused state. Change this line if you implemented paused variable in your database
  var pausedState = pausedUsers[userid] ? pausedUsers[userid] : false;
  var options = { method: 'POST',
    url: 'https://wayloapi.herokuapp.com/webhook',                              //URL is different for production API
    qs: {
      apikey: ,
      paused: pausedState
    },
    headers: 
     {'content-type': 'application/json' },
    body: message,
    json: true };

  request(options, function(error, response, body){

         if(error) {
           console.log(error)
         } else {
           console.log(response.statusCode, body)
         }
    });

}



/**** Log incoming messages and postbacks *********/

app.post('/webhook', function (req, res) {
  var data = req.body;
  wayloapi(req.body);                                             // logging inputs


  if (data.object == 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach(function(pageEntry) {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach(function(messagingEvent) {

        const senderID=  messagingEvent.sender.id;

        if(!pausedUsers[senderID]){                               // Note the bot pause part
          if (messagingEvent.optin) {
            receivedAuthentication(messagingEvent);
          } else if (messagingEvent.message) {
            receivedMessage(messagingEvent);
          } else if (messagingEvent.delivery) {
            receivedDeliveryConfirmation(messagingEvent);
          } else if (messagingEvent.postback) {
            receivedPostback(messagingEvent);
          } else if (messagingEvent.read) {
            receivedMessageRead(messagingEvent);
          } else if (messagingEvent.account_linking) {
            receivedAccountLink(messagingEvent);
          } else {
            console.log("Webhook received unknown messagingEvent: ", messagingEvent);
          }
        }
      });
    });

    // Assume all went well.
    //
    // You must send back a 200, within 20 seconds, to let us know you've 
    // successfully received the callback. Otherwise, the request will time out.
    res.sendStatus(200);
  }
});




/***************Bot pause ******************************/

var jsonParser = bodyParser.json();

// Test Bot pause

app.get('/pause', function(req, res) {
    console.log("pause");
    res.send(200);    
});


var pausedUsers = {};  // Implement this in the datebase to make it more robust
app.post('/pause', jsonParser, function (req, res) {
  const userId = req.query.userId;
  const paused = (req.query.paused === "true");
  pausedUsers[userId] = paused;                      
  res.send("ok")
})



/*************Button to pause bot and start Waylo Hotel booking *********/

var buttonData = {
  recipient: {
    id: userId                             // Make sure this is the id of the user
  },
  message: {
    attachment: {
      type: "template",
      payload: {
        template_type: "button",
        text: 'Ciao until next time :)',    // Bot maker is free to choose this text
        buttons:[ 
        {
          type: "postback",
          title: "Book hotel",              // Bot maker is free to choose this text
          payload: "pause=hotel"            // Do not change payload. Handle the payload in your logic if can
          
        }

        ]
      }
    }
  }
};  

callSendAPI(buttonData);                   // Call Messenger API




/********************* callSendAPI (Messenger API call) **************/


function callSendAPI(messageData) {
  wayloapi(messageData)                                          // Log outgoing message
  request({
    uri: 'https://graph.facebook.com/v2.8/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s", 
          messageId, recipientId);
      } else {
      console.log("Successfully called Send API for recipient %s", 
        recipientId);
      }
    } else {
      console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
    }
  });  
}

     

Response Meanings

Response Code Meaning
200 OK – Everything worked as expected.
400 Bad Request – The request was unacceptable, often due to missing a required parameter.
401 Unauthorized – Your api token is wrong
404 Not Found – The requested resource doesn't exist.
500, 502, 503, 504 Server Errors – Something went wrong on Waylo's end. Try again later. (These are rare.)