Thursday, March 8, 2018

Part 51 - Send OTP ( One Time Password ) to any mobile number in Asp.net MVC



In this video you will be able to know how to send OTP ( One time password) to any mobile number.  You need to follow below steps

1. Visit  TextLocal  official website and Register yourself
2. Generate API Key as show in video

3. Use your API key in C# MVC to send OTP via textlocal API 

Please copy below codes after generating API key.

# View Page (Index.cshtml)
Right click on your controller' s Index method and add a view. After adding view, replace content with below code. 

@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

        <div class="well">
           
            <a href="#" class="btn btn-success" onclick="SendOTP()">Send OTP</a>

        </div>

<script>


    var SendOTP = function () {
        
        $.ajax({
            url: "/Test/SendOTP",
            type: "post",
            success: function (data) {
                if (data == "success") {
                    
                    alert("OTP sent successfully");
                    window.location = "/Test/EnterOTP";
                }
                else {
                    alert("failed");
                }
            }


        })

    }

</script>




# Controller Code (TestController.cs)
Create a Test controller and copy below code into this. 

using ASPSnippets.SmsAPI;
using MVCTutorial.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {         

            return View();
        }

      
        public JsonResult SendOTP()
        {
            int otpValue = new Random().Next(100000, 999999);
            var status = "";
            try
            {
                string recipient =  ConfigurationManager.AppSettings["RecipientNumber"].ToString();
                string APIKey = ConfigurationManager.AppSettings["APIKey"].ToString();

                string message = "Your OTP Number is " + otpValue + " ( Sent By : Technotips-Ashish )";
                String encodedMessage = HttpUtility.UrlEncode(message);

                using (var webClient = new WebClient())
                {
                    byte[] response = webClient.UploadValues("https://api.textlocal.in/send/", new NameValueCollection(){
                                        
                                         {"apikey" , APIKey},
                                         {"numbers" , recipient},
                                         {"message" , encodedMessage},
                                         {"sender" , "TXTLCL"}});

                    string result = System.Text.Encoding.UTF8.GetString(response);

                    var jsonObject = JObject.Parse(result);

                    status = jsonObject["status"].ToString();

                    Session["CurrentOTP"] = otpValue;
                }


                return Json(status, JsonRequestBehavior.AllowGet);


            }
            catch (Exception e)
            {

                throw (e);

            }

        }

        public ActionResult EnterOTP()
        {
            return View();
        }
        
        [HttpPost]
        public JsonResult VerifyOTP(string otp)
        {
            bool result = false;

            string sessionOTP = Session["CurrentOTP"].ToString();

            if (otp == sessionOTP)
            {
                result = true;

            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }
}




#Web.Config file
Add two keys into your web.config file . In first key, Enter Your API key generated by textlocal.com website . In second key, Enter your mobile number as recipient  with country code. example: 919234567895 . You can get mobile number either from database or from the textbox in which user enter his mobile number.


  <add key="APIKey" value="Enter your API key here" />
  <add key="RecipientNumber" value="91XXXXXXXXXX" />
  



All Code Factory


11 comments:

Unknown said...

invalid login details error plzz help

Unknown said...

{"errors":[{"code":3,"message":"invalid login details"}],"status":"failure"} plzzz help plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

Unknown said...

var jsonObject=JObject.Parse(result);
in "JObject" am getting error.
How to solve this?

Unknown said...

Am getting error here

The type or namespace name'ASPSnippets' could not be found (are you missing a using directive or an assembly reference?)

Anonymous said...

really very good tutorial .....

Anonymous said...

This error is comming plz must reply =====> {"errors":[{"code":80,"message":"Invalid template"}],"status":"failure"}

gamikaran said...

{"errors":[{"code":4,"message":"No recipients specified"}],"status":"failure"}



please ans ?

jodi said...

These are some great tools that i definitely use for SEO work. This is a great list to use in the future.. Modern Behaviour Pty Ltd

Unknown said...

{"errors":[{"code":3,"message":"Invalid login details"}],"status":"failure"} how to slove this issu

TechguruJi said...

No full code, please load once again (Enter OTP & Index codes )

Ranjan Kumar Yadav said...

{"errors":[{"code":80,"message":"Invalid template"}],"status":"failure"}

Getting this error plz suggest how to resolve this