Systenics Solutions Logo
  • Home start here
  • Solutions services we provide
  • Products products we build
  • About Us who we are
  • Contact Us request a quote
  • Jobs work for us
  • Blog our views

Blog

Home / Blog

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

  • by:
  • in:
  • tags: .NET, C-Sharp
  • 0 Comments

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

Share This Post:

About the Author

This post was written by on Wednesday March 15, 2017.

Related Posts
  • Uncheck Radio Button in WPF - 23 March 2013
  • Use Lets Encrypt SSL with AuctionWorx - 25 April 2017
  • Enable TLS 1.2 for Authorize.Net and Salesforce API calls - 13 July 2017
  • Use Lucene.Net in for faster data search - 12 February 2017
  • Integrate Salesforce with C# or ASP.NET MVC Application - 15 December 2015
comments powered by Disqus
< Older Newer >
All Categories
  • Programming
  • General
  • DevOps
Tags
  • .NET (9)
  • Ajax (1)
  • Android (3)
  • ASP.NET (1)
  • ASP.NET 4.5 (1)
  • ASP.NET 5 (1)
  • ASP.NET 6 (1)
  • asp.net core (1)
  • ASP.NET MVC (12)
  • AuctionWorx (2)
  • Bootstrap (4)
  • Build and Release (1)
  • CI (1)
  • ClickOnce (1)
  • ClientDependency (1)
  • Code Signing (1)
  • Continuous Integration (1)
  • C-Sharp (9)
  • devops (1)
  • ExpressJS (1)
  • Interview Process (1)
  • iOS (1)
  • Linux (1)
  • Lucene (1)
  • MVC (2)
  • NodeJS (1)
  • Phonegap (3)
  • Razor (4)
  • Salesforce (2)
  • Socket.IO (1)
  • SQL CE 3.5 SP2 (1)
  • SQL Server (1)
  • Sync (1)
  • Sync Framework v2.1 (1)
  • Umbraco 6 (6)
  • Umbraco 7 (4)
  • Visual Studio 2015 (1)
  • Visual Studio Online (1)
  • VMWare ESXI 6.0 (1)
  • WCF (1)
  • Windows (2)
  • WPF (2)

About Us

Systenics Solutions is a customized software development company. We specialize in building Cloud, Web, and Mobile based applications using the latest Cloud Technologies. Our fine-tuned agile processes help you smoothly progress from conceptualizing your ideas, building proto-types/wireframes to bringing your product to market, giving our clients complete visibility and control at all times. We strive to provide our global clients of various sizes with cost effective benefits of offshore development while providing expert technical services.


Microsoft Partner - Gold Cloud Platform

Contact Us

Systenics Solutions

The Affaires, Unit #F-1, 1st Floor, Plot #9, Sector - 17, Opp. Bhumiraj Costarica, Sanpada, Navi Mumbai - 400705, India

 

Telephone: +91-22-2781 0808

Email: info@systenics.com

Skype: saurabhn

Testimonials

"Coming from a non-technical background, Saurabh and his team at Systenics took my business idea and turned it into a fully functional application which surpassed my expectations! You can be sure with them that all your IT related concerns will be covered."

Shobhan, CEO - IITJobs Inc

"The ability Systenics showed in code signing and deploying my click once code in Microsoft visual was truly awesome. I interviewed and tested 6 different development companies and only one was actually able to get the job done - that was Systenics Solutions! Professional, courteous and reliable - I highly recommend them and am very happy and eager to continue growing our business relationship now and in the near future. Thank you Saurabh"

Andre Pierre

I contracted with Systenics about 6 months ago, in an effort to customize auction software for a new company I am launching in the US. The entire process was as smooth as could be. Their estimate for the project was reasonable, and very close to the final number. I would absolutely use this company again, and I have so much confidence in their ability to work with me, I even agreed to a support agreement with them long term. Their ability to communicate with me in the US was always very timely. They listened to my thoughts and ideas, and then suggested some changes, that made my software have even greater value. I cannot thank them enough, and would highly suggest their quality services to anyone. A completely satisfied customer!

Joe Lefebvre - Pharmabid, LLC

Systenics did a great job on our customization , they clearly understood the requirements and completed the task in a timely manner. They were very thorough in project discussions and made sure that we understood how the customization works and suggested improvements when required

Mike Singh - Dr. Liquidator

Copyright © 2012-2018 Systenics Solutions. All rights reserved.

BACK TO TOP