JavaScript SMS API Integration Guide
Complete guide to integrate SMS API with JavaScript applications. Frontend and backend examples with error handling.
Platform Integration Guides
JavaScript SMS API Integration Guide
Learn how to integrate SMS functionality into your JavaScript applications, both frontend and backend, using our REST API.
Prerequisites
- Modern web browser or Node.js environment
- Basic knowledge of JavaScript and HTTP requests
- Valid API key from OnlineSMSService
- Understanding of async/await or Promises
Frontend Integration (Browser)
Client-side SMS Sending
// Frontend SMS Integration (Note: API key should be handled securely)
async function sendSMS(phone, message) {
try {
const response = await fetch('https://api.onlinesmsservice.com/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_api_key_here'
},
body: JSON.stringify({
to: phone,
message: message,
sender: 'OTPSMS',
type: 'transactional'
})
});
if (response.ok) {
const result = await response.json();
console.log('SMS sent successfully:', result);
return result;
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch (error) {
console.error('Failed to send SMS:', error);
throw error;
}
}
// Usage example
sendSMS('919876543210', 'Your OTP is: 123456')
.then(result => console.log('Success:', result))
.catch(error => console.error('Error:', error));
Backend Integration (Node.js)
// Backend SMS Integration with Express.js
const express = require('express');
const app = express();
app.use(express.json());
// SMS service class
class SMSService {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.onlinesmsservice.com';
}
async sendSMS(to, message, sender = 'OTPSMS') {
try {
const response = await fetch(`${this.baseUrl}/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
to: to,
message: message,
sender: sender,
type: 'transactional'
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('SMS sending failed:', error);
throw error;
}
}
}
// Initialize SMS service
const smsService = new SMSService(process.env.SMS_API_KEY);
// API endpoint
app.post('/api/send-otp', async (req, res) => {
try {
const { phone } = req.body;
const otp = Math.floor(100000 + Math.random() * 900000);
await smsService.sendSMS(phone, `Your OTP is: ${otp}`);
res.json({
success: true,
message: 'OTP sent successfully'
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Failed to send OTP',
error: error.message
});
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
React.js Integration
// React component for SMS integration
import React, { useState } from 'react';
const SMSForm = () => {
const [phone, setPhone] = useState('');
const [message, setMessage] = useState('');
const [loading, setLoading] = useState(false);
const [result, setResult] = useState(null);
const sendSMS = async (e) => {
e.preventDefault();
setLoading(true);
try {
const response = await fetch('/api/send-sms', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ phone, message })
});
const data = await response.json();
setResult(data);
} catch (error) {
setResult({ success: false, message: 'Failed to send SMS' });
} finally {
setLoading(false);
}
};
return (
);
};
export default SMSForm; Ready to Start Integrating SMS?
Get your API key and start sending SMS messages in minutes
Get API Key Try API Playground