Skip to main content

Generate OTP

The genOtp method generates and sends a one-time password (OTP) to a player's email address or phone number. This is the first step in the OTP authentication flow.

How OTP Authentication Works

  1. Generate OTP: Call genOtp with email or phone number
  2. Player Receives OTP: Player receives OTP via email or SMS
  3. Verify OTP: Player enters OTP in your game
  4. Login/Create Account: Use OTP to login or create account

This guide covers step 1. See Login with OTP or Create Account with OTP for steps 3-4.

Basic Usage

Generate OTP with either email or phone number (not both).

Email OTP

MoitribeSDK('my-game-id', 'genOtp', {
emailid: 'player@example.com',
callback: (result) => {
if (result.success) {
console.log('OTP sent to email');
showOtpInputScreen();
} else {
console.error('Failed to send OTP:', result.msg);
}
}
});

Phone OTP

MoitribeSDK('my-game-id', 'genOtp', {
phno: '+1234567890',
callback: (result) => {
if (result.success) {
console.log('OTP sent via SMS');
showOtpInputScreen();
} else {
console.error('Failed to send OTP:', result.msg);
}
}
});

Parameters

ParameterTypeRequiredDescription
emailidstringEither email or phonePlayer's email address
phnostringEither email or phonePlayer's phone number (E.164 format)
callbackfunctionYesCalled with generation result
warning

You must provide either emailid or phno, but not both. The SDK will return an error if both are omitted.

Response Format

The callback receives:

{
success: boolean; // true if OTP was sent successfully
msg?: string; // Error message (if success is false)
statuscode?: number; // Error code (if success is false)
}

Success Response

{
success: true
}

Error Response

{
success: false,
msg: 'Invalid email address',
statuscode: 101
}

Common Status Codes

CodeMeaningAction
0SuccessProceed to OTP input
101Invalid email/phoneValidate input and retry
103Rate limit exceededWait before retrying
105Service unavailableRetry later

Phone Number Format

Phone numbers must be in E.164 format:

// Correct formats
'+1234567890' // US/Canada
'+442071234567' // UK
'+919876543210' // India

// Incorrect formats
'1234567890' // Missing + prefix
'+1 234 567 8900' // Contains spaces
'+1-234-567-8900' // Contains hyphens

Format Helper Function

function formatPhoneNumber(phone) {
// Remove all non-digit characters except +
let cleaned = phone.replace(/[^\d+]/g, '');

// Ensure it starts with +
if (!cleaned.startsWith('+')) {
// Assume US number if no country code
cleaned = '+1' + cleaned;
}

return cleaned;
}

// Usage
const formattedPhone = formatPhoneNumber('(123) 456-7890');
MoitribeSDK('my-game-id', 'genOtp', {
phno: formattedPhone,
callback: handleOtpResult
});

Email Validation

Validate email addresses before generating OTP:

function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}

function generateOtp(emailid) {
if (!isValidEmail(emailid)) {
showError('Please enter a valid email address');
return;
}

MoitribeSDK('my-game-id', 'genOtp', {
emailid: emailid,
callback: (result) => {
if (result.success) {
showOtpInputScreen(emailid);
} else {
showError(result.msg || 'Failed to send OTP');
}
}
});
}

Complete Example: Email OTP Flow

// Step 1: Get email from player
function showEmailInput() {
const email = prompt('Enter your email address:');

if (!email) {
return; // Player cancelled
}

// Validate email
if (!isValidEmail(email)) {
alert('Please enter a valid email address');
showEmailInput(); // Try again
return;
}

// Generate OTP
generateEmailOtp(email);
}

// Step 2: Request OTP
function generateEmailOtp(emailid) {
// Show loading indicator
showLoading('Sending verification code...');

MoitribeSDK('my-game-id', 'genOtp', {
emailid: emailid,
callback: (result) => {
hideLoading();

if (result.success) {
console.log('OTP sent to:', emailid);
showOtpInputScreen(emailid);
} else {
showError(result.msg || 'Failed to send verification code');
}
}
});
}

// Step 3: Player enters OTP
function showOtpInputScreen(emailid) {
const otp = prompt('Enter the 6-digit code sent to ' + emailid);

if (otp) {
// Proceed to login (see Login with OTP guide)
loginWithOtp(emailid, otp);
}
}

function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

Complete Example: Phone OTP Flow

// Step 1: Get phone number from player
function showPhoneInput() {
const phone = prompt('Enter your phone number:');

if (!phone) {
return; // Player cancelled
}

// Format phone number
const formattedPhone = formatPhoneNumber(phone);

// Generate OTP
generatePhoneOtp(formattedPhone);
}

