DEV Community

Cover image for How to use Nexmo verify API and Message API in React native
absek
absek

Posted on • Originally published at kriss.io on

How to use Nexmo verify API and Message API in React native

In this tutorial, we are going to implement the verification process in our React Native application. For the verification process, we are going to use Nexmo to verify API and message API with React Native. Nexmo is a platform that provides full-service verification service. They help to deploy a scalable verification solution without compromising the user experience. this tutorial inspired by React Native Social Chat App Template

Currently, the user can register and use the app instantly. Now, we are going to add a verification page after the user successfully registers. First, we are going to create a Nexmp app for verification and message API. Then, we are going to create a verification server by using codesandbox. Finally, we will configure these verification APIs and server to our React Native app logic and test the result.

Prepare the Nexmo App

First, we are going to create a Nexmo app and configure it. To create a Nexmo app we need to go to the Nexmo developer dashboard and log in. If we don’t have an account then we need to register into the Nexmo platform which is pretty easy. We can see the Nexmo login interface below through which we can register as well as log in.

After successful registration and login into the Nexmo platform, we will be redirected to Nexmo dashboard as shown in the screenshot below:

In the drawer menu of the dashboard, we can see the “Messages and Dispatch” option which can be collapsed into the additional sub-menu options.

Among the options, we need to click on ‘Create an application’ option in order to create a Nexmo app. Then, we need to provide an application name i.e. ‘nexmo test app’ here. After that, we can see the ‘Generate public/private key pair’ button at the bottom in the screenshot below. We need to click on it to generate a key that provides us with a private key in order to use it for connecting to the Nexmo server. Then, we need to save that private key into our local directory in order to use later while creating our server. The key file here is named as jwtRS256.key.

Configurations of Nexmo app

Now, we need to fill webhook URL to receive status from Nexmo server as shown in the screenshot below:

Next, we need to click on ‘Create application’ on the bottom right-hand side which will provide us with a Nexmo app named ‘nexmo test app’ as shown in the code snippet below:

As we can see in the screenshot above, we have successfully created the Nexmo app with all the required configurations. Now, we create the server in codesandbox which handles the verification messages API with the key that we generated.

Creating a Server

For verification purposes, we need to create a server that handles the sending and checking of the OTP code. In this tutorial, we are going to demonstrate the implementation of the server by using codesandbox.

First, we need to go to codesandboxwhich is an online editor or IDE for coding and creating demos. Here, we need to login to the codesandbox account using our GitHub account. Then, we need to go to our dashboard and create a sandbox by clicking on ‘Create Sandbox’ which opens up a dialog as shown in the screenshot below:

From the dialog shown in the above screenshot, choose ‘Node’ as configuration. Then, it will load the template for Node.js server with all the files already configured as shown in the editor screenshot below:

Setting up Dependencies

Now, we can see that there is a ‘Dependencies’ dropdown option on the left-hand side menu. It has a option to add the required dependencies to our Node project. So, we need to click on ‘Add Dependency’ button in the Dependencies dropdown which will open up a dialog with a number of dependencies list as shown in the screenshot below:

On the dependences dialog shown above, there is an input field at the top to search for the required dependencies. So, we just need to type the name of the dependency that is required, which will appear in the list below the input and then click on the dependency to install them into our project. The list of packages or dependencies to search and install are given in the screenshot below:

Remember to install all the packages shown in the above screenshot.

Next, we need to add the private key that we generated in our Nexmo app and downloaded to our local directory as jwtRS256.keyinto our Node project as shown in the screenshot below:

To add the key file, we just need to click on the ‘file’ icon option in the ‘src’ file header options, navigate to the directory where we downloaded the key and then, double-click on the key file to add.

Now, its time to do some coding.

Imports and Configurations

First, we are going to import and initialize all the dependencies as shown in the code snippet below:

const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const Nexmo = require("nexmo");
const cors = require("cors");
const path = require("path");

