Receiving an SMS

To receive an SMS, you need to:

Prerequisites

Install dependencies

$ npm install express body-parser
Initialize your dependencies

Create a file named receive-express.js and add the following code:

Copy to Clipboard
const app = require('express')()
const bodyParser = require('body-parser')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

View full source 

Write the code

Add the following to receive-express.js:

Copy to Clipboard
app
  .route('/webhooks/inbound-sms')
  .get(handleInboundSms)
  .post(handleInboundSms)

function handleInboundSms(request, response) {
  const params = Object.assign(request.query, request.body)
  console.log(params)
  response.status(204).send()
}

app.listen(3000)

View full source 

Run your code

Save this file to your machine and run it:

$ node receive-express.js

Prerequisites

Install dependencies

Add the following to build.gradle:

compile 'com.nexmo:client:4.0.0'
compile 'com.sparkjava:spark-core:2.7.2'

Write the code

Add the following to the main method of the ReceiveSMS class:

Copy to Clipboard
    /*
     * Route to handle incoming SMS GET request.
     */
    Route inboundSmsAsGet = (req, res) -> {
        System.out.println("msisdn: " + req.queryParams("msisdn"));
        System.out.println("messageId: " + req.queryParams("messageId"));
        System.out.println("text: " + req.queryParams("text"));
        System.out.println("type: " + req.queryParams("type"));
        System.out.println("keyword: " + req.queryParams("keyword"));
        System.out.println("messageTimestamp: " + req.queryParams("message-timestamp"));

        res.status(204);
        return "";
    };

    /*
     * Route to handle incoming SMS with POST form-encoded or JSON body.
     */
    Route inboundSmsAsPost = (req, res) -> {
        // The body will be form-encoded or a JSON object:
        if (req.contentType().startsWith("application/x-www-form-urlencoded")) {
            System.out.println("msisdn: " + req.queryParams("msisdn"));
            System.out.println("messageId: " + req.queryParams("messageId"));
            System.out.println("text: " + req.queryParams("text"));
            System.out.println("type: " + req.queryParams("type"));
            System.out.println("keyword: " + req.queryParams("keyword"));
            System.out.println("messageTimestamp: " + req.queryParams("message-timestamp"));
        } else {
            MessageEvent event = MessageEvent.fromJson(req.body());

            System.out.println("msisdn: " + event.getMsisdn());
            System.out.println("messageId: " + event.getMessageId());
            System.out.println("text: " + event.getText());
            System.out.println("type: " + event.getType());
            System.out.println("keyword: " + event.getKeyword());
            System.out.println("messageTimestamp: " + event.getMessageTimestamp());
        }

        res.status(204);
        return "";
    };

    Spark.port(8080);
    Spark.get("/webhooks/inbound-sms", inboundSmsAsGet);
    Spark.post("/webhooks/inbound-sms", inboundSmsAsPost);
}

View full source 

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.nexmo.quickstart.sms with the package containing ReceiveSMS:

gradle run -Pmain=com.nexmo.quickstart.sms.ReceiveSMS

Prerequisites

Install dependencies

$ Install-Package Nexmo.Csharp.Client
Initialize your dependencies

Create a file named SMSController.cs and add the following code:

Copy to Clipboard
var client = new Client(creds: new Nexmo.Api.Request.Credentials
{
    ApiKey = "NEXMO_API_KEY",
    ApiSecret = "NEXMO_API_SECRET"
});

View full source 

Write the code

Add the following to SMSController.cs:

Copy to Clipboard
public ActionResult Receive([FromUri]SMS.SMSInbound response)
{

    if (null != response.to && null != response.msisdn)
    {
        Debug.WriteLine("------------------------------------");
        Debug.WriteLine("INCOMING TEXT");
        Debug.WriteLine("From: " + response.msisdn);
        Debug.WriteLine(" Message: " + response.text);
        Debug.WriteLine("------------------------------------");
        return new HttpStatusCodeResult(200);

    }
    else
    {
        Debug.WriteLine("------------------------------------");
        Debug.WriteLine("Endpoint was hit.");
        Debug.WriteLine("------------------------------------");
        return new HttpStatusCodeResult(200);

    }

}

View full source 

Run your code

Save this file to your machine and run it:

$ Run using your IDE

Prerequisites

Install dependencies

$ composer require slim/slim:^3.8
Initialize your dependencies

Create a file named index.php and add the following code:

Copy to Clipboard
$app = new \Slim\App;

View full source 

Write the code

Add the following to index.php:

Copy to Clipboard
$handler = function (Request $request, Response $response) {
    $params = $request->getParsedBody();

    // Fall back to query parameters if needed
    if (!count($params)){
        $params = $request->getQueryParams();
    }

    error_log(print_r($params, true));

    return $response->withStatus(204);
};

View full source 

Run your code

Save this file to your machine and run it:

$ php -f index.php

Prerequisites

Install dependencies

$ pip install flask
Initialize your dependencies

Create a file named receive-flask.py and add the following code:

Copy to Clipboard
from flask import Flask, request, jsonify
from pprint import pprint

app = Flask(__name__)

View full source 

Write the code

Add the following to receive-flask.py:

Copy to Clipboard
@app.route('/webhooks/inbound-sms', methods=['GET', 'POST'])
def inbound_sms():
    if request.is_json:
        pprint(request.get_json())
    else:
        data = dict(request.form) or dict(request.args)
        pprint(data)

    return ('', 204)

app.run(port=3000)

View full source 

Run your code

Save this file to your machine and run it:

$ python receive-flask.py

Prerequisites

Install dependencies

$ gem install sinatra
Initialize your dependencies

Create a file named receive.rb and add the following code:

Copy to Clipboard
require 'sinatra'
require 'sinatra/multi_route'
require 'json'

helpers do
  def parsed_body
     json? ? JSON.parse(request.body.read) : {}
  end

  def json?
    request.content_type == 'application/json'
  end
end

View full source 

Write the code

Add the following to receive.rb:

Copy to Clipboard
route :get, :post, '/webhooks/inbound-sms' do
  puts params.merge(parsed_body)
  status 204
end

set :port, 3000

View full source 

Run your code

Save this file to your machine and run it:

$ ruby receive.rb

Configure the webhook endpoint in your Nexmo Dashboard

So that Nexmo knows how to access your webhook, you must configure it in your Nexmo account.

In the building blocks, the webhook is located at /webhooks/inbound-sms. If you are using Ngrok, the webhook you need to configure in your Nexmo Dashboard API Settings page  is of the form https://demo.ngrok.io/webhooks/inbound-sms. Replace demo with the subdomain provided by Ngrok and enter your endpoint in the field labeled Webhook URL for Inbound Message:

#{alt_text}

Try it out

Now when you send your Nexmo number an SMS you should see it logged in your console. The message object contains the following properties:

{
  "msisdn": "447700900001",
  "to": "447700900000",
  "messageId": "0A0000000123ABCD1",
  "text": "Hello world",
  "type": "text",
  "keyword": "Hello",
  "message-timestamp": "2020-01-01T12:00:00.000+00:00",
  "timestamp": "1578787200",
  "nonce": "aaaaaaaa-bbbb-cccc-dddd-0123456789ab",
  "concat": "true",
  "concat-ref": "1",
  "concat-total": "3",
  "concat-part": "2",
  "data": "abc123",
  "udh": "abc123"
}