Delivery Receipts

You can verify that a message you sent using Nexmo's SMS API reached your customer by requesting a delivery receipt from the carrier.

To access the delivery receipt, you need to:

Prerequisites

Install dependencies

$ npm install express body-parser
Initialize your dependencies

Create a file named dlr-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 dlr-express.js:

Copy to Clipboard
app
  .route('/webhooks/delivery-receipt')
  .get(handleDeliveryReceipt)
  .post(handleDeliveryReceipt)

function handleDeliveryReceipt(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 dlr-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 ReceiveDLR class:

Copy to Clipboard
port(3000);

get("/webhooks/delivery-receipt", (req, res) -> {
    for (String param : req.queryParams()) {
        System.out.printf("%s: %s\n", param, req.queryParams(param));
    }
    res.status(204);
    return "";
});

post("/webhooks/delivery-receipt", (req, res) -> {
    // The body will be form-encoded or a JSON object:
    if (req.contentType().startsWith("application/x-www-form-urlencoded")) {
        for (String param : req.queryParams()) {
            System.out.printf("%s: %s\n", param, req.queryParams(param));
        }
    } else {
        IncomingDlrPayload jsonPayload = IncomingDlrPayload.fromJson(req.bodyAsBytes());
        System.out.println(jsonPayload);
    }

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

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 ReceiveDLR:

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

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 DLR([FromUri]SMS.SMSDeliveryReceipt response)
{

    Debug.WriteLine("------------------------------------");
    Debug.WriteLine("DELIVERY RECIEPT");
    Debug.WriteLine("Message ID: " + response.messageId);
    Debug.WriteLine("From: " + response.msisdn);
    Debug.WriteLine("To: " + response.to);
    Debug.WriteLine("Status: " + response.status);
    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);
};

$app->get('/webhooks/delivery-receipt', $handler);
$app->post('/webhooks/delivery-receipt', $handler);

$app->run();

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 dlr-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 dlr-flask.py:

Copy to Clipboard
@app.route('/webhooks/delivery-receipt', methods=['GET', 'POST'])
def delivery_receipt():
    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 dlr-flask.py

Prerequisites

Install dependencies

$ gem install sinatra
Initialize your dependencies

Create a file named delivery-receipt.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 delivery-receipt.rb:

Copy to Clipboard
route :get, :post, '/webhooks/delivery-receipt' 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 delivery-receipt.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/delivery-receipt. 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/delivery-receipt. Replace demo with the subdomain provided by Ngrok and enter your endpoint in the field labeled Webhook URL for Delivery Receipts:

#{alt_text}

Try it out

Send a message to a mobile number and you should receive a delivery receipt in the following format:

{
  "err-code": "0",
  "message-timestamp": "2020-10-25 12:10:29",
  "messageId": "0B00000127FDBC63",
  "msisdn": "447700900000",
  "network-code": "23410",
  "price": "0.03330000",
  "scts": "1810251310",
  "status": "delivered",
  "to": "Nexmo CLI"
}