Integration of Nexmo SMS and Verify API using C# for AuctionWorx

by: Shruti Sawant in: Programming tags: ASP.NET MVC, AuctionWorxs,

Introduction

This tutorial explains how to use Nexmo SMS and Verify API to add additional functionality into AuctionWorx MVC application. Nexmo SMS API is used to send and receive a high volume of SMS anywhere in the world. There are many APIs Nexmo provides and in this article I am going to explain two APIs - SMS and Verify.

Nexmo even provides an official Nexmo Client Library for C#/.NET for .Net Framework 4.5.2 and above which will allow you to integrate their API calls with your C# application. But in our case, we had an older version of AuctionWorx MVC application which was running on .Net Framework 4.5.1 and hence we decided to write our own code to call their APIs. Refer this link to know more about .Net Framework issue on Nexmo GitHub.

Pre-requisites

1. Mobile or landline phone number (mobile preferred to receive SMS).

2. Nexmo Test Account - you can create a test account using your mobile or landline phone number and Nexmo provides free credit which is enough to get started to learn how to use their APIs in your application.

3. Visual Studio (C#)

Nexmo SMS API

1. It is used to send SMS to given number. Using this API, you can send any customize text message. It follows below scenario.

2. Create Request: Send a request to Nexmo to send SMS to user.

3. Get Response: Gives response to ensure that SMS request you sent is successful.

SMS API Request

This is rest API. For e.g. https://rest.nexmo.com/sms/json?api_key=xxxxxxxx&api_secret=xxxxxxxx&to=ToNumber&from=FromNumber&text=hello+test+message

Where,
a. https://rest.nexmo.com/sms is Base URL. All the request to the SMS API must use this URL. Your base URL becomes either: json / XML (https://rest.nexmo.com/sms/json or https://rest.nexmo.com/sms/xml)
b. api_key and api_secret: Nexmo provides this "api_key" and "api_secret" from Nexmo Dashboard
c. to: A single phone number in international format. You can set one recipient only for each request.
d. from: A single phone/mobile number with country code from which SMS is going to be sent.
e. text: The SMS body. Messages where "type" is "text" (the default) are in UTF-8 with URL encoding.

Let’s start with the coding :)

1. Create 2 model classes - SmsResponse and Message.

    public class SmsResponse
    {
        public string MessageCount { get; set; }
        public List Messages { get; set; }
    }

    public class Message
    {
        public string To { get; set; }
        public string MessageId { get; set; }
        public string Status { get; set; }
        public string RemainingBalance { get; set; }
        public string MessagePrice { get; set; }
        public string Network { get; set; }
        public string From { get; set; }
    }

2. Create class "SMS" and create a method "SendSms" of return type "SmsResponse" and pass "to" number and "type=text" string as a parameter.

3. Now to send request to Nexmo SMS API, use following code:

        string uri = string.Format("{0}/sms/json?from={1}&to={2}&text={3}&api_key= {4}&api_secret={5} &type={6}",
            ConfigurationManager.AppSettings["Nexmo.Url.Rest"],
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.from_number"]),
            HttpUtility.UrlEncode(toNumber),
            HttpUtility.UrlEncode(text),
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.api_key"]),
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.api_secret"]),
            type);
        var json = new WebClient().DownloadString(uri);

Here you have to add "api_key" and "api_secret" as I mentioned above. I have added this key-value pair in web.config file as shown below.

                
  <appSettings>
    <!-- START - Nexmo SMS API settings -->
    <add key="Nexmo.Url.Rest" value="https://rest.nexmo.com" />
    <add key="Nexmo.Url.Api" value="https://api.nexmo.com" />
    <add key="Nexmo.api_key" value="your api key goes here" />
    <add key="Nexmo.api_secret" value="your api_secret key goes here" />
    <add key="Nexmo.from_number" value="country_code+ from_number goes here" />
    <!-- END - Nexmo SMS API settings -->
  </appSettings>

4. To get the SMS API response:

    
        SmsResponse result = JsonConvert.DeserializeObject(json);

SMS API Response

Each request you make using the SMS API returns a response - the "status" and "price" of your request to Nexmo in JSON or XML format. Each response comes in specific format with key and value pair.

