Verifying One Time Password (OTP) from MSG91 URL using ReactJS

Currently, I am working on a small project that involves receiving and verifying OTPs from MSG91. While I have managed to successfully receive OTPs using MSG91, I am encountering an issue when trying to verify OTPs - specifically, I keep getting an error message stating 'Failed to verify OTP : Invalid Auth key', even though I am certain that I am using the correct Auth key, template ID, and all other necessary details. The setup includes files such as setupProxy.js and App.js.

const { createProxyMiddleware } = require('http-proxy-middleware');

const templateId = 'xxxxxxxxxxxxxxxxx';
const authKey = 'xxxxxxxxxxxxxxxxxx'; 

module.exports = function(app) {
app.use(
    '/api/verifyOTP',
    createProxyMiddleware({
      target: `https://control.msg91.com/api/v5/otp/verify?authkey=${authKey}`,
      changeOrigin: true,
      pathRewrite: function (path, req) {
        const mobile = req.body ? req.body.mobile : '';
        const otp = req.body ? req.body.otp : '';
        return `&mobile=91${mobile}&otp=${otp}`;
      }
    })
  );
}
<button onClick={verifyOTP}>Verify OTP</button>
const verifyOTP = async () => {
      const mobileNumber = mobile;
  
    try {
      const response = await fetch(`/api/verifyOTP?otp=${otp}&mobile=91${mobileNumber}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
  
      if (response.ok) {
        const responseData = await response.json();
  
        if (responseData.type === 'success' && responseData.message === 'OTP verified successfully') {
          console.log('OTP Verified Successfully');
        } else {
          console.error('Failed to verify OTP:', responseData.message);
        }
      } else {
        console.error('Error verifying OTP. Status code:', response.status);
      }
    } catch (error) {
      console.error('Error verifying OTP:', error);
    }
  };

Answer №1

The problem at hand is that the MSG91 verify OTP API requires the authentication key to be included in the headers, not as query parameters.

It appears that you are attempting to access OTP and mobile numbers in the request body, but when fetching data from the verifyOTP endpoint, you seem to pass them as query parameters instead of including them in the request body. Please make necessary adjustments.

app.use(
    '/api/verifyOTP',
    createProxyMiddleware({
      target: `https://control.msg91.com/api/v5/otp/verify`,
      changeOrigin: true,
      pathRewrite: function (path, req) {
        const mobile = req.query.mobile ?? '';
        const otp = req.query.otp ?? '';
        return `&mobile=91${mobile}&otp=${otp}`;
      },
      headers: {authkey: 'Enter your MSG91 authkey'}
    })
  );
}

Detailed Information

curl --request GET \
     --url 'https://control.msg91.com/api/v5/otp/verify?mobile=919999999999' \
     --header 'accept: application/json' \
     --header 'authkey: Enter your MSG91 authkey'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing public static files in Express by using the routes folder

I'm currently facing an issue with accessing a static file named 'home.html' located in the public directory of my app's architecture: public home.html routes index.js views myapp.js In myapp.js: var express = require('ex ...

Turn off the authentication middleware for a particular HTTP method on a specific endpoint

Currently, I am using Express/Node and have developed authentication middleware to validate JWT on each request. My requirement is to disable this middleware for a specific route (POST '/api/user/') while keeping it active for another route (GET ...

When the nav-element is clicked, it will load the new content/file.php into the div with the id of "include."

Seeking the most efficient method to load content from a php file into a designated div on my webpage, prioritizing speed, minimal performance requirements, and ease of implementation. Unsure whether it's preferable to utilize php or javascript for t ...

Showcase every assortment in mongodb+express

Here is the code I've written to send data to a database: app.post('/thanks', function(req, res) { if (atendees.checkin === req.body.dbstring) { dbConn.then(client => { delete req.fee._id; const db = client.db('myd ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

Adding properties to Vue.js component in the script section without affecting rendering

How can I import component A with props and pass it to another component B for rendering? import MyComponent from '/MyComponent.vue' computed: { compnt: function () { var comp = MyComponent // How can I set props to MyC ...

What is the best way to update the background color for specific days in fullcalendar?

I have been working on my fullcalendar code and I am trying to figure out how to change the background color only for Feb 14. dayRender: function (date, cell) { var Xmas = new Date('2017-02-14'); var weekday = Xmas ...

Is there a way to fetch API data selectively rather than all at once?

Hello everyone, I successfully managed to retrieve data from the Star Wars API in JSON format and display it on my application. Initially, I set the state as 'people.name' to obtain the name object. However, this also rendered unwanted data when ...

Proper method for declaring a global variable within a React component

In the process of working on my react.js project, I have encountered a situation where I need all components to be able to access an object before the main component is rendered. My current approach involves passing the object as a prop to the main compo ...

Examining the execution of a function/method when a click event occurs within a functional component

It took me a while to realize that testing functional components with vue-test-utils can present some challenges In my case, I am utilizing Bootstrap-Vue's B-Button with a @click event that calls a function/method. When I attempt to test whether the ...

Implementing a Bootstrap datetime picker using the hh:mm:ss time format

I'm currently developing an application and I've run into a roadblock with the datetimepicker feature. I need the datepicker to display the date format as yyyy-mm-dd hh:mm:ss (year, month, and date with the current hour, minutes, and seconds). It ...

The D3.extent() function is raising a TypeError because it is unable to iterate over the

I have been struggling with this issue for the past few hours, and I could really use some help. I'm not very familiar with using D3 in conjunction with React. Essentially, I have an anomaly detection algorithm running on the backend Flask App that r ...

Detecting When an Input has an :invalid Selector in Jquery

Here is the code snippet I am currently working with: HTML <input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" /> CSS input[type=text]:invalid { background-color: red; } Javascript $("[data-ty ...

The functionality of List.js is currently not optimized for use with tables

I'm currently experimenting with list.js in order to create a real-time search feature for a table. I have successfully tested it on lists (similar to the example provided at ). However, I am facing difficulty replicating this functionality for tables ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

Altering the character by striking a key

I have a canvas with custom styling. In the center of the canvas is a single letter. Please see the code below for reference. The goal is to change the displayed letter by pressing a key on the keyboard. For instance: Letter A is centered in the canvas: P ...

Error with Ant Design Autocomplete functionality when searching for a number

I am currently using ant design to develop a more advanced autocomplete component that will display data from multiple columns. In this particular scenario, I have two columns named tax_id and legal_name that users can search by. Everything works smoothly ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

What are some strategies for ensuring that Plotly JS can adapt its height and width to fit the entire div dynamically, without relying on fixed pixel dimensions?

Is there a way to ensure that Plotly automatically adjusts to the size of the container #myDiv without any noticeable delay when the top button is clicked? This code snippet demonstrates a high delay: var z = [], steps = [], i; for (i = 0; i < 500; i+ ...