DEV Community

Cover image for How to send OTP codes with WhatsApp using Node.js
Jahongir Sobirov
Jahongir Sobirov

Posted on

How to send OTP codes with WhatsApp using Node.js

For sending OTP (One-Time Password) codes to clients with WhatsApp using Node.js pretty simple! For that we need only one library which is named auth-verify

npm install auth-verify
Enter fullscreen mode Exit fullscreen mode

Initialize auth-verify

We need to configure our WhatsApp phone number for sending OTP codes.

const AuthVerify = require("auth-verify");
const auth = new AuthVerify();

// configuring whatsapp
auth.otp.sender({
   via: "whatsapp",
   phoneId: "YOUR_PHONE_ID",
   token: "YOUR_WHATSAPP_TOKEN"
});
Enter fullscreen mode Exit fullscreen mode

Sending OTP codes to the users

For sending you need to only send() method from auth-verify:

auth.otp.send("RECIEVER_PHONE", {text: `Your OTP code is ${auth.otp.code}`}, (err, info)=> {
    if(err) console.log(err);
    else console.log(info);
});
Enter fullscreen mode Exit fullscreen mode

Verfiying the OTP code

For verifying it you should use verify() method:

auth.otp.verify("RECIEVER_PHONE", "123456", (err, success) => {
    if(err) console.error(err.message);
    else console.log("✅ OTP verified");
});
Enter fullscreen mode Exit fullscreen mode

Full codes

const AuthVerify = require("auth-verify");
const auth = new AuthVerify();

// configuring whatsapp
auth.otp.sender({
   via: "whatsapp",
   phoneId: "YOUR_PHONE_ID",
   token: "YOUR_WHATSAPP_TOKEN"
});

auth.otp.send("RECIEVER_PHONE", {text: `Your OTP code is ${auth.otp.code}`}, (err, info)=> {
    if(err) console.log(err);
    else console.log(info);
});

auth.otp.verify("RECIEVER_PHONE", "123456", (err, success) => {
    if(err) console.error(err.message);
    else console.log("✅ OTP verified");
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)