// Step 2: Request OTP
function generatePhoneOtp(phno) {
showLoading('Sending verification code...');

MoitribeSDK('my-game-id', 'genOtp', {
phno: phno,
callback: (result) => {
hideLoading();

if (result.success) {
console.log('OTP sent to:', phno);
showOtpInputScreen(phno);
} else {
showError(result.msg || 'Failed to send verification code');
}
}
});
}

// Step 3: Player enters OTP
function showOtpInputScreen(phno) {
const otp = prompt('Enter the verification code sent to ' + phno);

if (otp) {
// Proceed to login (see Login with OTP guide)
loginWithOtp(null, otp, phno);
}
}

function formatPhoneNumber(phone) {
let cleaned = phone.replace(/[^\d+]/g, '');
if (!cleaned.startsWith('+')) {
cleaned = '+1' + cleaned;
}
return cleaned;
}

TypeScript Example

import MoitribeSDK from '@veniso/moitribe-js';

interface OtpResult {
success: boolean;
msg?: string;
statuscode?: number;
}

interface OtpParams {
emailid?: string;
phno?: string;
callback: (result: OtpResult) => void;
}

const GAME_ID = 'my-game-id';

function generateOtpForEmail(email: string): void {
if (!isValidEmail(email)) {
showError('Please enter a valid email address');
return;
}

const params: OtpParams = {
emailid: email,
callback: (result: OtpResult) => {
if (result.success) {
showOtpInputScreen(email);
} else {
showError(result.msg || 'Failed to send OTP');
}
}
};

MoitribeSDK(GAME_ID, 'genOtp', params);
}

function isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

Rate Limiting

Implement client-side rate limiting to prevent OTP spam:

let lastOtpRequest = 0;
const OTP_COOLDOWN = 60000; // 60 seconds

function generateOtpWithRateLimit(emailid) {
const now = Date.now();
const timeSinceLastRequest = now - lastOtpRequest;

if (timeSinceLastRequest < OTP_COOLDOWN) {
const remaining = Math.ceil((OTP_COOLDOWN - timeSinceLastRequest) / 1000);
showError(`Please wait ${remaining} seconds before requesting another code`);
return;
}

lastOtpRequest = now;

MoitribeSDK('my-game-id', 'genOtp', {
emailid: emailid,
callback: (result) => {
if (result.success) {
showOtpInputScreen(emailid);
} else {
// Reset timer on error so player can retry
lastOtpRequest = 0;
showError(result.msg || 'Failed to send OTP');
}
}
});
}

Error Handling

Handle common error cases:

function handleOtpError(result) {
if (result.statuscode === 101) {
showError('Invalid email or phone number. Please check and try again.');
} else if (result.statuscode === 103) {
showError('Too many requests. Please wait a few minutes and try again.');
} else if (result.statuscode === 105) {
showError('Service temporarily unavailable. Please try again later.');
} else {
showError(result.msg || 'Failed to send verification code. Please try again.');
}
}

MoitribeSDK('my-game-id', 'genOtp', {
emailid: 'player@example.com',
callback: (result) => {
if (result.success) {
showOtpInputScreen();
} else {
handleOtpError(result);
}
}
});

Best Practices

1. Show Clear Instructions

Tell players where to look for the OTP:

MoitribeSDK('my-game-id', 'genOtp', {
emailid: email,
callback: (result) => {
if (result.success) {
showMessage(
'Verification Code Sent',
`We've sent a 6-digit code to ${email}. Please check your inbox and spam folder.`
);
}
}
});

2. Allow Resend

Let players request a new OTP if they don't receive it:

function showOtpInputWithResend(emailid) {
showDialog({
title: 'Enter Verification Code',
message: `Code sent to ${emailid}`,
input: 'text',
buttons: [
{
text: 'Verify',
action: (otp) => loginWithOtp(emailid, otp)
},
{
text: 'Resend Code',
action: () => generateOtpWithRateLimit(emailid)
}
]
});
}

3. Mask Sensitive Information

Don't display full email/phone in UI:

function maskEmail(email) {
const [username, domain] = email.split('@');
const masked = username.substring(0, 2) + '***@' + domain;
return masked;
}

// Show: 'pl***@example.com'
showMessage(`Code sent to ${maskEmail('player@example.com')}`);
tip

OTPs typically expire after 10-15 minutes. Implement a resend feature so players can request a new code if needed.

Next Steps

After generating an OTP, continue with:

Related topics: