Skip to content

Getting started with Node.js

This tutorial is intended for those new to engineers and web developers, who want to learn how to use Enfonica products. As such there is an assumed level of basic knowledge required.

  • Javascript
  • Programming Knowledge

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 as well. First things first let's get your NodeJS development enviroment and project directory set up to use the Enfonica Messaging SDK.

Install Node.js and NPM

Make sure that you have at least version 10 installed as this is the minimum version required to use the SDK. You also need NPM which is a package manager for Node. This should already be packaged with Node when it was installed.

To verify the version you have installed run the following commands.

node -v
npm -v

If you dont get a version number, you will need to install Node.js and NPM first. The quickest way to install node 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 is installed!

Create the directory and install the Enfonica Messaging SDK

Now that we have a working directory we get it setup to use NPM which we will use to install the Enfonica SDK. The SDK is opensource and you can checkout 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 (e.g name, description and verions) as well as the list of dependencies that it relies one (such as the Enfonica SDK).

Lets first make a project directory and initialize it to use npm. Run the following commands to do this and then follow the prompts.

mkdir myProject
cd myProject
npm init

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

npm install --save @enfonica/messaging

This command will install the latest version of the SDK and will update your package.json file which should now include a dependencies section as we specified the --save flag.

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

Nice Work! 🎉 You enviroment is ready to go so let's continue with the tutorial.

Sending your first SMS

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

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

To use the service account key, define the enviroment variable ENFONICA_APPLICATION_CREDENTIALS to be the location fo your service account key. For example:

set ENFONICA_APPLICATION_CREDENTIALS=/path/to/key.json

The client library you are using will use this enviroment 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 is the minimum required field needed to send a message, parent which is the project you are using, and the message itself which is an object made up of to, from and body. To read more about these fields and other available fields have a look at the public interface definitions.

MessagesClient.createMessage({ 
  parent: 'projects/first', 
  message: { 
    to: '-', 
    from: '-', 
    body: 'Hello World' 
  } 
});

Great now in your terminal use the following command which will run the server.js file and send the message.

node server.js

Alright you did it! Now that we 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

Okay now that we have covered the basics when it comes to sending an outgoing message let's now look at how we can handle an incoming message as well. Let's do this by making a simple scissors paper rock game by creating a webhook (Read more about webhooks) that we can add to one of our phone numbers that support SMS. This will be triggered when we send a 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 to use. The main one to mention here is express which is a node.js framework. Read more about it here.

npm install --save express
npm install --save body-parser
npm install --save xml

Great 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 setup express to listen on port 8080 and use the body parser library we added. There is alot more to express than just this but for the purpose of this guide we will just stick with the basics. You should definetly 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 setup let's also go ahead and add a /sms endpoint and set it up to be used for POST requests. This will be the POST endpoint that we will use as our webhook and will handle the scissors paper rock logic.

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

Okay great, now that we have a basic express server and the post endpoint we need let's now implement the logic for our scissors paper rock game. There a number of different ways we could implement the logic for this but for this tutorial let's make 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 = '';
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 additional logic to map your input to the correct index in the choices array and also add in some fallback logic if the input doesn't match up to 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?'
}

Awesome now we can also add in some basic functions to generate the computer's choice and then determine the winner as well.

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

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

const computerChoice = getComputerChoice();
const winner = getWinner(playerChoice, computerChoice);

Great and lastly let's add an if statement to handle if the user a valid value and set an appropriate message to sent to the player.

if (message !== 'Huh?' || message !== 'Aww okay.') {
  message = winner + " [Computer: " + choices[computerChoice] + ", Player: " + choices[playerChoice] + "]"
}

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

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

As you can see in the example we defined here the status code when our endpoint is hit. We can obviously set this to a different status code based on what occured. We also set the Content-Type header as text/xml as 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 a little something like this behind the scenes.

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

You might be wondering why we were specific about sending an XML response as part of the endpoint. Well that is actually 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 player. Read more about MessageML here!

Yay! we now have a webhook setup and it's time to try it out. First if you dont have Ngrok installed already go ahead and do so. We are going to use this to proxy our local Node.js server. Run ngrok in your terminal using port 8080.

Once you have done this copy the https url as we will be using this in the Enfonica Console to configure our phone number. Check out the guide here on how to purchase and configure a number in the console here.

Next up we need to update our phone number to include a messaging URI. Enter the ngrok url here and dont forget to add /sms to the end as that is our webhook endpoint.

Time for Testing

Great we are all set up and ready to go, your server.js file should be now looking 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());

// Recordings Client Example
MessagesClient.createMessage({
  parent: 'projects/first',
  message: {
    to: '+61413400110',
    from: '+61488828503',
    body: 'Hi want to play scissors paper rock? (Reply with Scissors/Paper/Rock or No)'
  }
});

app.post("/sms", (req, res) => {
  let message = ''
  let playerChoice = '';
  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];
  };

  const computerChoice = getComputerChoice();
  const winner = getWinner(playerChoice, computerChoice);

  if (message !== 'Huh?' || message !== 'Aww okay.') {
    message = winner + " [Computer: " + choices[computerChoice] + ", Player: " + choices[playerChoice] + "]"
  }

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

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

Now before we run our server let's quickly update the original send message request in server to send a message saying 'Hi want to play scissors paper rock? (Reply with Scissors/Paper/Rock or No)' and set the to number to be a phone you have access to and the from number to be the number that you added the ngrok uri to.

Next simply run the server again with

node server.js

Congrats if everything went according to plan you should've received a message asking if you want to play scissors paper rock and it should be from the number you specified.

Nice Work!

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

Start Building! Want to start building your solution but not quite sure how to get started? Feel free to let us know at support@enfonica.com