Checkout the latest Books by Login via Mobile Number feature using HMS Account Kit in Books App (React Native)
Tags: huawei, reactnative, javascript, hmsaccountkit
Published: 2022-04-13 12:21:40

## **Introduction**
In this article, I will be integrating Huawei Account Kit in an Application. Account Kit provides you with simple, secure and quick sign-in and authorization functions. By integrating the Auth Service SDK into our app, we can easily and quickly provide functions such as registration and sign-in for our users. We can choose to provide our users with one or more of the authentication modes like Mobile number, Email address, Facebook, WeChat etc. We will integrate the mobile number authentication mode into the app, so that our users can use mobile numbers and passwords or verification codes to sign in to the app securely.

## **React Native**
React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.
Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.
React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.
It uses the same fundamental UI building blocks as regular iOS and Android apps.

## **Requirements**
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.

## **Integrate HMS Dependencies**

- 
 First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a [Huawei ID](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148).

- 
 Create a project in android studio, refer Creating an Android Studio Project.

- 
 Generate a SHA-256 certificate fingerprint.

- 
 To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > [SHA256 code](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#3).
Or use cmd as explained in SHA256 CODE

- 
 [Create an App in AppGallery Connect.
](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0)
- 
 Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.

 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3d0ccebars0nhltnyka5.png)
 

- 
 Enter SHA-256 certificate fingerprint and click Save, as follows.

 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v15j3aqzp0anewgembwl.png)
 

- 
 Click Manage APIs tab and enable Account Kit.

 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t03qak7ho1ed5i10ceky.png)
 

**React Native Project Preparation**

- 
 Environment set up, refer below link.
     https://reactnative.dev/docs/environment-setup


- 
 Create project using below command.
`react-native init project name`

- 
 Download the React Native [Account Kit SDK](https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Library-V1/react-native-plugin-0000001050770211-V1) and paste it under Node Modules directory of React Native project. If you cannot find node modules run below command under project directory using CLI.
`“npm install” & “npm link”`
 

- 
 Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
`maven {url 'http://developer.huawei.com/repo/'} `

- 
   Configure app level build.gradle. (Add to dependencies)
`Implementation project (“:react-native-hms-account”)`


- 
   Linking the HMS Account Kit Sdk.
Run below command in the project directory
`react-native link react-native-hms-account`

- 
 Add below permissions to Android.manifest file.

```
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```
  

- 
 Enabling Auth Service
(i). Sign in to AppGallery Connect and click My projects.
(ii). Click a project that you want to enable Auth Service from the project list.
(iii). Choose Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/crfgly8az236jp5h5vhh.png)
 
(iv). Click Enable in the row of each authentication mode to be enabled.
 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cl9hocvaiw9vaav3robd.png)
 
For more details visit this [documentation.](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-auth-android-getstarted-0000001053053922#section916641174412)


## **Development**

**•	Registering an Account**

- 
	Apply for a verification code for mobile number-based registration. The verification code will be sent to the user's mobile number to ensure that the mobile number belongs to this user. Call PhoneAuthProvider.requestVerifyCode to apply for a registration verification code.

```
let settings = new VerifyCodeSettings(
              VerifyCodeAction.REGISTER_OR_LOGIN,
              "zh_CN",
              30
            );
            PhoneAuthProvider.requestVerifyCode("countryCode", "phoneNumber", settings)
              .then((verifyCodeResult) => {
                // verifyCodeResult.shortestInterval
                // verifyCodeResult.validityPeriod
              })
              .catch((error) => {
                // error
              });
```

- 
	Register a user using a mobile number.
Call AGCAuth.createPhoneUser to register a user. After the registration is successful, the user signs in automatically, and you do not need to call the sign-in API again. The password is optional, and the user can sign in using a verification code.

```
AGCAuth.getInstance()
  .createPhoneUser(
    "countryCode",
    "phoneNumber",
    "password if you want",
    "verifyCode"
  )
  .then((signInResult) => {
    // signInResult.user
  })
  .catch((error) => {
    // error
  });
```

- 
	After successful sign-in, call AGCAuth.currentUser to obtain user account data.
 

```
AGCAuth.getInstance()
  .currentUser()
  .then((user) => {
    if (user) {
      // A user signed in
    }
  });
```


**•	Signing In with a Password**

- 
	On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.

```
AGCAuth.getInstance()
  .currentUser()
  .then((user) => {
    if (user) {
      // A user signed in
    }
  });
```

- 
	Call AGCAuth.signIn for sign-in.

```
let credential = PhoneAuthProvider.credentialWithPassword(
    "countryCode",
    "phoneNumber",
    "password"
  );
  AGCAuth.getInstance()
    .signIn(credential)
    .then((signInResult) => {
      if (signInResult && signInResult.user) {
        // signInResult.user get user info
      }
    })
    .catch((error) => {
      // error
    });

```
- 
	After successful sign-in, call AGCAuth.currentUser to obtain user account data.

**•	Signing In with a Verification Code**

- 
	On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.

```
AGCAuth.getInstance()
       .currentUser()
       .then((user) => {
          if (user) {
            // A user signed in
          }
        });
```

- 
	Call PhoneAuthProvider.requestVerifyCode to apply for a verification code.

```
let settings = new VerifyCodeSettings(
      VerifyCodeAction.REGISTER_OR_LOGIN,
      "zh_CN",
      30
    );
    PhoneAuthProvider.requestVerifyCode("countryCode", "phoneNumber", settings)
      .then((verifyCodeResult) => {
        // verifyCodeResult.shortestInterval
        // verifyCodeResult.validityPeriod
      })
      .catch((error) => {
        // error
      });
```




- 
	Call AGCAuth.signIn for sign-in.

 

```
let credential = PhoneAuthProvider.credentialWithVerifyCode(
        "countryCode",
        "phoneNumber",
        null,
        "verificationCode"
      );
      AGCAuth.getInstance()
        .signIn(credential)
        .then((signInResult) => {
          if (signInResult && signInResult.user) {
            // signInResult.user get user info
          }
        })
        .catch((error) => {
          // error
        });

```
- 
	After successful sign-in, call AGCAuth.currentUser to obtain user account data.

Testing
Run the android App using the below command.
`react-native run-android`












## **Result**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ir2xiwkeas40w3qnpj4.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a55ejyp2elac2lyrrdc8.png)
 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2j7fgg7s6mbz5cckw2e0.png)
 
   








## **Conclusion**
In this article, we have learnt that how to integrate the mobile number authentication mode into the app, so that our users can use mobile numbers and passwords or verification codes to sign in to the app securely.

## **Reference**
Account Kit: [Documentation](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-auth-reactnative-usage-0000001072110443#section1965310529147)
Account Kit: [Training Video](https://developer.huawei.com/consumer/en/training/course/video/101583005582480166)