Skip to content

Instantly share code, notes, and snippets.

@imdkbj
Created November 4, 2021 04:37
Show Gist options
  • Save imdkbj/a74b7cdf71fd88aeb46466793d57cc5e to your computer and use it in GitHub Desktop.
Save imdkbj/a74b7cdf71fd88aeb46466793d57cc5e to your computer and use it in GitHub Desktop.
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const VERIFY_SERVICE_SID = process.env.VERIFY_SERVICE_SID;
const client = require('twilio')(accountSid, authToken);
const smsErrorHandler = (e) => {
console.log(e)
let { message, code, status } = e;
let _message = (status === 401 && code === 20003) || status === 404 ?
"Error with SMS module" :
code === 60200 ? 'Invalid mobile number' :
code === 20404 ? 'Please resend the OTP' : message;
return { status: false, message: _message }
}
const sendOTP = ({ to }) => {
return new Promise((resolve, reject) => {
client.verify.services(VERIFY_SERVICE_SID)
.verifications.create({ to, channel: 'sms' })
.then(() => resolve({ status: true, message: "OTP sent successfully" }))
.catch(e => resolve(smsErrorHandler(e)))
})
}
const otpVerify = ({ to, code }) => {
return new Promise((resolve, reject) => {
client.verify.services(VERIFY_SERVICE_SID)
.verificationChecks.create({ to, code })
.then(message => resolve({ status: true, message }))
.catch(e => resolve(smsErrorHandler(e)))
})
}
module.exports = {
sendOTP,
otpVerify
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment