Skip to content

Getting started with Node.js

This tutorial is for engineers and web developers who are new to Enfonica. It assumes basic knowledge of:

  • JavaScript
  • Programming

In this tutorial, you'll learn how to send your first SMS using the Enfonica Messaging SDK, and how to handle incoming SMS using MessageML. First, let's get your Node.js development environment and project directory set up to use the Enfonica Messaging SDK.

Install Node.js and npm

The SDK requires Node.js version 10 or later. We recommend the current LTS release. You also need npm, the package manager for Node.js, which is installed with Node.js.

To verify the versions you have installed, run the following commands.

node -v
npm -v

If you don't get a version number, you need to install Node.js and npm first. The quickest way is to go to the official Node.js downloads page and use the installer for your OS. Once installed, run the previous commands again to confirm that Node.js is installed.

Create the directory and install the Enfonica Messaging SDK

Next, create a project directory and set it up to use npm, which you'll use to install the Enfonica SDK. The SDK is open source, and you can check out the code in this GitHub repo. It's also listed on npmjs.com so that npm knows where to find it.

Any Node.js project that uses npm needs a package.json file, which includes information about the package (such as its name, description and version) as well as the list of dependencies that it relies on (such as the Enfonica SDK).

Let's first make a project directory and initialize it to use npm. Run the following commands, and then follow the prompts.

mkdir myProject
cd myProject
npm init

Now that you have a directory to work in, let's install the Enfonica SDK. Run the following command:

npm install @enfonica/messaging

This command installs the latest version of the SDK and updates your package.json file, which now includes a dependencies section.

{
  "dependencies": {
    "@enfonica/messaging": "^1.3.1"
  }
}

Your environment is ready to go, so let's continue with the tutorial.

Sending your first SMS

First, let's create a new file in the same directory as your package.json file and call it server.js.

In this file, let's include the Enfonica SDK using require() and create a new instance of it. The SDK authenticates using a service account key, which you can get from the Enfonica Console.

To use the service account key, set the environment variable ENFONICA_APPLICATION_CREDENTIALS to the location of your service account key file. For example:

export ENFONICA_APPLICATION_CREDENTIALS=/path/to/key.json
$env:ENFONICA_APPLICATION_CREDENTIALS = "C:\path\to\key.json"
set ENFONICA_APPLICATION_CREDENTIALS=C:\path\to\key.json

The client library uses this environment variable by default to authenticate with Enfonica services.

const messaging = require('@enfonica/messaging');
const MessagesClient = new messaging.MessagesClient();

Now that we have an instance of the messaging client to play with, let's send our very first message by using the createMessage method. Below are the minimum fields needed to send a message: parent, which is the project you are using, and message, which is an object made up of to, from and body. Replace projects/first with your project name, to with your mobile number, and from with an SMS-enabled phone number in your project. To read more about these fields and the other available fields, have a look at the public interface definitions.

MessagesClient.createMessage({
  parent: 'projects/first',
  message: {
    to: '+61491570156',
    from: '+61491570110',
    body: 'Hello World'
  }
})
  .then(([response]) => console.log(`Sent ${response.name}`))
  .catch(console.error);

Now, in your terminal, use the following command to run the server.js file and send the message.

node server.js

You did it. Now that you have sent your first message, you should have a basic understanding of what the Enfonica Messaging SDK is all about. There are other methods available for you to use as well, in the public interface definitions.

What's next

Now that we have covered the basics of sending an outgoing message, let's look at how we can handle an incoming message as well. Let's do this by making a simple scissors paper rock game. We'll create a webhook (read more about webhooks) that we can add to one of our phone numbers that supports SMS. The webhook is triggered when we send an SMS to the phone number we choose in our project.

First up, let's create the webhook. For this we could use some help, so go ahead and run the following commands to install some new dependencies. The main one to mention here is Express, which is a Node.js framework.

npm install express
npm install body-parser
npm install xml

Now let's add the require statements for these new dependencies, like we did previously.

const express = require("express");
const bodyParser = require("body-parser");
const xml = require("xml");

Next, we can add the following code to set up Express to listen on port 8080 and use the body parser library we added. There is a lot more to Express than just this, but for the purpose of this guide we will stick with the basics. You should definitely check it out, though, when it comes to Node.js development.

const app = express();
app.use(bodyParser.json());

const port = 8080;
app.listen(port);
console.log(`app is listening on port: ${port}`);

Now that we have a basic Express server set up, let's also add a /sms endpoint and set it up to be used for POST requests. This is the POST endpoint that we will use as our webhook, and it will handle the scissors paper rock logic.

app.post("/sms", (req, res) => {});

Now that we have a basic Express server and the POST endpoint we need, let's implement the logic for our scissors paper rock game. There are a number of different ways we could implement this, but for this tutorial let's make it so that the player can send a message to a number with their choice of Rock, Paper or Scissors, and then our logic will randomly make a choice as well. Firstly, we need to define our constants and variables.

let message = '';
let playerChoice = null;
const t = 'Tie',
      c = 'You lose',
      p = 'You win',
      winningMap = [
        [t, c, p],
        [p, t, c],
        [c, p, t]
      ],
      choices = ["Rock", "Paper", "Scissors"];