Next, we need to add Nexmo app credentials to the Codesandbox environment variable. In order to do this, we need to go to the sandbox ‘Server control panel’, there we will see the place to add the secret keys at the bottom. Now, we need to add the keys with name and value as shown in the screenshot below:

After adding the keys, we can now use the Node environment variable into our codesandbox Node project.

Now, we are going to initialize the Nexmo app into our Node project using Nexmo() class which takes apiKey, apiSecret, applicationId, privateKeyas parameters. These parameters are initialized with the value from the environment variable and the key that we set up earlier as shown in the code snippet below:

const nexmo = new Nexmo(
             { apiKey: process.env.apiKey, 
               apiSecret: process.env.apiSecret, 
               applicationId: process.env.applicationId, 
               privateKey: path.join(__dirname, "jwtRS256.key") 
             }
);

Checking OTP code

Now, we initialize other core configurations into our project. We had initialized an expresspackage into the appvariable which provides a use() method. We are going to define the cors() method inside the app.use()method in order to receive the cross-site requests. Then, we are going to define a port as 3000 which is going to listen to all the incoming requests. Then, we are going to parse those incoming request using bodyParserwith json() method to parse the request data into JSON format. The code to implement all these configurations is given in the code snippet below:

app.use(cors());
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Next, we need to create a function to handle the sending of OTP. The express package defined in appvariable provides us with post method to receive the send verification code request and respond accordingly. The request will consist of country code as callingCodeand phone number as phoneNumberwhich will send to the Nexmo app to verify. The implementation of the function to send the OTP request to Nexmo app is provided in the code snippet below:

The function in the above code snippet receives the country code and phone number from our app then sends a request by calling the nexmo verify API to send SMS and request_id back to the app in order to check OTP.

Now, we need to define another function to check the OTP code. Here, in this function, we will receive the country code, phone number, and verification_id and use Nexmo verify API to check the OTP.

If the verification is a success, we call Nexmo message API to send a welcome message to our app. The code for the function to check the OTP code is provided in the code snippet below:

app.put("/check_verify_code", (req, res) => { 
   // console.log(req.body); 
   let phone_number = req.body.callingCode + req.body.phoneNumber; 
   let verifyRequestId = req.body.verfication_id; 
   let code = req.body.code; 

   nexmo.verify.check( { request_id: verifyRequestId, code: code }, (err, result) => { 
      if (err) { 
        return res.status(500).json({ error: err }); 
      } else { 
        const message = { 
          content: { type: "text", text: "Welcome to Chat App" } 
        }; 
       nexmo.channel.send( 
                  { type: "sms", number: phone_number }, 
                  { type: "sms", number: "Chat App" }, 
                  message, 
                  (err, data) => { 
                     console.log(err); 
                   }, 
                  { 
                    useBasicAuth: true 
                  } 
       ); 
       return res.send(result); 
       } 
     } 
  ); 
});

Finally, we have successfully implemented the server to send OTP and verify the OTP code.

Creating React Native application

Now, we are going to create an app using React Native to implement the OTP verification process. The idea is to create a phone input to enter the phone number and then an OTP code verification check on the same screen. Here, we need to add logic to switch between the phone number form and OTP code verification form on the same screen. When the phone number is entered, the phone number input form should disappear and the OTP code entry form should appear. The boilerplate template to get started is already available in the GitHub for you.

So, let’s begin!!

Setting up React Native boilerplate template

Here, a ready to use boilerplate React Native app template is provided with a home and register screen already implement to help us get started easily with the app implementation part of this tutorial. To download this boilerplate into our local directory, we need Git to be installed into our system. Then, simply copy the following code and paste it into your command prompt with the desired location to download this GitHub repository into your local directory.

git clone https://github.com/krissnawat/nexmo\_tutorial

Now, we will have the react-native boilerplate template to help us get started with the app implementation. Now, navigate to project directory and run the command yarn or npm installto install all the required dependencies. Then, we need to run the following command to run the app project into our iOS simulator:

react-native run-ios

The screenshot below shows the project directory structure with all the components that are already provided in the app template project.

