Skip to content

Instantly share code, notes, and snippets.

@otoo-peacemaker
Created August 13, 2024 08:46
Show Gist options
  • Save otoo-peacemaker/62f98d86d6c2db0b26c214f942353510 to your computer and use it in GitHub Desktop.
Save otoo-peacemaker/62f98d86d6c2db0b26c214f942353510 to your computer and use it in GitHub Desktop.
Infobip API Implementation witth Javascript and Axios
const express = require('express');
const axios = require('axios');
const router = express.Router();
const FormData = require('form-data');
const {baseUrl, key} = require('@config/test_config.js').infobip;
// Helper function to make API requests
const infobipRequest = async (endpoint, data, method = 'POST') => {
try {
const response = await axios({
method,
url: `${baseUrl}${endpoint}`,
data,
headers: {
'Authorization': `App ${key}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
maxRedirects: 20
});
return response.data;
} catch (error) {
console.error(`Error during Infobip API request to ${endpoint}:`, error.response ? error.response.data : error.message);
throw new Error(error.response ? error.response.data : error.message);
}
};
// Helper function to send emails
const infobipSendEmail = async ({ from, subject, to, text, placeholders }) => {
const form = new FormData();
form.append('from', from);
form.append('subject', subject);
form.append('to', JSON.stringify([{ to, placeholders }]));
form.append('text', text);
try {
const response = await axios.post(`${baseUrl}/email/3/send`, form, {
headers: {
'Authorization': `App ${key}`,
'Content-Type': 'multipart/form-data',
...form.getHeaders()
},
maxRedirects: 20
});
return response.data;
} catch (error) {
console.error(`Error during Infobip API request to /email/3/send:`, error.response ? error.response.data : error.message);
throw new Error(error.response ? error.response.data : error.message);
}
};
// Endpoint for sending SMS
router.post('/send-sms', async (req, res) => {
const { to, message } = req.body;
const smsData = {
messages: [
{
destinations: [{ to }],
from: 'ServiceSMS',
text: message
}
]
};
try {
const data = await infobipRequest('/sms/2/text/advanced', smsData);
res.status(200).json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Combined endpoint for creating application, setting up template, and sending OTP
router.post('/send-sms-otp', async (req, res) => {
const { applicationName, messageText, to } = req.body;
try {
// Step 1: Create 2FA application
const createAppData = {
name:applicationName,
enabled: true,
configuration: {
pinAttempts: 10,
allowMultiplePinVerifications: true,
pinTimeToLive: '15m',
verifyPinLimit: '1/3s',
sendPinPerApplicationLimit: '100/1d',
sendPinPerPhoneNumberLimit: '10/1d'
}
};
const appResponse = await infobipRequest('/2fa/2/applications', createAppData);
const applicationId = appResponse.applicationId;
// Step 2: Set up 2FA message template
const createTemplateData = {
pinType: "NUMERIC",
messageText,
pinLength: 4,
senderId: "ServiceSMS"
};
const templateResponse = await infobipRequest(`/2fa/2/applications/${applicationId}/messages`, createTemplateData);
const messageId = templateResponse.messageId;
console.log('Created Message ID:', messageId); // Debugging log
// Step 3: Deliver the passcode
const sendOtpData = {
applicationId,
messageId,
from: "ServiceSMS",
to
};
const otpResponse = await infobipRequest('/2fa/2/pin', sendOtpData);
res.status(200).json({
application: appResponse,
template: templateResponse,
otp: otpResponse
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Endpoint for verifying the passcode
router.post('/verify-sms-otp', async (req, res) => {
const { pinId, pin } = req.body;
const postData = { pin };
try {
const data = await infobipRequest(`/2fa/2/pin/${pinId}/verify`, postData);
res.status(200).json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Endpoint to send email
router.post('/send-email', async (req, res) => {
const { from, subject, to, text, placeholders } = req.body;
if (!from || !subject || !to || !text) {
return res.status(400).json({ error: 'Missing required fields: from, subject, to, text' });
}
try {
const response = await infobipSendEmail({ from, subject, to, text, placeholders });
res.status(200).json(response);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment