How to send OTPs using Whatsapp - SAMWAD

Get 25% off on new accounts. Limited time offer. Ask us how.

   +91 7766881755   portal@samwad.tech

How to send OTPs using Whatsapp

The need for secure and efficient authentication methods is paramount. One-Time Passwords (OTPs) have emerged as a popular solution for enhancing security in various online transactions and user verifications. OTPs provide a layer of protection against unauthorized access by ensuring that only the rightful user can complete the verification process. They are typically used in scenarios requiring a high level of security, such as banking transactions, account recoveries, and access to sensitive information.

Traditionally, OTPs have been sent via SMS. However, the rapid evolution of communication technology has introduced new, more effective methods. One of the most promising alternatives to SMS for sending OTPs is WhatsApp Business API. This platform offers several advantages over traditional SMS, making it a superior choice for businesses and service providers. Below, we will explore why OTPs are essential and why sending them via WhatsApp Business API is a better option compared to SMS.

Why OTPs Are Relevant

  1. Enhanced Security: OTPs significantly reduce the risk of unauthorized access and fraud. Each OTP is unique and valid for only a short period, ensuring that even if intercepted, it cannot be reused.
  2. User Convenience: OTPs simplify the authentication process for users. Instead of remembering complex passwords, users receive a simple code that they can use for verification.
  3. Regulatory Compliance: In many industries, the use of OTPs is mandated by regulatory bodies to ensure the security of user data and transactions.

Advantages of Using WhatsApp Business API for OTPs

High Delivery Rates

WhatsApp messages have a higher delivery and read rate compared to SMS. Users are more likely to see and respond to messages on WhatsApp promptly.

Rich Media Capability

Unlike SMS, WhatsApp supports rich media, allowing businesses to send not just text but also images, videos, and documents, enhancing the user experience.

Cost-Effective

Sending messages via WhatsApp can be more cost-effective, especially for businesses with a large customer base. This can lead to significant savings in the long run.

Global Reach

WhatsApp is used by over 2 billion people worldwide, making it an ideal platform for businesses looking to reach a global audience.


Enhanced User Engagement

WhatsApp allows for two-way communication, enabling businesses to engage with customers more effectively. This can improve customer satisfaction and loyalty.

Security and Privacy

WhatsApp offers end-to-end encryption, ensuring that the OTPs are delivered securely and cannot be intercepted by third parties.


How to send OTPs using Whatsapp.

1. Create  an Authentication Template

Create an authentication template by visiting Manage template on your whatsapp business manager. Click here to visit.

2. Click on create template and select Authentication

This essentially conveys to meta that we are creating an authentication template.

Click Next.

3. Enter Essential Details

After entering your template name and selecting language as English (can be any language of your choice).

Now we have few choices for setup :

  • Zero-tap autofill : To be selected when we are trying to use it for any application. Fill out your application package name on next step.
  • One-tap autofill : When user intervention is required to fill the otp in application. The main difference being the need of user intervention.
  • Copy Code : Your customers can directly copy the otp.

Optional Items

  • Select expiration time for the otp.
  • Change the button code from Copy Code to anything else.

Upon filling up the required details, Click submit. The template confirmation can be immediate. 

You can confirm the same using your SAMWAD account by visiting Templates -> Sync.

4. Lets Code!

Now in order to send the otp in your application, copy the code depending on your application. If your application is not listed below, drop a message on our whatsapp number and support team will get in touch with you.

				
					<?php

function generateOtp($length = 6) {
    $digits = '0123456789';
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= $digits[rand(0, 9)];
    }
    return $otp;
}

function sendOtp($phoneNumber, $otp) {
    $url = 'https://www.app.samwad.tech/api/wpbox/sendtemplatemessage';
    $payload = json_encode([
        "token" => *ENTER YOUR TOKEN FROM SAMWAD DASHBOARD*
        "phone" => $phoneNumber,
        "template_name" => "website_otp",
        "template_language" => "en",
        "components" => [
            [
                "type" => "body",
                "parameters" => [
                    [
                        "type" => "text",
                        "text" => $otp
                    ]
                ]
            ],
            [
                "type" => "button",
                "sub_type" => "url",
                "index" => "0",
                "parameters" => [
                    [
                        "type" => "text",
                        "text" => $otp
                    ]
                ]
            ]
        ]
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

// Example usage
$otp = generateOtp();
$phoneNumber = *RECEIVER PHONE NUMBER*;
$response = sendOtp($phoneNumber, $otp);
print_r($response);
?>

				
			
				
					import random
import string
import requests

def generate_otp(length=6):
    """Generate a random OTP of a given length."""
    digits = string.digits
    otp = ''.join(random.choice(digits) for _ in range(length))
    return otp

def send_otp(phone_number, otp):
    url = "https://www.app.samwad.tech/api/wpbox/sendtemplatemessage"
    payload = {
        "token":  *ENTER YOUR TOKEN FROM SAMWAD DASHBOARD*,
        "phone": phone_number,
        "template_name": "website_otp",
        "template_language": "en",
        "components": [
            {
                "type": "body",
                "parameters": [
                    {
                        "type": "text",
                        "text": otp
                    }
                ]
            },
            {
                "type": "button",
                "sub_type": "url",
                "index": "0",
                "parameters": [
                    {
                        "type": "text",
                        "text": otp
                    }
                ]
            }
        ]
    }
    headers = {"Content-Type": "application/json"}
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

# Example usage
otp = generate_otp()
phone_number = "RECEIVER PHONE NUMBER"
response = send_otp(phone_number, otp)
print(response)

				
			
				
					const axios = require('axios');

function generateOtp(length = 6) {
    const digits = '0123456789';
    let otp = '';
    for (let i = 0; i < length; i++) {
        otp += digits[Math.floor(Math.random() * 10)];
    }
    return otp;
}

function sendOtp(phoneNumber, otp) {
    const url = 'https://www.app.samwad.tech/api/wpbox/sendtemplatemessage';
    const payload = {
        token:  *ENTER YOUR TOKEN FROM SAMWAD DASHBOARD*,
        phone: phoneNumber,
        template_name: 'website_otp',
        template_language: 'en',
        components: [
            {
                type: 'body',
                parameters: [
                    {
                        type: 'text',
                        text: otp
                    }
                ]
            },
            {
                type: 'button',
                sub_type: 'url',
                index: '0',
                parameters: [
                    {
                        type: 'text',
                        text: otp
                    }
                ]
            }
        ]
    };
    return axios.post(url, payload, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
}

// Example usage
const otp = generateOtp();
const phoneNumber = 'RECEIVER PHONE NUMBER';
sendOtp(phoneNumber, otp)
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error(error);
    });

				
			
				
					using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class OTPGenerator
{
    public static string GenerateOtp(int length = 6)
    {
        const string digits = "0123456789";
        Random random = new Random();
        char[] otp = new char[length];

        for (int i = 0; i < length; i++)
        {
            otp[i] = digits[random.Next(digits.Length)];
        }

        return new string(otp);
    }

    public static async Task SendOtpAsync(string phoneNumber, string otp)
    {
        var url = "https://www.app.samwad.tech/api/wpbox/sendtemplatemessage";
        var payload = new
        {
            token = " *ENTER YOUR TOKEN FROM SAMWAD DASHBOARD*",
            phone = phoneNumber,
            template_name = "website_otp",
            template_language = "en",
            components = new[]
            {
                new
                {
                    type = "body",
                    parameters = new[]
                    {
                        new
                        {
                            type = "text",
                            text = otp
                        }
                    }
                },
                new
                {
                    type = "button",
                    sub_type = "url",
                    index = "0",
                    parameters = new[]
                    {
                        new
                        {
                            type = "text",
                            text = otp
                        }
                    }
                }
            }
        };

        var jsonPayload = JsonConvert.SerializeObject(payload);
        var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.PostAsync(url, httpContent);
            var responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseContent);
        }
    }

    // Example usage
    public static async Task Main(string[] args)
    {
        string otp = GenerateOtp();
        string phoneNumber = "RECEIVER PHONE NUMBER";
        await SendOtpAsync(phoneNumber, otp);
    }
}

				
			

Conclusion

In conclusion, the integration of One-Time Passwords (OTPs) with the WhatsApp Business API offers a secure, efficient, and user-friendly solution for modern authentication needs. The increasing demand for enhanced security measures in online transactions and user verifications makes OTPs essential. WhatsApp Business API stands out as a superior method for sending OTPs compared to traditional SMS, providing high delivery rates, rich media capabilities, cost-effectiveness, global reach, and robust security through end-to-end encryption.

By following the step-by-step guide provided, businesses can seamlessly generate and send OTPs using Python, Node.js, PHP, and ASP.NET. This versatility ensures that developers can implement OTP functionality regardless of their preferred programming language or platform. The ability to engage with users through a familiar and widely-used messaging platform like WhatsApp further enhances user experience and satisfaction.

Get in touch with us to know more.

Table of Contents

Grow your business with Whatsapp API today!