Documentation: Retrieving OTP Sent by SMS with JavaScript Library
This document explains how to retrieve a One-Time Password (OTP) sent via SMS using the otp-device-sync
JavaScript library. This approach is ideal for automating tests that require SMS-based OTPs to verify two-factor authentication (2FA) flows.
Installation
To use the library, first install it via npm:
npm install otp-device-sync
Importing the Function
The library provides a getSMSCode
function specifically for retrieving OTPs sent by SMS.
import { getSMSCode } from 'otp-device-sync';
Function Overview: getSMSCode
Purpose: Retrieve an OTP sent by SMS for a specified user and service.
Function Parameters
The getSMSCode
function accepts the following parameters:
- user:
string
(required)
The phone number of the user receiving the OTP. - service:
string
(required)
The identifier for the service sending the OTP (e.g., sender name or number). - options:
object
(required)verbose
:boolean
(optional) – Enables logging if set totrue
.timeout
:number
(optional) – Timeout in milliseconds; defaults to 5 minutes.registeredKey
:string
(required) – Unique key to authenticate and authorize the request.
Return Value
The getSMSCode
function returns a Promise<{ code: string }>
object containing:
- code:
string
– The OTP code retrieved from the SMS.
Example Usage
Here’s an example of how to use the getSMSCode
function to retrieve an SMS OTP:
import { getSMSCode } from 'otp-device-sync';
(async () => {
try {
const smsOTP = await getSMSCode("+1234567890", "ServiceName", {
verbose: true,
timeout: 300000, // 5 minutes in milliseconds
registeredKey: "YOUR_REGISTERED_KEY"
});
console.log(`Retrieved SMS OTP: ${smsOTP.code}`);
} catch (error) {
console.error(`Error retrieving SMS OTP: ${error.message}`);
}
})();
Key Points
- Time Sensitivity: Retrieve the OTP promptly, as it may expire.
- Authentication: Ensure
registeredKey
is stored securely, as it is required for authorization. - Error Handling: Use try/catch blocks to manage potential retrieval issues.
Verbose Mode
Setting verbose: true
in the options enables detailed logging, useful for debugging the OTP retrieval process.
Summary
The otp-device-sync
library makes it straightforward to retrieve OTPs sent via SMS, allowing you to streamline 2FA testing in automated test environments. The getSMSCode
function helps automate OTP handling with ease, making it a valuable asset for end-to-end testing of SMS-based authentication flows.