From 3a54aa056463cd9c9c6f648b925fdc777c5da840 Mon Sep 17 00:00:00 2001 From: Chinmay G Date: Wed, 19 Sep 2018 18:22:34 +0530 Subject: [PATCH] setOtpTamplate, setOtpLength, send function refactoring. --- README.md | 30 +++-- index.js | 341 ++++++++++++++++++++++++++++++------------------------ 2 files changed, 211 insertions(+), 160 deletions(-) diff --git a/README.md b/README.md index 6245a96..cbcc4d4 100644 --- a/README.md +++ b/README.md @@ -5,15 +5,15 @@ This SDK enables sendOTP and allows you to send OTP ### Set-up: 1. Download the NPM module -``` +```node npm install sendotp --save ``` 2. Require the package in your code. -``` +```javascript const SendOtp = require('sendotp'); ``` 3. Initialize with your [MSG91](https://msg91.com) auth key -``` +```javascript const sendOtp = new SendOtp('AuthKey'); ``` That's all, your SDK is set up! @@ -36,24 +36,40 @@ Error object sample code ### Usage: -To send OTP, without optional parameters +##### To send OTP + ```javascript sendOtp.send("919999999999", "PRIIND", function (error, data) { console.log(data); }); ``` -To send OTP, with optional parameters +##### To send Custom OTP + +Make sure OTP code length is set using `setOtpLength(otp_length)` where `otp_length` is same as length of custom OTP code. ```javascript sendOtp.send("919999999999", "PRIIND", "4635", function (error, data) { console.log(data); }); ``` -If you want to set custom expiry of OTP verification +##### Optional settings. + +Set OTP Expiry +```javascript +sendOtp.setOtpExpiry(otp_expiry); // otp_expiry is number of minutes (default: 1440, max: 1440, min: 1)` +``` +Set OTP Length ```javascript -sendOtp.setOtpExpiry('90'); //in minutes +sendOtp.setOtpLength(otp_length); // otp_length is number (default: 4, max: 9, min: 4) ``` +Set OTP Template +```javascript +sendOtp.setOtpTemplate(template); // template is string. +``` +**Important:** placeholder is ##OTP## (ex. `Your otp is ##OTP##.`) +Placeholder is required in template string which will be replaced with actual OTP by library. + To retry OTP ```javascript diff --git a/index.js b/index.js index 702011e..c653f5c 100644 --- a/index.js +++ b/index.js @@ -4,175 +4,210 @@ let request = require('request'); class SendOtp { - /** - * Creates a new SendOtp instance - * @param {string} authKey Authentication key - * @param {string, optional} messageTemplate - */ - constructor(authKey, messageTemplate) { - this.authKey = authKey; - if(messageTemplate){ - this.messageTemplate = messageTemplate; - }else{ - this.messageTemplate = "Your otp is {{otp}}. Please do not share it with anybody"; - } - this.otp_expiry = 1440; //1 Day =1440 minutes + /** + * Creates a new SendOtp instance + * @param {string} authKey Authentication key + * @param {string, optional} messageTemplate + */ + constructor(authKey, messageTemplate) { + this.authKey = authKey; + if (messageTemplate) { + this.messageTemplate = messageTemplate; + } else { + this.messageTemplate = "Your otp is ##OTP##."; } - - /** - * Returns the base URL for MSG91 api call - * @returns {string} Base URL for MSG91 api call - */ - static getBaseURL() { - return "https://control.msg91.com/api/"; + this.otp_expiry = 1440; //1 Day =1440 minutes + this.otp_length = 4; + } + + /** + * Returns the base URL for MSG91 api call + * @returns {string} Base URL for MSG91 api call + */ + static getBaseURL() { + return "https://control.msg91.com/api/"; + } + + /** + * Set the OTP expiry minutes default: 1440, min: 1, max: 1440 + */ + setOtpExpiry(otp_expiry) { + this.otp_expiry = otp_expiry; + return; + } + + /** + * Set the OTP template. + * The placeholder for OTP in the template content should be ##OTP## + * ##OTP## will be replaced with actual OTP. + */ + setOtpTemplate(template) { + this.messageTemplate = template; + return; + } + + /** + * Set the OTP length between default: 4, min: 4, max: 9 + */ + setOtpLength(otp_length) { + if (otp_length > 3 && otp_length < 10) { + this.otp_length = otp_length; + return; } - - /** - * Set the OTP expiry minutes for MSG91 api call - */ - setOtpExpiry(otp_expiry) { - this.otp_expiry=otp_expiry; - return; + throw new Error("OTP length is not in between 4 to 9."); + } + + /** + * Returns the 4 digit otp + * @returns {integer} 4 digit otp + */ + static generateOtp() { + return Math.floor(1000 + Math.random() * 9000); + } + + /** + * Send Otp to given mobile number + * @param {string} contactNumber receiver's mobile number along with country code + * @param {string} senderId + * @param {string, optional} otp + * Return promise if no callback is passed and promises available + */ + send(contactNumber, senderId, otp, callback) { + let message = this.messageTemplate; + let customOTP = undefined; + if (typeof otp === 'function') { + callback = otp; + } else { + let otpLength = otp.toString().length; + if (otpLength === this.otp_length) { + customOTP = otp; + message = this.messageTemplate.replace('##OTP##', otp); + } else { + throw new Error("Invalid OTP length. Expected OTP length is " + this.otp_length); + } } + let args = { + authkey: this.authKey, + mobile: contactNumber, + sender: senderId, + message: message, + otp_expiry: this.otp_expiry, + otp_length: this.otp_length + }; - /** - * Returns the 4 digit otp - * @returns {integer} 4 digit otp - */ - static generateOtp() { - return Math.floor(1000 + Math.random() * 9000); + if (customOTP) { + args['otp'] = customOTP } - - /** - * Send Otp to given mobile number - * @param {string} contactNumber receiver's mobile number along with country code - * @param {string} senderId - * @param {string, optional} otp - * Return promise if no callback is passed and promises available - */ - send(contactNumber, senderId, otp, callback) { - if (typeof otp === 'function') { - callback = otp; - otp = SendOtp.generateOtp() - } - let args = { - authkey: this.authKey, - mobile: contactNumber, - sender: senderId, - message: this.messageTemplate.replace('{{otp}}', otp), - otp: otp, - otp_expiry: this.otp_expiry - }; - return SendOtp.doRequest('get', "sendotp.php", args, callback); + return SendOtp.doRequest('get', "sendotp.php", args, callback); + } + + /** + * Retry Otp to given mobile number + * @param {string} contactNumber receiver's mobile number along with country code + * @param {boolean} retryVoice, false to retry otp via text call, default true + * Return promise if no callback is passed and promises available + */ + retry(contactNumber, retryVoice, callback) { + let retryType = 'voice'; + if (!retryVoice) { + retryType = 'text' } + let args = { + authkey: this.authKey, + mobile: contactNumber, + retrytype: retryType + }; - /** - * Retry Otp to given mobile number - * @param {string} contactNumber receiver's mobile number along with country code - * @param {boolean} retryVoice, false to retry otp via text call, default true - * Return promise if no callback is passed and promises available - */ - retry(contactNumber, retryVoice, callback) { - let retryType = 'voice'; - if (!retryVoice) { - retryType = 'text' - } - let args = { - authkey: this.authKey, - mobile: contactNumber, - retrytype: retryType - }; + return SendOtp.doRequest('get', "retryotp.php", args, callback); + } + + /** + * Verify Otp to given mobile number + * @param {string} contactNumber receiver's mobile number along with country code + * @param {string} otp otp to verify + * Return promise if no callback is passed and promises available + */ + verify(contactNumber, otp, callback) { + let args = { + authkey: this.authKey, + mobile: contactNumber, + otp: otp + }; + return SendOtp.doRequest('get', "verifyRequestOTP.php", args, callback); + } - return SendOtp.doRequest('get', "retryotp.php", args, callback); - } + static doRequest(method, path, params, callback) { - /** - * Verify Otp to given mobile number - * @param {string} contactNumber receiver's mobile number along with country code - * @param {string} otp otp to verify - * Return promise if no callback is passed and promises available - */ - verify(contactNumber, otp, callback) { - let args = { - authkey: this.authKey, - mobile: contactNumber, - otp: otp - }; - return SendOtp.doRequest('get', "verifyRequestOTP.php", args, callback); + if (typeof params === 'function') { + callback = params; + params = {}; + } + // Return promise if no callback is passed and promises available + else if (callback === undefined && this.allow_promise) { + promise = true; } - static doRequest (method, path, params, callback) { - - if (typeof params === 'function') { - callback = params; - params = {}; - } - // Return promise if no callback is passed and promises available - else if (callback === undefined && this.allow_promise) { - promise = true; - } + let options = { + method: method, + url: SendOtp.getBaseURL() + "" + path + }; - let options = { - method: method, - url: SendOtp.getBaseURL() + "" + path - }; + if (method === 'get') { + options.qs = params; + } - if (method === 'get') { - options.qs = params; - } + // Pass form data if post + if (method === 'post') { + let formKey = 'form'; - // Pass form data if post - if (method === 'post') { - let formKey = 'form'; + if (typeof params.media !== 'undefined') { + formKey = 'formData'; + } + options[formKey] = params; + } - if (typeof params.media !== 'undefined') { - formKey = 'formData'; - } - options[formKey] = params; + request(options, function (error, response, data) { + // request error + if (error) { + return callback(error, data); + } + + // JSON parse error or empty strings + try { + // An empty string is a valid response + if (data === '') { + data = {}; } - - request(options, function(error, response, data) { - // request error - if (error) { - return callback(error, data); - } - - // JSON parse error or empty strings - try { - // An empty string is a valid response - if (data === '') { - data = {}; - } - else { - data = JSON.parse(data); - } - } - catch(parseError) { - return callback( - new Error('JSON parseError with HTTP Status: ' + response.statusCode + ' ' + response.statusMessage), - data - ); - } - - - // response object errors - // This should return an error object not an array of errors - if (data.errors !== undefined) { - return callback(data.errors, data); - } - - // status code errors - if(response.statusCode < 200 || response.statusCode > 299) { - return callback( - new Error('HTTP Error: ' + response.statusCode + ' ' + response.statusMessage), - data - ); - } - // no errors - callback(null, data); - }); - - }; + else { + data = JSON.parse(data); + } + } + catch (parseError) { + return callback( + new Error('JSON parseError with HTTP Status: ' + response.statusCode + ' ' + response.statusMessage), + data + ); + } + + + // response object errors + // This should return an error object not an array of errors + if (data.errors !== undefined) { + return callback(data.errors, data); + } + + // status code errors + if (response.statusCode < 200 || response.statusCode > 299) { + return callback( + new Error('HTTP Error: ' + response.statusCode + ' ' + response.statusMessage), + data + ); + } + // no errors + callback(null, data); + }); + + }; }