Now, we need to add a new component file named OTP.js in the component directory as shown in the screenshot below:

Creating Phone Input Form

In this step, we are going to create a phone number input form to receive the phone from the user. We are going to implement this form in the OTP.js file that we created earlier.

First of all, we need to import all the components necessary to implement this form from the react-native package. The required components to imported are provided in the code snippet below:

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from "react-native";

Next, we are going to define a color constant named brandColor into our OTP.js file as shown in the code snippet below:

const brandColor = "#103D5F";

Next, we need to create a class named PhoneInputwhich extends to Component module. Then, we need to create a view for the form with two main components TextInput for the input field and TouchableOpacity in order to make the clickable button to submit the phone number. The code for this is provided in the code snippet below:

export default class PhoneInput extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.header}>Phoene Input</Text>
        <View style={{ flexDirection: "row" }}>
          <TextInput
            ref={"textInput"}
            name="phoneNumber"
            type={"TextInput"}
            underlineColorAndroid={"transparent"}
            autoCapitalize={"none"}
            autoCorrect={false}
            placeholder={"Phone Number"}
            style={[styles.textInput]}
            returnKeyType="go"
            autoFocus
          />
        </View>
        <TouchableOpacity style={styles.button}>
          <Text style={styles.buttonText}>send OTP</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

Then, we need to add some styles to our components. The style codes are given implement using the Stylesheet component which is given below with all the required styles:

const styles = StyleSheet.create({ 
  container: { flex: 1, margin: 20 }, 
  header: { textAlign: "center", marginTop: 60, fontSize: 22, margin: 20, color: "#4A4A4A" }, 
  textInput: { padding: 0, margin: 0, flex: 1, fontSize: 20, color: brandColor }, 
  button: { 
   marginTop: 20, 
   height: 50, 
   backgroundColor: brandColor, 
   alignItems: "center", 
   justifyContent: "center",
   borderRadius: 5 
  }, 
  buttonText: { 
   color: "#fff", 
   fontFamily: "Helvetica", 
   fontSize: 16, 
   fontWeight: "bold"
  } 
});

Hence, we get the following result in our iOS emulator:

The Logic to Switch Form Style

Here, we are going to implement a logic to switch the form from phone number input to OTP input. The idea is to switch the form from phone input to OTP input after we send the phone number to receive the OTP code. Here, we are going to use the state to handle the switching of the forms when the user enters the phone number and submits it to receive the OTP code. The state variable used here is enterCode as shown in the code snippet below:

constructor(props) { 
  super(props); 
  this.state = { 
     enterCode: false 
  }; 
}```



Hence, we use `enterCode` state to decide whether to display phone input or OTP input.

Next, we use this `enterCode` state as a condition to toggle the form name and placeholder style as shown in the code snippet below:



```javascript
<View style={{ flexDirection: "row" }}> 
  <TextInput ref={"textInput"} 
             name={this.state.enterCode ? "code" : "phoneNumber"} 
             type={"TextInput"} underlineColorAndroid={"transparent"} 
             autoCapitalize={"none"} 
             autoCorrect={false} 
             placeholder={this.state.enterCode ? "_ _ _ _" : "Phone Number"} 
             style={[styles.textInput, textStyle]} 
             returnKeyType="go" 
             maxLength={this.state.enterCode ? 6 : 20} 
             autoFocus /> 
</View>

Now, in the render() method, we define the toggle variables based on enterCode state as shown in the code snippet below:

  • headerText to handle the toggling of the form title name.
  • buttonText variable to handle the toggling of the button text.
  • textStyle variable to handle the toggling of input style.

Then, we bind these toggle variables to the components as shown in the code snippet below:

render() { 
  let headerText = `What's your ${ this.state.enterCode ? "verification code" : "phone number" }?`; 
  let buttonText = this.state.enterCode ? "Verify confirmation code" : "Send confirmation code"; 
  let textStyle = this.state.enterCode ? { height: 50, textAlign: "center", fontSize: 40, fontWeight: "bold", fontFamily: "Courier" } : {};

Now, we need to create a function to handle the sending of phone number and receiving of OTP code. Here, we simply implement this function named getSubmitAction() to change the enterCode state in order to test the toggling of input forms as shown in the code snippet below:

_getSubmitAction = () => { 
    this.setState({
      enterCode: !this.state.enterCode
    }); 
};

Now, we need to bind the function to onpress event of the TouchableOpacity component so that whenever we press the button, the getSubmitAction()function is triggered to change the enterCode state as shown in the code snippet below:

<TouchableOpacity style={styles.button} onPress={this._getSubmitAction}>
          <Text style={styles.buttonText}>{buttonText}</Text>
</TouchableOpacity>

Hence, we will see the following result in our emulator:

As we can see in the emulator simulation above, we have successfully implemented the logic to switch the form from phone input to OTP input.

Implementing function to send OTP

In this step, we are going to implement a function to request the OTP verification code after we submit the phone number.

First, we need to install three packages which are frisbee , react-native-form , and react-native-loading-spinner-overlay. We can simply run the following command into our project directory to install all three packages:

yarn add frisbee react-native-form react-native-loading-spinner-overlay

Then, we need to import all these packages to our OTP.js file as shown in the code snippet below:

import Frisbee from "frisbee";
import Spinner from "react-native-loading-spinner-overlay";
import Form from "react-native-form";
  • Frisbee package: In order to perform the HTTP requests.
  • Spinner package: In order to display the loading indicator.
  • Form package: In order to get data from the form.

Implementing Frisbee Instance

Here, we are going to initialize the Frisbee instance to perform the HTTP request to our codesandbox server. The baseURI is set from the URL from the codesandbox server. The initialization of Frisbee instance with URL and header configuration is provided in the code snippet below:

const api = new Frisbee({
  baseURI: "https://qeo3m.sse.codesandbox.io",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  }
});

Then, we need to add more states i.e. spinner and country to handle to snipper and country code as shown in the code snippet below:

constructor(props) {
   super(props); 
   this.state = { 
      enterCode: false, 
      spinner: false, 
     country: { cca2: "TH", callingCode: "66"}
 }; 
}

Now, we need to get the form values i.e. either a phone or OTP code depending upon the enterCode state. To get the form values, we are going to use the Form package as shown in the code snippet below:

<Form ref={"form"} style={styles.form}>
  <View style={{ flexDirection: "row" }}> 
     <TextInput ref={"textInput"} 
                name={this.state.enterCode ? "code" : "phoneNumber"} 
                type={"TextInput"} underlineColorAndroid={"transparent"}
                autoCapitalize={"none"}
                autoCorrect={false} 
                placeholder={this.state.enterCode ? "_ _ _ _" : "Phone Number"} 
                style={[styles.textInput, textStyle]} 
                returnKeyType="go" 
                maxLength={this.state.enterCode ? 6 : 20}
                autoFocus /> 
    </View> 
    <TouchableOpacity style={styles.button} onPress= {this._getSubmitAction}> 
          <Text style={styles.buttonText}>{buttonText}</Text> 
    </TouchableOpacity> </Form> 
    <Spinner visible={this.state.spinner} textContent={"One moment..."} textStyle={{ color: "#fff" }} /> 
  </View>

Here, we use ref to define the form name which is used to get value from the input. Then, we are going to add the loading spinner.

Perform HTTP request

Now, since we can get the phone number input from the phone number input form, we perform the HTTP request to the server by implementing the getCode() function. The code to implement the function getCode to send the verification code request is provided in the code snippet below:

_getCode = () => {
this.setState({ spinner: true });
setTimeout(async () => {
      try {
        const res = await api.post("/send_verify_code", {
          body: {
            ...this.refs.form.getValues()
          }
        });
        if (res.err) throw res.err;
        this.setState({
          spinner: false,
          enterCode: true,
          verification: res.body
        });
        this.refs.form.refs.textInput.setNativeProps({ text: "" });
       setTimeout(() => {
          Alert.alert("Sent!", "We've sent you a verification code", [
            {
              text: "OK",
              onPress: () => this.refs.form.refs.textInput.focus()
            }
          ]);
        }, 100);
      } catch (err) {
        console.log(err);
        setTimeout(() => {
          Alert.alert("Oops!", err.message);
        }, 100);
      }
    }, 100);
  };

The code in the getCode function is defined below in line-wise fashion:

  • 2nd line: This line sets the spinner state to true in order to show the snipper when we send the OTP code request.
  • 4th line: Here, we set a timeout function in order to show the loading spinner for some period of time until the request ends.
  • 6–11th line: Here, we send the HTTP request to an endpoint that we created on the server
  • 14- 16th line: Here, we switch the form to the OTP form and hide spinner. Then, we set the verification_id that we received from the server to the state.
  • 19th line: Then, we clear the form while switching to the OTP check form.
  • 21–28th line: Here, we trigger an alert to display the status.
  • 29–36th line: Here, we handle the display alert, when the error is thrown.

Then, we trigger the getSubmitAction function which in turn triggers the getCode function as shown in the code snippet below:

_getSubmitAction = () => {
  this._getCode();
};

Hence, we get the following result in our emulator:

As we can see in the emulator simulation above, we have successfully sent the phone to receive the OTP verification code and trigger an alert.

Now, Before we implement the OTP code checking, we want to implement a country code picker to help users fill their country code.

Adding country picker

Here, we are going to add the country picker in our phone number input form so that users can pick their country code easily.

First, we are going to install the react-native-country-picker-modal package by simple using the command below in our project directory:

yarn add react-native-country-picker-modal

Then, we need to import the package to our app in OTP.js file as shown in the code snippet below:

import CountryPicker from "react-native-country-picker-modal";

Configuring function

Next, we are going to implement a function renderCountryPicker that returns the CountryPicker component shown in the code snippet below:

_renderCountryPicker = () => {
    if (this.state.enterCode) return <View />;
   return (
      <CountryPicker
        ref={"countryPicker"}
        closeable
        style={styles.countryPicker}
        onChange={this._changeCountry}
        cca2={this.state.country.cca2}
        styles={countryPickerCustomStyles}
        translation="eng"
      />
    );
  };

_renderCallingCode = () => {
    if (this.state.enterCode) return <View />;
    return (
      <View style={styles.callingCodeView}>
        <Text style={styles.callingCodeText}>
          +{this.state.country.callingCode}
        </Text>
      </View>
    );
  };

In the 6th line, we need to add ref initialized to “countryPicker” to create a mark which provides access to element like before.

Then in 8th line, we need to add the following styles to the element as shown in the code snippet above.

