Follow along with the video tutorial:

https://youtu.be/6W2rIyUdmas?embedable=true

We are launching our first hackathon next week, and giving away over $1K in prizes! Join us in building a cool project and winning any of the following prizes 🏆

Additionally, everyone who submits a project successfully integrating the Courier API will receive a $20 Amazon gift card!

Not sure where to start? In this tutorial, we will be building a Node.js app that sends multi-channel notifications in morse code.

What’s going on?

We are secret agents today, and our goal is to send encoded messages to our spy network. Some spies prefer reading emails, and others prefer reading texts, so we need to ensure that our app can accommodate all spy preferences.

Note: The first five secret agents to successfully complete this tutorial and this task will receive a gift from Courier.

In Chapter 1, we will first integrate the Gmail and Twilio APIs, which Courier will use to send emails and text messages. In Chapter 2, we will demonstrate how to send single messages and setup routing to send multi-channel notifications. In Chapter 3, we will integrate a translation API to convert our messages into Morse code.

We are hosting our first hackathon next month, starting September 5th until September 30th. Register now to submit this project for a chance to win some cool prizes.

Register for the Hackathon: https://courier-hacks.devpost.com/

Instructions

Chapter 1: Authorize Courier to send messages using Gmail and Twilio APIs

In this first Chapter, we will need to authorize our API to send the secret messages. Let’s get started by integrating the Gmail and Twilio APIs, enabling Courier to send emails and messages from a single API call.

Once you can see the dancing pigeon, you are ready to use Courier to send more notifications. Before we build out our application, we need to set up the Twilio provider to enable text messages.

Lastly, you need to locate the Messaging Service SID, which you create in the Messaging tab on the left menu. Checkout Twilio’s docs on how to create a Messaging Service SID, linked in the description.

Chapter 2: Send single and multi-channel notifications

In this next Chapter, you will start sending messages. To send the secret messages, head to the Send API documentation. Here you can find everything related to sending messages.

On the right, you will see some starter code and can select a language of your choice from cURL, Node.js, Ruby, Python, Go, or PHP.

// Dependencies to install:
// $ npm install node-fetch --save

const fetch = require('node-fetch');

const options = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "message": {
      "template": "NOTIFICATION_TEMPLATE"
    }
  })
};

fetch('https://api.courier.com/send', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

This basic POST request can be edited to include the spies’ data such as how to contact them and the message you need to send. The “Notification Template” can be replaced with your own template.

// Dependencies to install:
// $ npm install node-fetch --save

const fetch = require('node-fetch');

const options = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "message": {
      "template": "NOTIFICATION_TEMPLATE",
      "to": {
        "email": "[email protected]"
      }
    }
  })
};

fetch('https://api.courier.com/send', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

Next, you need to add the actual message you are sending. These messages are pretty simple, so you can write them directly into the API call instead of creating a template.

// Dependencies to install:
// $ npm install node-fetch --save

const fetch = require('node-fetch');

const options = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "message": {
      "to": {
        "email": "[email protected]"
      },
      "content": {
        "title": "new subject",
        "body": "message"
      }
    }
  })
};

fetch('https://api.courier.com/send', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

As before, the data on the left automatically appears in the code snippet on the right. There is a content object that encompasses the title and body parameters.

Now you just need to make sure that this API call has access to your Courier account, which links to the Gmail and Twilio APIs.

// Dependencies to install:
// $ npm install node-fetch --save

const fetch = require('node-fetch');

const options = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: 'Bearer apikey'
  },
  body: JSON.stringify({
    "message": {
      "to": {
        "email": "[email protected]"
      },
      "content": {
        "title": "new subject",
        "body": "message"
      }
    }
  })
};

fetch('https://api.courier.com/send', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err)); 

Now you can integrate this code into our own Node.js application.

$ npm install node-fetch --save

$ node index.js

npm install node-fetch@2

Now when you run this program, you should get a response from Courier that includes the requestID in the VS Code console. This indicates that the API call was made successfully, and you can head over to the Courier datalog to determine if the message was also sent successfully.

Since you are a Secret Agent, you should probably protect the API key in case our code gets into the wrong hands.

APIKEY="fksdjfgjsdkfgndfsmn"

At this point, you can send a single message to the spies via email. However, you know that some spies prefer to use text messages, so you will need to enable multi-channel notifications. Let’s head back to the Courier docs and scroll down to the routing object, which contains the method and channels. Two types of methods are available - all and single. ‘All’ means that Courier will attempt to send the message to every channel listed. “Single” means that Courier will attempt to send it to the first channel that works. Let’s integrate this into our program.

"message": {
    "to": {
      "email": process.env.EMAIL
    },
    "content": {
      "title": "new subject",
      "body": "message"
    },
    "routing": {
      "method": "single",
      "channels": "email"
    },
}

"channels": ["email", "sms"]

You now have two different channels that this message can be sent to. All methods would send this message to both email and SMS. Single method would try to send this to the first that works. Since you have the user’s email address but not their phone number, this program can only send it via email.

If the two channels were reversed, Courier would try to send an SMS, fail to do so, and then default to sending an email.

"channels": ["sms", "email"]

"message": {
    "to": {
      "email": process.env.EMAIL,
      "phone_number": process.env.PHONENUMBER
    },
    "content": {
      "title": "new subject",
      "body": "message"
    },
    "routing": {
      "method": "single",
      "channels": ["sms", "email"]
    },
}

