How to Integrate a Secure OTP SMS API in Node.js and PHP (2026 Tutorial)

Two-Factor Authentication (2FA) via SMS OTP is one of the most reliable ways to secure user checkouts, verify registrations, and protect logins. In this tutorial, we will write step-by-step code implementations to integrate a secure OTP SMS verification system into your web app using Node.js and PHP.
To follow this guide, you will need a registered developer account on SMSGo.lk to obtain your secure API Token and Sender Mask.
The OTP Verification Flow
A typical OTP validation flow consists of three steps:
- Generation: When a user initiates login or checkout, generate a secure random 4 to 6 digit code in your backend.
- Transmission: Send this code to the user's mobile number using the SMS API.
- Validation: Store the code temporarily (e.g. in Redis or database with an expiry timestamp) and prompt the user to input the code. Compare the input; if it matches and hasn't expired, authorize the user.
1. Node.js (Express) Implementation
First, install the request library (such as Axios) if you haven't already:
npm install axios
Create a controller function to dispatch the OTP message:
const axios = require('axios');
async function sendOtpSMS(recipientPhone, otpCode) {
const apiUrl = 'https://api.smsgo.lk/v1/send';
const apiToken = process.env.SMSGO_API_TOKEN; // Set this in your environment variables
const payload = {
sender: 'SMSGO', // Your approved sender mask
recipient: recipientPhone, // Format: 9476XXXXXXX
message: `Your verification code is ${otpCode}. It will expire in 5 minutes.`
};
try {
const response = await axios.post(apiUrl, payload, {
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
});
if (response.data && response.data.success) {
console.log('OTP SMS sent successfully:', response.data.messageId);
return true;
} else {
console.error('API Error:', response.data.error);
return false;
}
} catch (error) {
console.error('Request failed:', error.message);
return false;
}
}
2. PHP Implementation
For WordPress, Laravel, or custom PHP backends, you can use PHP cURL to deliver the OTP payload:
<?php
function sendOtpSMS($recipientPhone, $otpCode) {
$apiUrl = 'https://api.smsgo.lk/v1/send';
$apiToken = 'YOUR_SMSGO_API_TOKEN'; // Replace with your token
$payload = [
'sender' => 'SMSGO', // Your approved sender mask
'recipient' => $recipientPhone, // Format: 9476XXXXXXX
'message' => "Your verification code is " . $otpCode . ". It will expire in 5 minutes."
];
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiToken,
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
error_log('cURL Error: ' . $err);
return false;
}
$result = json_decode($response, true);
if (isset($result['success']) && $result['success']) {
return true;
} else {
error_log('API Error: ' . ($result['error'] ?? 'Unknown error'));
return false;
}
}
?>
Security Best Practices for OTP
- Expiry Time limit: Keep the OTP token valid for a maximum of 3 to 5 minutes to mitigate interception risks.
- Rate Limiting: Implement API rate-limiting on your server (e.g. limit requests to 3 per IP/phone number per minute) to prevent bot abuse and SMS spamming charges.
- Code Entropy: Use cryptographically secure random number generators (like crypto.randomInt in Node.js) rather than standard Math.random() to generate codes.
Conclusion
Integrating OTP is a straightforward process that instantly elevates your app's security profile. By using SMSGo.lk (the best and most reliable SMS gateway in Sri Lanka) and its high-speed routing servers, you can build reliable 2FA workflows that delivery codes to Dialog, Mobitel, Hutch, and Airtel customers in under 2 seconds. Fetch your API token today and secure your application in minutes.
Implement this in your platform today
Integrate SMSGo's high-speed Sri Lankan SMS gateway API, set up secure OTP verification, or start bulk marketing campaigns.