As you can see in the code above, we are using a map which helps determine the outcome. You can think of it as a 3x3 grid where the order on each axis matches the order we defined in the choices array.

Now let's add some logic to map the player's input to the correct index in the choices array, and some fallback logic if the input doesn't match anything.

if (req.body.body === 'Rock') {
  playerChoice = 0;
} else if (req.body.body === 'Paper') {
  playerChoice = 1;
} else if (req.body.body === 'Scissors') {
  playerChoice = 2;
} else if (req.body.body === 'No') {
  message = 'Aww okay.';
} else {
  message = 'Huh?';
}

Next, we can add some basic functions to generate the computer's choice and determine the winner.

const getComputerChoice = function () {
  return Math.floor(Math.random() * 3);
};

const getWinner = function (playerChoice, computerChoice) {
  return winningMap[playerChoice][computerChoice];
};

Lastly, let's add an if statement that, when the player sent a valid choice, plays the game and sets the message to send back to the player.

if (playerChoice !== null) {
  const computerChoice = getComputerChoice();
  const winner = getWinner(playerChoice, computerChoice);
  message = winner + " [Computer: " + choices[computerChoice] + ", Player: " + choices[playerChoice] + "]";
}

At the end of our route, we need to add a few lines of code which send data back to Enfonica.

res.status(200);
res.set('Content-Type', 'text/xml');
res.send(xml({ Response: [{ Message: message }] }));

As you can see in the example, we set the status code that our endpoint returns. We could set this to a different status code based on what occurred. We also set the Content-Type header to text/xml because we want the response body to be sent as XML, and then finally we use the XML library we added previously to generate our XML response, which ends up looking like this.

<Response><Message>Huh?</Message></Response>

You might be wondering why we were specific about sending an XML response from the endpoint. That's because we can use MessageML to automatically send a message once the endpoint is hit. In our case, we are using MessageML to send the result of the scissors paper rock game back to the player. Read more about MessageML.

We now have a webhook set up, and it's time to try it out. First, if you don't have ngrok installed already, go ahead and install it. We are going to use it to proxy our local Node.js server. Run ngrok in your terminal using port 8080.

ngrok http 8080

Once you have done this, copy the https URL, because we will use it in the Enfonica Console to configure our phone number. If you don't have an SMS-enabled phone number yet, see Buy a phone number in the Help Center.

Next, we need to add the webhook to our phone number. In the Console, open the phone number, and under Messaging settings, add the ngrok URL to Incoming message handlers. Don't forget to add /sms to the end, because that is our webhook endpoint. Then select Save Changes.

Time for testing

We are all set up and ready to go. Your server.js file should now look something like this.

const messaging = require('@enfonica/messaging');
const express = require("express");
const bodyParser = require("body-parser");
const xml = require("xml");

const MessagesClient = new messaging.MessagesClient();

const app = express();
app.use(bodyParser.json());

// Send the first message
MessagesClient.createMessage({
  parent: 'projects/first',
  message: {
    to: '+61491570156',
    from: '+61491570110',
    body: 'Hi want to play scissors paper rock? (Reply with Scissors/Paper/Rock or No)'
  }
})
  .then(([response]) => console.log(`Sent ${response.name}`))
  .catch(console.error);

app.post("/sms", (req, res) => {
  let message = '';
  let playerChoice = null;
  const t = 'Tie',
    c = 'You lose',
    p = 'You win',
    winningMap = [
      [t, c, p],
      [p, t, c],
      [c, p, t]
    ],
    choices = ["Rock", "Paper", "Scissors"];

  if (req.body.body === 'Rock') {
    playerChoice = 0;
  } else if (req.body.body === 'Paper') {
    playerChoice = 1;
  } else if (req.body.body === 'Scissors') {
    playerChoice = 2;
  } else if (req.body.body === 'No') {
    message = 'Aww okay.';
  } else {
    message = 'Huh?';
  }

  const getComputerChoice = function () {
    return Math.floor(Math.random() * 3);
  };

  const getWinner = function (playerChoice, computerChoice) {
    return winningMap[playerChoice][computerChoice];
  };

  if (playerChoice !== null) {
    const computerChoice = getComputerChoice();
    const winner = getWinner(playerChoice, computerChoice);
    message = winner + " [Computer: " + choices[computerChoice] + ", Player: " + choices[playerChoice] + "]";
  }

  res.status(200);
  res.set('Content-Type', 'text/xml');
  res.send(xml({ Response: [{ Message: message }] }));
});

const port = 8080;
app.listen(port);
console.log(`app is listening on port: ${port}`);

Before we run our server, make sure the send message request in server.js says 'Hi want to play scissors paper rock? (Reply with Scissors/Paper/Rock or No)', and set the to number to a phone you have access to and the from number to the number that you added the ngrok URL to.

Next, run the server again with:

node server.js

If everything went according to plan, you should have received a message asking if you want to play scissors paper rock, and it should be from the number you specified. Reply with your choice to play.

Summary

You've not only sent your first message, but have also learned a way of handling an incoming message, and even learned a bit about MessageML, all using Node.js and the Enfonica Messaging SDK. If you had any issues getting this running, check out the repo.

Want to start building your solution but not quite sure how to get started? Contact Enfonica support.