Handle an incoming message

Note:

Before you can get started, you need to do the following:

Using the Conversation API, you can receive and respond to messages from any channel you have configured. This tutorial shows you how to set up a Node.js application that receives and responds to messages.

Note:

This tutorial is easier to accomplish if you have already completed the steps for sending a message.

Steps:
  1. Set up your Node.js application
  2. Configure your Conversation API webhook
  3. Test the application

Set up your Node.js application

  1. Create a new node app with npm.
    Copy
    Copied
    npm init
  2. Accept the defaults for the application.
  3. Add the fetch package with npm to generate the necessary dependencies. In this application, we are going to use Express to handle incoming requests.
    Copy
    Copied
    npm install cross-fetch
    npm install express

Create your file

Note:

This tutorial uses basic authentication for testing purposes. We recommend in a production environment you use oauth2 authentication. Read more about authentication methods here.

Create a new file named index.js in the project and paste the provided "index.js" code found on this page into the file.

Note:

This sample code is configured for the US region. If your Conversation API app wasn't created in the US region, replace all instances of https://us.conversation.api.sinch.com with https://eu.conversation.api.sinch.com in the sample code.

This code starts a server that listens for incoming messages. It then sends a text message in response.

index.js

This code sample is to be used with the instructions on this page to build a web server that will handle and respond to incoming messages.

// Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys
const fetch = require('cross-fetch');
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

const ACCESS_KEY = "";
const ACCESS_SECRET = "";

app.post("/", async (req, res) => {
    var requestBody = req.body;
    console.log(requestBody);
    if (requestBody.message != undefined) {
        const sendMessage = {
            app_id: requestBody.app_id,
            recipient: {
                contact_id: requestBody.message.contact_id
            },
            message: {
                text_message: {
                    text: "You sent: " + requestBody.message.contact_message.text_message.text
                }
            },
            channel_priority_order: [requestBody.message.channel_identity.channel]
        };
        console.log(sendMessage);
    
        let result = await fetch(
            "https://us.conversation.api.sinch.com/v1/projects/" + requestBody.project_id + "/messages:send",
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: 'Basic ' + Buffer.from(ACCESS_KEY + ":" + ACCESS_SECRET).toString('base64')
                },
                body: JSON.stringify(sendMessage)
            }
        );
        console.log(await result.json());
        res.send("Ok");
    }
    else {
        res.send("Ok");
    }
});

app.listen(port, () => {
    console.log("Listening at http://localhost:" + port);
});

Fill in your parameters

  1. Assign your values to the following parameters:
ParameterYour value
ACCESS_KEYFind your access key on your Sinch dashboard.
ACCESS_SECRETFind your access secret on your Sinch dashboard.
Note: Access secrets are only available during initial key creation.
  1. Save the file.

Start your web server and set up a tunnel

  1. Start the server by executing the following command in your terminal or command prompt:
    Copy
    Copied
    node index.js
  2. Now you need to open a tunnel to the server you just set up. We are using ngrok for this.
    Note

    If you don't have ngrok installed already you can install it with the following command:

    Copy
    Copied
    npm install ngrok -g
  3. Open a new terminal or command prompt and enter:
    Copy
    Copied
    ngrok http 3000
  4. Copy the HTTP address that ends with .ngrok.io.

Configure your webhook

For your application to receive messages from Conversation API, you must configure a webhook in your Conversation API app. For detailed instructions on configuring a webhook, click here.

Set your webhook URL to the HTTP address you copied in the previous step. Additionally, assign the following triggers:

  • CONVERSATION_START
  • CONVERSATION_STOP
  • EVENT_DELIVERY
  • EVENT_INBOUND
  • MESSAGE_DELIVERY
  • MESSAGE_INBOUND
  • UNSUPPORTED

Test the application

Now that your server is running and your webhook is configured, you can test the application.

From your messaging platform, send your Conversation API app a message. You will receive a message back in response on the messaging platform.

Additional resources

Read the links below to learn more:

Was this page helpful?

index.js

This code sample is to be used with the instructions on this page to build a web server that will handle and respond to incoming messages.

// Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys
const fetch = require('cross-fetch');
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

const ACCESS_KEY = "";
const ACCESS_SECRET = "";

app.post("/", async (req, res) => {
    var requestBody = req.body;
    console.log(requestBody);
    if (requestBody.message != undefined) {
        const sendMessage = {
            app_id: requestBody.app_id,
            recipient: {
                contact_id: requestBody.message.contact_id
            },
            message: {
                text_message: {
                    text: "You sent: " + requestBody.message.contact_message.text_message.text
                }
            },
            channel_priority_order: [requestBody.message.channel_identity.channel]
        };
        console.log(sendMessage);
    
        let result = await fetch(
            "https://us.conversation.api.sinch.com/v1/projects/" + requestBody.project_id + "/messages:send",
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: 'Basic ' + Buffer.from(ACCESS_KEY + ":" + ACCESS_SECRET).toString('base64')
                },
                body: JSON.stringify(sendMessage)
            }
        );
        console.log(await result.json());
        res.send("Ok");
    }
    else {
        res.send("Ok");
    }
});

app.listen(port, () => {
    console.log("Listening at http://localhost:" + port);
});