DEV Community

Cover image for Phone number verification via OTP in Node JS
Phone Email
Phone Email

Posted on

Phone number verification via OTP in Node JS

In the rapidly evolving landscape of web and mobile applications, ensuring a secure and seamless user experience is paramount. Traditional username-password combinations are giving way to more innovative authentication methods. One such breakthrough is the "Log in with Phone" button, a solution offered by Phone Email that allows users to verify their phone numbers at little to no cost.

Introduction to "Log in with Phone" Button
The "Log in with Phone" button operates similarly to Firebase phone authentication. It is embedded in client websites or mobile apps, triggering a new authentication window upon clicking. This window prompts users to enter their country code and mobile number, subsequently verifying the provided information using a one-time passcode (OTP) sent to the user's mobile device. Once the phone number is verified, control returns to the client's website or app, armed with an access token for further interactions.

How "Log in with Phone" Button Automatically Sends SMS OTP
The heart of the "Log in with Phone" functionality lies in its ability to seamlessly send SMS OTP to users. This process involves the generation and delivery of a unique passcode to the provided mobile number, serving as a secure method of authentication. The automation of this SMS OTP delivery adds a layer of convenience and security to the user verification process.

Integration Steps for Node.js
1. Create Admin Account
Begin by creating an admin account on the Phone Email platform. This account will provide the necessary credentials for integrating the “Log in with Phone” button into your Node.js application.

2. Add "Log in with Phone" Button to Call Free SMS OTP API in React JS Frontend
To integrate the "Log in with Phone" button into your React JS frontend, follow these steps:

// code snippet for integrating "Log in with phone" button

import React, { useEffect, useState } from "react";

const App = () => {
  const searchParams = new URLSearchParams(window.location.search);
  const accessToken = searchParams.get('access_token');

  // Replace with your actual CLIENT_ID
  const CLIENT_ID = "YOUR_CLIENT_ID";

  const REDIRECT_URL = window.location.href;
  const AUTH_URL = `https://auth.phone.email/log-in?client_id=${CLIENT_ID}&redirect_url=${REDIRECT_URL}`;

  // Use state to manage user details
  const [userDetails, setUserDetails] = useState({
    countryCode: "",
    phoneNo: "",
    phEmailJwt: ""
  });


  useEffect(() => {
    if (accessToken) {
      httpRequest();
    }
  }, [accessToken]);

  return (
    <React.Fragment>
      {!accessToken && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '50px 30px' }}>
          <div style={{ color: '#024430 !important', textAlign: 'center', backgroundColor: '#fff', padding: '30px', borderRadius: '0.5rem', boxShadow: '0 1px 3px rgba(17, 24, 39, .09)', width: '100%', maxWidth: '420px', margin: '0 auto', fontFamily: 'sans-serif, serif, system-ui, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen, Ubuntu, Cantarell, \'Open Sans\', \'Helvetica Neue\', sans-serif', lineHeight: '28px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <img className="phe-login-img" width="250px" src="https://storage.googleapis.com/prod-phoneemail-prof-images/phem-widgets/phe-signin-box.svg"
              alt="phone email login demo" />
            <h1 style={{ margin: "10px" }}>Sign In</h1>
            <p style={{ color: "#a6a6a6" }}>Welcome to Sign In with Phone</p>
            <button
              style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '14px 20px', backgroundColor: '#02BD7E', fontWeight: 'bold', color: '#ffffff', border: 'none', borderRadius: '3px', fontSize: 'inherit', cursor: 'pointer', maxWidth: '320px', width: '100%' }}
              id="btn_ph_login"
              name="btn_ph_login"
              type="button"
              onClick={() => window.open(AUTH_URL, 'peLoginWindow', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0, width=500, height=560, top=' + (window.screen.height - 600) / 2 + ', left=' + (window.screen.width - 500) / 2)}>
              <img src="https://storage.googleapis.com/prod-phoneemail-prof-images/phem-widgets/phem-phone.svg"
                alt="phone email" style={{ marginRight: "10px" }} />
              Sign In with Phone
            </button>
          </div>
        </div>
      )}

      {accessToken && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '50px 30px' }}>
          <div style={{ color: '#024430 !important', textAlign: 'center', backgroundColor: '#fff', padding: '30px', borderRadius: '0.5rem', boxShadow: '0 1px 3px rgba(17, 24, 39, .09)', width: '100%', maxWidth: '420px', margin: '0 auto', fontFamily: 'sans-serif, serif, system-ui, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen, Ubuntu, Cantarell, \'Open Sans\', \'Helvetica Neue\', sans-serif', lineHeight: '28px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }}>
            <img className="phe-login-img" width="250px" src="https://storage.googleapis.com/prod-phoneemail-prof-images/phem-widgets/phe-signin-success.svg" alt="phone email login demo" />
            <div className="phem-card-body">
              <h1>Welcome!</h1>
              <h4 style={{ lineHeight: "36px" }}>You are logged in successfully with <br />
                {userDetails.countryCode} {userDetails.phoneNo}
              </h4>
            </div>
            <button style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '14px 20px', backgroundColor: '#02BD7E', fontWeight: 'bold', color: '#ffffff', border: 'none', borderRadius: '3px', fontSize: 'inherit', cursor: 'pointer', maxWidth: '320px', width: '100%', }} onClick={() => window.location.href = '/'}>Back</button>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Ensure to replace YOUR_CLIENT_ID with your actual client ID.

