Documentation: Generating Time-Based OTP with HTTP API
This document explains how to generate and retrieve a Time-Based One-Time Password (TOTP) using the OTP Device Sync HTTP API. This feature is ideal for automated tests requiring 2FA (two-factor authentication) with time-based codes.
API Endpoint
Endpoint URL:
GET {API_BASE_URL}/retrieve/totp
This endpoint returns a TOTP for a specified user and service using an API key for authentication.
Request Parameters
- issuer:
string
(required)
The identifier for the service generating the OTP. This corresponds to the service name or application issuing the OTP. - label:
string
(required)
The user identifier for whom the OTP is generated. Typically, this is the user’s email or account name. - registeredKey:
string
(required)
A unique key required to authenticate and authorize the API request.
Example Query:
GET {API_BASE_URL}/retrieve/totp?issuer=ServiceName&label=user@example.com®isteredKey=YOUR_REGISTERED_KEY
Response
The API returns a JSON response with the OTP and any additional status messages.
Success Response:
{
"code": "123456" // The TOTP code
}
Error Response: If there is an error, the API will return a 4xx or 5xx status code with an error message.
{
"error": "Invalid registeredKey or missing parameters"
}
Example Usage
To retrieve a TOTP, make a GET request with the required parameters. The following example uses JavaScript (Node.js) to fetch a TOTP:
const fetch = require('node-fetch');
const getTimeBasedCode = async (user, service, registeredKey) => {
const url = new URL(`${process.env.API_BASE_URL}/retrieve/totp`);
url.searchParams.append('issuer', service);
url.searchParams.append('label', user);
url.searchParams.append('registeredKey', registeredKey);
try {
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
console.log(`Retrieved TOTP: ${data.code}`);
return data.code;
} else {
const errorText = await response.text();
throw new Error(`Error retrieving TOTP: ${errorText}`);
}
} catch (error) {
console.error(`Failed to fetch TOTP: ${error.message}`);
throw error;
}
};
// Usage example:
getTimeBasedCode("user@example.com", "ServiceName", "YOUR_REGISTERED_KEY");
Key Points
- Time Sensitivity: The TOTP is valid for a limited time (typically 30 seconds), so retrieve and use it promptly.
- Authentication: Ensure
registeredKey
is stored securely, as it authenticates the request. - Error Handling: Implement error handling to manage cases where the TOTP request fails.
This API-based approach allows efficient, automated retrieval of TOTPs for test scenarios requiring 2FA.