const styles = StyleSheet.create({
  countryPicker: { alignItems: "center", justifyContent: "center" },
   .......

Now, we are going to implement a function that handles the change of country named changeCountry() bound to onchange event of CountryPicker component; shown inline 8. When this changeCountry() function is triggered, the country state changes and there is a focus on our form component. The code for this function is provided in the code snippet below:

_changeCountry = country => { 
    this.setState({ country });
    this.refs.form.refs.textInput.focus(); 
};

Then, in line 10, we need to add cca2 code to state country .

Next, we need to implement a function called renderCallingCode() which is used to display calling code besides the form. Here, we are going to use enterCode state, in order to determine the showing and hiding of the OTP code check form.

Finally, we add the function renderCountryPicker() and renderCallinCode() inside the Form component as highlighted in the code snippet below:

return (
      <View style={styles.container}>
        <Text style={styles.header}>{headerText}</Text>
<Form ref={"form"} style={styles.form}>
          <View style={{ flexDirection: "row" }}>
{this._renderCountryPicker()}
{this._renderCallingCode()}

As a result, we get the country code picker on our phone number input form as shown in the emulator simulation below:

Fetching code from Server

Next, we need to attach calling code i.e. country state to the request body inside getCode() function as highlighted in the code snippet below:

_getCode = () => {
    this.setState({ spinner: true });
    setTimeout(async () => {
      try {
        const res = await api.post("/send_verify_code", {
          body: {
            ...this.refs.form.getValues(),
             ...this.state.country
          }
        });
        if (res.err) throw res.err;
........

Lastly, we need to add a text footer in order to explain the policy. Here, we are going to use enterCode state condition to toggle between the return text to display in the footer inside the renderFooter() function as shown in the code snippet below:

_renderFooter = () => {
    if (this.state.enterCode)
      return (
        <View>
          <Text style={styles.wrongNumberText} onPress={this._tryAgain}>
            Enter the wrong number or need a new code?
          </Text>
        </View>
      );
     return (
      <View>
        <Text style={styles.disclaimerText}>
          By tapping "Send confirmation code" above, we will send you an SMS to
          confirm your phone number. Message &amp; data rates may apply.
        </Text>
      </View>
    );
  };

Then, we need to add the renderFooter() function to main input form as shown in the code snippet below:

<TouchableOpacity
    style={styles.button}
    onPress={this._getSubmitAction}
  >
    <Text style={styles.buttonText}>{buttonText}</Text>
  </TouchableOpacity>
  {this._renderFooter()}
</Form>

As a result, we can see the beautiful form with the country code selection and the phone number input in the screenshot below:

Implementing a Function to verify the OTP code

In this step, we are going to implement a function to check the OTP verification code.

Here, we are going to create a verifyCode() function which is to be triggered when we execute the verify code button. The overall code to implement the verifyCode() function is provided in the code snippet below:

_verifyCode = () => {
    this.setState({ spinner: true });
    setTimeout(async () => {
      try {
        const res = await api.put("check_verify_code", {
          body: {
            verfication_id: this.state.verification,
            ...this.refs.form.getValues(),
            ...this.state.country
          }
        });
       if (res.err) throw res.err;
        this.refs.form.refs.textInput.blur();
        this.setState({ spinner: false });
        setTimeout(() => {
          Alert.alert(
            "Success!",
            "You have successfully verified your phone number"
          );
          return this.props.navigation.navigate("MainChat", {
            username: this.props.navigation.getParam("username")
          });
        }, 100);
      } catch (err) {
        this.setState({ spinner: false });
        setTimeout(() => {
          Alert.alert("Oops!", err.message);
        }, 100);
      }
    }, 100);
  };

The explanation of the most important code sections in the above code snippet is provided below:

  • In 8th line, we have added the verification_id that equals to the username in the server.
  • In the 24th line, after the successful verification of the received OTP code, we are redirecting the user to the Main app screen.

Then, in order to call the verifyCode() function we come back to getSubmitAction() function that we defined earlier. And by using enterCode state as a condition, we add a toggle between two functions as shown in the code snippet below:

_getSubmitAction= () => {
  this.state.enterCode ? this._verifyCode() : this._getCode();
};

As a result, we get the following result in our emulator:

As we can see in the emulator simulation above, we have implemented the sending of a phone number to receive the OTP verification code from the server and then, verify the OTP verification code successfully. This completes our implementation of the OTP verification process using Nexmo app API, message API and Codesandbox server in React Native app successfully.

Conclusion

Well, this has been a heck of a long tutorial. In this tutorial, we got to learn many important features used during OTP verification. Here, we learned how to use Nexmo verify API and message API in the NodeJS server while using React native as frontend. We got step by step guide on how to create a Nexmo app and how to use the configuration from Nexmo app into our codesandbox Node server. Then, we also got guidance on how to create an HTTP request in React Native to request the Node server and also handle the response. We also learned how to add a country code picker to pick the country code while sending the phone number to the server to request for OTP code. Finally, we successfully implemented an OTP verification process.

The post How to use Nexmo verify API and Message API in React native appeared first on Kriss.

Disclosure

This post includes affiliate links; I may receive compensation if you purchase
products or services from different links provided in this article.

Top comments (0)