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

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

HTML Date Form: Setting the Start Date to Tomorrow with JavaScript

Is there a way to restrict the start date to tomorrow's local date? I'm having trouble with the code below: <form method="POST"> <div> <label for="s2">pickup_date</label> ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Is there a way for me to retrieve the UrlMatcher from ui-router?

While exploring the ui-router documentation, I came across an object called UrlMatcher. This object contains useful methods like exec, but I am struggling to find clear instructions on how to access it. Nevertheless, the documentation page provides a detai ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

User input determines the path of Iron Route in Meteor

A requirement is to execute a function that prompts the user for input and then navigates to that specified value. For instance, if the inserted value is: https://www.youtube.com/watch?v=_ZiN_NqT-Us The intended destination URL should be: download?u ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Implementing Button Activation and Deactivation Upon Checkbox Selection in JQuery

When a single checkbox is selected, the Edit and Delete buttons are enabled while the Add button is disabled. If two or more checkboxes are selected, the Delete button is enabled while the Add and Edit buttons are disabled. This is my HTML code: < ...

Print custom jQuery attribute to console or log output

I need help retrieving and displaying a custom jQuery attribute in either an alert or console. Despite attempting to use console.log() to access my custom data attribute, I am unable to see its value appear. The specific value I am trying to display is d ...

Sending properties in NextJS from the server side (Application routing)

In order to share data for each request, I have created an object with this data in the rootLayout. export interface IProps { children: React.ReactNode; data: any; } export default function RootLayout(props: IProps) { const {children} = props; ...

Enhancing Real-time Communication with NodeJS and NowJs Servers

Recently, I stumbled upon NodeJS and NowJS and I'm fascinated by the technology. My goal is to develop a Facebook-style instant commenting application where users can post comments that will instantly appear on the feed. After watching the screencast ...

Using the JSON parameter in C# with MVC 3

I'm facing an issue with sending JSON data from a JavaScript function to a C# method using Ajax. When I receive the data in C#, it's not being recognized as JSON. How can I resolve this issue? If I try to output the received data using Response.W ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

What is the best way to retrieve the value of the "Observer" object?

I am a user of Vue.js and I have the following data in this.suspendedReserveMemo: this.suspendedReserveMemo [__ob__: Observer]650: "memo3"651: "memo4"652: ""653: ""654: ""655: ""656: ""657: ""658: ""659: ""660:""661: ""662: ""length: 663__ob__: Observer {v ...

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

Having trouble sending data to API with Node, Express, and vanilla JavaScript POST form

I am currently utilizing Node JS along with Express JS in order to implement a form submission that pushes data into the database. Below is my form structure <form action="/pokedex/register/poke_submission" method="POST"> ...

Leveraging Toaster Notifications in AngularJS for Custom Exception Management and Logging

Implemented the use of AngularJS Toaster for effective notification handling. To customize exception handling, set up in index.html as shown below <toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...