Alerts

You use Event Based Alerts to communicate with people using Event Based Alerts. Provision a US Short Code with a standard or custom template that specifies the custom parameters for Alert messages.

Note: quality of delivery (QoD) statistics are based on delivery receipts (DLR). For the US we only receive intermediate and not handset DLRs. This means Dashboard analytics cannot show QoD statistics for short codes.

Sending Alerts

You use Event Based Alerts to send custom messages to your users. Before you use this API you have to Setup a Pre-approved Short Code for Event Based Alerts

The workflow for sending Event Based Alerts is:

Event Based Alerts Workflow

  1. Send an Event Based Alerts request.

  2. Check the response codes in the response and ensure that you sent the request to Nexmo correctly.

  3. Nexmo sends the alert to your user.

  4. Receive the delivery receipt at your webhook endpoint and verify delivery.

Implementing the Event Based Alerts workflow

To send Event Based Alerts to your users:

  1. Send an Event Based Alerts request. If you have multiple templates, remember to set the template number in your request.

    var https = require('https');
    
    var data = JSON.stringify({
     api_key: 'API_KEY',
     api_secret: 'API_SECRET',
     to: 'TO_NUMBER',
     TEMPLATE_VARIABLE_NAME: 'VALUE'
    });
    
    var options = {
     host: 'rest.nexmo.com',
     path: '/sc/us/alert/json',
     port: 443,
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
       'Content-Length': Buffer.byteLength(data)
     }
    };
    
    var req = https.request(options);
    
    req.write(data);
    req.end();
    
    var responseData = '';
    req.on('response', function(res){
     res.on('data', function(chunk){
       responseData += chunk;
     });
    
     res.on('end', function(){
       console.log(JSON.parse(responseData));
     });
    });
    
    <?php
    $url = 'https://rest.nexmo.com/sc/us/alert/json?' . http_build_query([
            'api_key' => 'API_KEY',
            'api_secret' => 'API_SECRET',
            'to' => 'TO_NUMBER',
            'TEMPLATE_VARIABLE_NAME' => 'VALUE'
        ]);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    
    import urllib
    
    params = {
        'api_key': 'API_KEY',
        'api_secret': 'API_SECRET',
        'to': 'TO_NUMBER',
        'TEMPLATE_VARIABLE_NAME' : 'VALUE'
    }
    
    url = 'https://rest.nexmo.com/sc/us/alert/json?' + urllib.urlencode(params)
    
    response = urllib.urlopen(url)
    print response.read()
    
    require "net/http"
    require "uri"
    
    uri = URI.parse("https://rest.nexmo.com/sc/us/alert/json")
    params = {
        'api_key' => 'API_KEY',
        'api_secret' => 'API_SECRET',
        'to' => 'TO_NUMBER',
        'TEMPLATE_VARIABLE_NAME' => 'VALUE'
    }
    
    response = Net::HTTP.post_form(uri, params)
    
    puts response.body
    
  2. Check the response codes in the response and ensure that you sent the request to Nexmo correctly:

    // Decode the json object you retrieved when you ran the request.
    
    var decodedResponse = JSON.parse(responseData);
    
    console.log('You sent ' + decodedResponse['message-count'] + ' messages.\n');
    
    decodedResponse['messages'].forEach(function(message) {
        if (message['status'] === "0") {
          console.log('Success ' + decodedResponse['message-id']);
        }
        else {
          console.log('Error ' + decodedResponse['status']  + ' ' +  decodedResponse['error-text']);
        }
    });
    
    <?php
    // Decode the json object you retrieved when you ran the request.
    $decoded_response = json_decode($response, true);
    
    error_log('You sent ' . $decoded_response['message-count'] . ' messages.');
    
    foreach ( $decoded_response['messages'] as $message ) {
        if ($message['status'] == 0) {
            error_log("Success " . $message['message-id']);
        } else {
            error_log("Error {$message['status']} {$message['error-text']}");
        }
    }
    
    import json
    
    #Using the response object from the request
    
    if response.code == 200 :
        data = response.read()
        #Decode JSON response from UTF-8
        decoded_response = json.loads(data.decode('utf-8'))
        # Check if your messages are succesful
        messages = decoded_response["messages"]
        for message in messages:
            if message["status"] == "0":
                print "success"
    else :
        #Check the errors
        print "unexpected http {code} response from nexmo api". response.code
    
    require 'json'
    
    # Decode the json object from the response object you retrieved from the request.
    if response.kind_of? Net::HTTPOK
      decoded_response = JSON.parse(response.body )
    
      messagecount = decoded_response["message-count"]
    
      decoded_response["messages"].each do |message|
        if message["status"] == "0"
            p "message " + message["message-id"] + " sent successfully.\n"
          else
            p "message has error " + message["status"]  + " " + message["error-text"]
        end
      end
    else
      puts response.code + " error sending message"
    end
    
  3. Nexmo sends the alert to your user.

  4. Receive the delivery receipt at your webhook endpoint so you can see:

    1. If the status was delivered.
    2. When and how the message was made.
    3. How much the message cost.
    var app = require('express')();
    app.set('port', (process.env.PORT || 5000));
    app.use(require('body-parser').urlencoded({
        extended: false
    }));
    // Handle GET webhook
    app.get('/delivery-receipt-webhook', function(req, res) {
        handleWebhook(req.query, res);
    });
    // Handle POST webhook
    app.post('/delivery-receipt-webhook', function(req, res) {
        handleWebhook(req.body, res);
    });
    
    function handleWebhook(params, res) {
        if (!params['status'] || !params['messageId']) {
            console.log('This is not a delivery receipt');
        } else {
            //This is a DLR, check that your message has been delivered correctly
            if (params['status'] !== 'delivered') {
                console.log("Fail:", params['status'], ": ", params['err-code']);
            } else {
                console.log("Success");
              /*
                * The following parameters in the delivery receipt should match the ones
                * in your request:
                * Request - from, dlr - to\n
                * Response - message-id, dlr - messageId
                * Request - to, Responese - to, dlr - msisdn
                * Request - client-ref, dlr - client-ref
               */
            }
        }
        res.sendStatus(200);
    }
    app.listen(app.get('port'), function() {
        console.log('Example app listening on port', app.get('port'));
    });
    
    <?php
    // work with get or post
    $request = array_merge($_GET, $_POST);
    
    // Check that this is a delivery receipt.
    if (!isset($request['messageId']) OR !isset($request['status'])) {
        error_log('This is not a delivery receipt');
        return;
    }
    
    //Check if your message has been delivered correctly.
    if ($request['status'] == 'delivered') {
        error_log("Your message to {$request['msisdn']} (message id {$request['messageId']}) was delivered.");
        error_log("The cost was {$request['price']}.");
    } elseif ($request['status'] != 'accepted') {
        error_log("Your message to {$request['msisdn']} (message id {$request['messageId']}) was accepted by the carrier.");
        error_log("The cost was {$request['price']}.");
    } else {
        error_log("Your message to {$request['msisdn']} has a status of: {$request['status']}.");
        error_log("Check err-code {$request['err-code']} against the documentation.");
    }
    
    #To run this code, replace the MyHandler in
    #https://wiki.python.org/moin/BaseHttpServer With the following code,
    from urlparse import urlparse, parse_qs
    class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def do_GET(s):
            """Tell Nexmo that you have recieved the GET request."""
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            """Parse parameters in the GET request"""
            parsed_path = urlparse(s.path)
            try:
                    delivery_receipt = dict(
                    [p.split('=') for p in parsed_path[4].split('&')])
            except:
                    delivery_receipt = {}
    
                """Check the is a delivery receipt"""
            if 'text' in delivery_receipt:
                print ("This is not a delivery receipt")
            elif delivery_receipt['status'] != "delivered":
                print "Fail:" + delivery_receipt['status']
                + ": " + delivery_receipt['err-code'] +  ".\n"
            else:
                print "success"
                    """Handle the DLR for a message sent succesfully
                        The following parameters in the delivery receipt should
                        match the ones in your request:
                         * Request - from, dlr - to
                         * Response - message-id, dlr - messageId
                         * Request - to, Responese - to, dlr - msisdn
                         * Request - client-ref, dlr - client-ref
                        Use the documentation to check the values."""
    
    require 'socket'
    require 'uri'
    
    def handle_delivery_receipt(request_line)
    #Parse the parameters and check if the message was delivered
      params = URI::decode_www_form(request_line).to_h
      if params["status"].nil? or params["messageId"].nil?
        p ('This is not a delivery receipt')
      elsif params["status"] != 'delivered'
        p ("Your request " + params["status"] +
        "because of " + params["err-code"] );
      else
        p ("Success for request " + params['messageId'] )
      end
    end
    
    # Initialize a TCPServer
    server = TCPServer.new('', 9999)
    
    # Wait for connections
    loop do
      # Wait until a client connects
      socket = server.accept
    
      method, path = socket.gets.split
      handle_delivery_receipt(path)
    
      # Return the 200 so Nexmo does not send the DLR to you repeatedly
      socket.print "HTTP/1.1 200 OK"
      # Close the socket, terminating the connection
      socket.close
    end
    

Note: remember to send return 200 ok when you receive the delivery receipt.