3. Get Verified Phone Numbers Back in Node.js Using getuser Rest API
After successful phone number verification, retrieve verified phone numbers back in Node.js using the getuser REST API. Pass the access token and client ID in the request parameters of the getuser API call. Check the GitHub repository here for the complete code snippet.

// React JS code snippet for integrating "Log in with phone" button
// GitHub: https://github.com/phoneemail/sign-in-with-phone-reactjs
const httpRequest = async () => {
    try {
      const url = "https://eapi.phone.email/getuser";
      const data = new FormData();

      data.append("access_token", accessToken);
      data.append("client_id", CLIENT_ID);

      const response = await fetch(url, { method: "POST", body: data });

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const responseData = await response.json();

      if (responseData.status !== 200) {
        throw new Error("Something went wrong");
      }

      const phEmailJwt = responseData.ph_email_jwt;

      setUserDetails({
        countryCode: responseData.country_code,
        phoneNo: responseData.phone_no,
        phEmailJwt: phEmailJwt
      });

      // Register User: As the user phone number has been verified successfully. If user corrosponding to this verified  mobile number does not exist in your user table then register the user by creating a row in user table. If user already exists then simply continue to the next step.

    } catch (error) {
      console.error("Fetch error:", error);
    }
  };
Enter fullscreen mode Exit fullscreen mode

FAQs
Q: What is OTP or passcode?
A: OTP stands for One-Time Passcode. It is a unique, temporary code sent to a user's mobile device for authentication purposes.

Q: What is Phone Authentication?
A: Phone authentication is a secure method of verifying a user's identity by validating their mobile phone number using methods such as OTP.

Q: How does "Log in with Phone" work?
A: The "Log in with Phone" button triggers an authentication window where users enter their country code and mobile number. Upon verification, an access token is provided for further interactions.

Q: How does OTP verification work?
A: OTP verification involves sending a one-time passcode to the user's mobile device. The user then enters this code to confirm their identity.

Conclusion
Embrace the future of user authentication with the "Log in with Phone" button and the seamless integration of free SMS OTP services in Node.js. Elevate your application's security while providing a user-friendly experience. Get started today and revolutionize the way users verify their identities.

Explore further:

  • Phone Authentication Demo using "Log in with Phone" Button
  • Read Docs

Top comments (1)

Collapse
 
baby_walks_8e667a9df4d339 profile image
Baby Walks

Phone crossbody bags typically feature secure closures like zippers or magnetic snaps shop, reducing the risk of your phone falling out or being stolen compared to carrying it in your hand or pocket.