Skip to main content

📧 Email Verification Explorer

Complete the authentication flow by verifying the 6-digit code sent to your email after a successful login.


🧪 Live API Testing

POSThttps://api.swapbits.co/auth/login/verify

Verify the 6-digit email code to complete authentication

Parámetros

6-digit verification code from email

Session token received from login endpoint

Comando cURL

curl -X POST 'https://api.swapbits.co/auth/login/verify' \
  -H 'Content-Type: application/json'

Response Scenarios

✅ Verification Successful (Code 1008)

Authentication complete - Code is valid, JWT tokens issued.

{
"code": 1008,
"message": "OTP code is valid",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "user-uuid",
"email": "user@example.com",
"verified": true,
"firstName": "John",
"lastName": "Doe"
}
}
}

Result: Save tokens and redirect to authenticated area

❌ Invalid Code (Code 4005)

Verification failed - Code doesn't match or is malformed.

{
"code": 4005,
"message": "Invalid verification code",
"id": "error-trace-id"
}

Action: Check the code in your email and try again

⏰ Code Expired (Code 4003)

Time limit exceeded - Code expired (10-minute limit).

{
"code": 4003,
"message": "The OTP code has expired",
"id": "error-trace-id"
}

Action: Start the login process again to get a new code

🚫 Invalid Token (Code 4015)

Session expired - Login token is invalid or expired.

{
"code": 4015,
"message": "Invalid token",
"id": "error-trace-id"
}

Action: Return to Login Explorer and start over


🔄 Verification Flow

📧 Email Verification Process

Complete verification steps:

  1. Successful Login → Receive session token + verificationType: "EMAIL_CODE"
  2. Check Email → Look for 6-digit code (check spam folder)
  3. Verify Code → POST to /auth/login/verify (you are here)
  4. Authentication Complete → Receive JWT access/refresh tokens
  5. Start Using API → Include access token in Authorization header

Important Notes:

  • Codes expire in 10 minutes
  • Maximum 3 attempts per session token
  • After 3 failed attempts, you must login again

💻 Integration Examples

cURL Command

Verify email code with cURL
curl -X POST 'https://api.swapbits.co/auth/login/verify' \
-H 'Content-Type: application/json' \
-d '{
"code": "123456",
"token": "your-session-token-here"
}'

JavaScript/TypeScript

Email verification with error handling
interface VerifyResponse {
code: number;
message: string;
data?: {
accessToken: string;
refreshToken: string;
user: {
id: string;
email: string;
verified: boolean;
firstName?: string;
lastName?: string;
};
};
id?: string;
}

async function verifyEmailCode(code: string, sessionToken: string): Promise<VerifyResponse> {
const response = await fetch('https://api.swapbits.co/auth/login/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: code.trim(),
token: sessionToken,
}),
});

return await response.json();
}

// Complete verification flow with state management
class AuthManager {
private accessToken: string | null = null;
private refreshToken: string | null = null;

async verifyAndStoreTokens(code: string, sessionToken: string) {
try {
const result = await verifyEmailCode(code, sessionToken);

switch (result.code) {
case 1008:
// ✅ Success - store tokens
this.accessToken = result.data!.accessToken;
this.refreshToken = result.data!.refreshToken;

// Store in localStorage for persistence
localStorage.setItem('swapbits_access_token', this.accessToken);
localStorage.setItem('swapbits_refresh_token', this.refreshToken);
localStorage.setItem('swapbits_user', JSON.stringify(result.data!.user));

console.log('✅ Authentication complete!', result.data!.user);
return { success: true, user: result.data!.user };

case 4005:
console.log('❌ Invalid verification code');
return { success: false, error: 'Invalid code', retryable: true };

case 4003:
console.log('⏰ Code expired - need to login again');
return { success: false, error: 'Code expired', retryable: false };

case 4015:
console.log('🚫 Session expired - need to login again');
return { success: false, error: 'Session expired', retryable: false };

default:
console.log('❓ Unexpected response:', result);
return { success: false, error: 'Unexpected error', retryable: false };
}
} catch (error) {
console.error('🔥 Network error:', error);
return { success: false, error: 'Network error', retryable: true };
}
}

getAccessToken(): string | null {
return this.accessToken || localStorage.getItem('swapbits_access_token');
}

async makeAuthenticatedRequest(endpoint: string, options: RequestInit = {}) {
const token = this.getAccessToken();
if (!token) {
throw new Error('No access token available');
}

return fetch(`https://api.swapbits.co${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
...options.headers,
},
});
}
}

// Usage
const auth = new AuthManager();
const result = await auth.verifyAndStoreTokens('123456', 'session-token');

if (result.success) {
// Now you can make authenticated requests
const profileResponse = await auth.makeAuthenticatedRequest('/users/me');
const profile = await profileResponse.json();
console.log('User profile:', profile);
}

Python

Email verification with Python
import requests
import json
from typing import Dict, Any, Optional

class SwapBitsAuth:
def __init__(self):
self.access_token: Optional[str] = None
self.refresh_token: Optional[str] = None
self.base_url = 'https://api.swapbits.co'

def verify_email_code(self, code: str, session_token: str) -> Dict[str, Any]:
"""Verify email code and complete authentication"""

url = f'{self.base_url}/auth/login/verify'
data = {
'code': code.strip(),
'token': session_token
}

try:
response = requests.post(url, json=data, timeout=10)
result = response.json()

if result['code'] == 1008:
# ✅ Success - store tokens
self.access_token = result['data']['accessToken']
self.refresh_token = result['data']['refreshToken']

print("✅ Authentication complete!")
return {
'success': True,
'user': result['data']['user'],
'tokens': {
'access': self.access_token,
'refresh': self.refresh_token
}
}
elif result['code'] == 4005:
print("❌ Invalid verification code")
return {'success': False, 'error': 'Invalid code', 'retryable': True}
elif result['code'] == 4003:
print("⏰ Code expired - need to login again")
return {'success': False, 'error': 'Code expired', 'retryable': False}
elif result['code'] == 4015:
print("🚫 Session expired - need to login again")
return {'success': False, 'error': 'Session expired', 'retryable': False}
else:
print(f"❓ Unexpected response: {result}")
return {'success': False, 'error': 'Unexpected error', 'retryable': False}

except requests.exceptions.RequestException as e:
print(f"🔥 Network error: {e}")
return {'success': False, 'error': 'Network error', 'retryable': True}

def make_authenticated_request(self, endpoint: str, method: str = 'GET', data: Dict = None) -> requests.Response:
"""Make authenticated API request"""

if not self.access_token:
raise ValueError("No access token available")

url = f'{self.base_url}{endpoint}'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {self.access_token}'
}

if method.upper() == 'GET':
return requests.get(url, headers=headers)
elif method.upper() == 'POST':
return requests.post(url, headers=headers, json=data)
# Add other methods as needed

# Usage
auth = SwapBitsAuth()
result = auth.verify_email_code('123456', 'session-token-from-login')

if result['success']:
print(f"Welcome, {result['user']['email']}!")

# Now make authenticated requests
profile_response = auth.make_authenticated_request('/users/me')
profile = profile_response.json()
print(f"Profile: {profile}")

🔗 Next Steps

🎯 After Successful Verification

You're now authenticated! Here's what you can do:

  • 👤 Profile Explorer - View and update your profile
  • 💰 Banking Explorer (Coming Soon) - Access trading features
  • 🔄 Session Management (Coming Soon) - Manage your tokens
  • 🛡️ 2FA Setup - Add extra security to your account

🆘 Troubleshooting

🔧 Common Issues & Solutions

Problem: Code not received in email Solution: Check spam folder, wait up to 2 minutes, verify email address

Problem: Getting "Invalid verification code" with correct code Solution: Check for extra spaces, ensure 6 digits exactly, case sensitive

Problem: Code expired error Solution: Start over from Login Explorer to get fresh code

Problem: Session token invalid Solution: The login session expired, start fresh login process

Problem: Multiple failed attempts Solution: After 3 failures, you must complete a new login flow