You are on page 1of 2

using System;

using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Mvc;

public class HomeController : Controller


{
// Replace with your actual 2Factor.in API key
private const string ApiKey = "YOUR_API_KEY";

public async Task<ActionResult> Index()


{
// Your user's phone number
string phoneNumber = "91999999999";

// Generate a random 4-digit OTP


string otp = GenerateRandomOtp();

// Send the OTP via 2Factor.in API


bool isOtpSent = await SendOtp(phoneNumber, otp);

if (isOtpSent)
{
// OTP sent successfully
// You can store the OTP in the session or database for verification
later
TempData["otp"] = otp;
return View();
}
else
{
// Error handling if OTP sending fails
return View("Error");
}
}

[HttpPost]
public ActionResult VerifyOtp(string enteredOtp)
{
// Retrieve the previously generated OTP from TempData
string storedOtp = TempData["otp"] as string;

if (enteredOtp == storedOtp)
{
// OTP verification successful
ViewBag.Message = "OTP verified successfully!";
}
else
{
// Incorrect OTP
ViewBag.Message = "Incorrect OTP. Please try again.";
}

return View("Index");
}

private async Task<bool> SendOtp(string phoneNumber, string otp)


{
using (HttpClient client = new HttpClient())
{
string apiUrl =
$"http://2factor.in/API/V1/{ApiKey}/SMS/{phoneNumber}/{otp}";

try
{
HttpResponseMessage response = await client.GetAsync(apiUrl);
response.EnsureSuccessStatusCode();

// Check the response content if needed


// string responseBody = await
response.Content.ReadAsStringAsync();

return true;
}
catch (HttpRequestException)
{
// Handle exceptions here
return false;
}
}
}

private string GenerateRandomOtp()


{
// Generate a 4-digit random OTP
Random random = new Random();
return random.Next(1000, 9999).ToString();
}
}

You might also like