"message": {
    "to": {
      "email": process.env.EMAIL,
      "phone_number": process.env.PHONENUMBER
    },
    "content": {
      "title": "new subject",
      "body": "message"
    },
    "routing": {
      "method": "all",
      "channels": ["sms", "email"]
    },
}

Courier can now send via Twilio and Gmail within the same API call.

Chapter 3: Integrate a translation API to convert messages to Morse code

NOTE: The Morse API has a rate limit, which may give you an error if you run it too many times within the hour. In this case, you will have to wait for some time before continuing.

In this last Chapter, you will integrate the Fun Translations Morse API to encode the secret messages and send them over to the spies. You can search for documentation on the Morse API on the Fun Translations website.. Here you have access to all the information you need to make the call - you have an endpoint and an example demonstrating that the original message is a parameter for the endpoint.

🔗 Fun Translations: https://funtranslations.com/api/#morse

🔗 Fun Translations API: https://api.funtranslations.com/

// Dependencies to install:
// $ npm install node-fetch --save

const fetch = require('node-fetch');
require('dotenv').config()

async function send_secret_message() {

    const courier_options = {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + process.env.APIKEY
        },
        body: JSON.stringify({
          "message": {
            "to": {
              "email": process.env.EMAIL,
              "phone_number": process.env.PHONENUMBER
            },
            "content": {
              "title": "new subject",
              "body": "message"
            },
            "routing": {
              "method": "all",
              "channels": ["sms", "email"]
            },
          }
        })
      };

      fetch('https://api.courier.com/send', courier_options)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));

}

send_secret_message()

Before sending the message, you first need to make a call to the Morse API to translate the message. You can use node-fetch in the same way as you did for Courier to make this call.

// Dependencies to install:
// $ npm install node-fetch --save

const fetch = require('node-fetch');
require('dotenv').config()

async function send_secret_message() {

    const morse_options = {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        }
      };

      const original_message = "hey%20secret%20agent%20x%20this%20is%20your%20message"
      const morse_endpoint = "https://api.funtranslations.com/translate/morse.json?text="+original_message

      fetch(morse_endpoint, morse_options)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));

    const courier_options = {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + process.env.APIKEY
        },
        body: JSON.stringify({
          "message": {
            "to": {
              "email": process.env.EMAIL,
              "phone_number": process.env.PHONENUMBER
            },
            "content": {
              "title": "new subject",
              "body": "message"
            },
            "routing": {
              "method": "all",
              "channels": ["sms", "email"]
            },
          }
        })
      };

      fetch('https://api.courier.com/send', courier_options)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));

}

send_secret_message()

When you run this program, we may receive an error that states that there is an error parsing the JSON. This issue is caused by an error in the documentation, which here states that it should be a POST request. However, on a separate API documentation, it is written as a GET request. Update the call type to GET, and you should see the translated message within the response.

ObviouslyClearly, you don’t want to send all of this information to the spies, y. You only need the secret message.

fetch(morse_endpoint, morse_options)
    .then(response => response.json())
    .then(response => console.log(response.contents.translated))
    .catch(err => console.error(err));

You need to be able to access the translation from this API call in the body of the Courier API call.

const morse_response = await fetch(morse_endpoint, morse_options)
    // .then(response => response.json())
    // .then(response => console.log(response.contents.translated))
    // .catch(err => console.error(err));
const translation = await morse_response.json();
const message = translation.contents.translated
console.log(message)

"message": {
    "to": {
      "email": process.env.EMAIL,
      "phone_number": process.env.PHONENUMBER
    },
    "content": {
      "title": "new secret message",
      "body": message
    },
    "routing": {
      "method": "all",
      "channels": ["sms", "email"]
    },
}

The Courier datalog should show that the messages were successfully encoded and sent via both SMS and email. Here’s what the email looks like:

Conclusion

Our spies are now ready to receive their secret encoded messages. Try changing the body of the content to your own secret message and send it over to [email protected] ,and we will send a gift to the first five Secret Agents who complete this task! Don’t forget to submit your project to our Hackathon for a chance to win over $1000 in cash and prizes!XYZ.

🔗 GitHub Repository: https://github.com/shreythecray/secret-messages

🔗 Video tutorial: https://www.youtu.be/6W2rIyUdmasLog in to your Courier accountLog in to your Courier account

🔗 Courier: https://app.courier.com/signup?utm_campaign=Developer Relations&utm_source=secret-messageapp.courier.comapp.courier.com

🔗 Register for the Hackathon: https://courier-hacks.devpost.com/

🔗 Courier's Get Started with Node.js: https://www.courier.com/docs/guides/getting-started/nodejs/

🔗 Courier Send API Docs: https://www.courier.com/docs/reference/send/message/

🔗 Twilio Messaging Service SID Docs: https://support.twilio.com/hc/en-us/articles/223181308-Getting-started-with-Messaging-Services

🔗 Node-fetch: https://www.npmjs.com/package/node-fetch

🔗 Dotenv: https://www.npmjs.com/package/dotenv

🔗 Fun Translations: https://funtranslations.com/api/#morse

🔗 Fun Translations API: https://api.funtranslations.com/

Also published here.