{
  "message-count": "1",
  "messages": [
    {
      "status": "returnCode",
      "message-id": "messageId",
      "to": "to",
      "client-ref": "client-ref",
      "remaining-balance": "remaining-balance",
      "message-price": "message-price",
      "network": "network",
      "error-text": "error-message"
    }
  ]
}

Refer this link for detail information. I have attached the output of the SMS API below.

img1
Figure 1: Output for SMS API Sample

 

Nexmo Verify API

Nexmo Verify API is used to send a PIN by SMS or Text-To-Speech in order to prove that a user can be contacted on a specific phone number.

By default, the Nexmo Verify API sends PIN (OTP) by an SMS. Due to some reason if there is no reply, it sends PIN by TTS. The reason can be the receiver number user is providing might be a landline number.

This can be used to verify that a phone number is valid, reachable and accessible by that user.

Verify API Request

A Verify API request looks like: https://api.nexmo.com/verify/json?api_key=xxxxxxxx&api_secret=xxxxxxxx&number=xxxxxxxxxxxx&brand=MyApp

Where,
a. https://api.nexmo.com/verify is Base URL. All the request to the SMS API must use this URL. Your base URL becomes either: json / XML (https://api.nexmo.com/verify/json or https://api.nexmo.com/verify/xml)
b. api_key and api_secret: Nexmo provides this "api_key" and "api_secret" from Nexmo Dashboard
c. to: A single phone number in international format. You can set one recipient only for each request.
d. number: A single phone/mobile number with country code to which PIN is going to be sent.
e. brand: The name of the company or application for which you are using Verify API. For example: "Your brand PIN is ...". For more details, click here.

1. Create 2 model classes - JsonResponse and JsonVerifyCheckResponse.

    public class JsonResponse
    {
        public string RequestId { get; set; }
        public int Status { get; set; }
    }

    public class JsonVerifyCheckResponse
    {
        public string EventId { get; set; }
        public int Status { get; set; }
        public decimal Price { get; set; }
        public string Currency { get; set; }
        public string Error { get; set; }
        public string RequestId { get; set; }
    }

2. Create another class "CallTTS" and add method into it named "SendSMSOrCall" with return type "JsonResponse"

3. Now to send request to Verify API, add following line:

       
        string uri = string.Format("{0}/verify/json?api_key={1}&api_secret={2}&number={3}&brand={4}",
            ConfigurationManager.AppSettings["Nexmo.Url.Api"],
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.api_key"]),
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.api_secret"]),
            HttpUtility.UrlEncode(toNumber),
            "--your app name goes here--");

        var json = new WebClient().DownloadString(uri);

You can use more parameters as you want. For more details, click here

4. To get Verify API response, add following line:

        JsonResponse result = JsonConvert.DeserializeObject(json);

5. Each request you make to the Verify API returns:

{
  "request_id": "requestId",
  "status": "status",
  "error_text": "error"
}

6. Now to check whether the PIN number user entered is correct or not, I have created another method named "VerifyOTPCode" with parameter "requestId", "code" and "toNumber" of type string with return type "JsonVerifyCheckResponse"

Where, requestId = Id which is generated by Nexmo per request code = PIN number which user will enter toNumber = phone/mobile number to whom SMS is to be sent. For more details, click here.

7. To send request, add following code in this method:

        string uri = string.Format("{0}/verify/check/json?api_key={1}&api_secret={2}&request_id={3} &code={4}",
            ConfigurationManager.AppSettings["Nexmo.Url.Api"],
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.api_key"]),
            HttpUtility.UrlEncode(ConfigurationManager.AppSettings["Nexmo.api_secret"]),
            requestId, code);

        var json = new WebClient().DownloadString(uri);

8. Now add below line to deserialize the given object and get the response.

        JsonVerifyCheckResponse result = JsonConvert.DeserializeObject(json);

Response will look like following format:

{
  "event_id": "eventId",
  "status": "status",
  "price": "price",
  "currency": "currency",
  "error_text": "error"
}

9. The response contains key-value format. For more details about responses, click here. I have attached the output of Verify API below.

img1
Figure 2: Output for Verify API Sample

 

Some Helpful Links

Getting started sending SMS guide

Nexmo Developer

Happy Coding :)