{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Huawei Account Kit in an Application.
Account Kit
Account Kit: Account Kit provides you with simple, secure and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their HUAWEI IDs.
React Native
REACT Native helps you 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
Any operating system (MacOS, Linux and Windows).
Must have a Huawei phone with HMS 4.0.2.300 or later.
Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Minimum API Level 21 is required.
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.
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 or use cmd as explained in SHA256 CODE
Create an App in AppGallery Connect.
Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
Enter SHA-256 certificate fingerprint and click Save, as follows.
Click Manage APIs tab and enable Account Kit.
React Native Project Preparation
Environment set up, refer below link.
Setting up the development environment · React Native
This page will help you install and build your first React Native app.
reactnative.dev
Create project using below command.
Code:
react-native init project name
Download the React Native Account Kit SDK 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.
Code:
“npm install” & “npm link”
Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“:react-native-hms-account”)
Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
Add below permissions to Android.manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development
Account Kit provides APIs for normal sign-in, silent sign-in, sign-out, and authorization revoking. Create a UI in your Android Studio project. An example is shown in the following figure.
1. signIn()
Sign In securely to the application using Huawei ID.
JavaScript:
import HMSAccount, {
HMSAuthParamConstants,
HMSAuthRequestOptionConstants,
} from "react-native-hms-account";
let signInData = {
huaweiIdAuthParams: HMSAuthParamConstants.DEFAULT_AUTH_REQUEST_PARAM,
authRequestOption: [
HMSAuthRequestOptionConstants.ID_TOKEN,
HMSAuthRequestOptionConstants.EMAIL,
],
};
HMSAccount.signIn(signInData)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
2. signOut()
Signing out securely using the signOut() method.
JavaScript:
HMSAccount.signOut()
.then(() => {
console.log("signOut -> Success")
})
.catch((err) => {
console.log(err)
});
3. silentSignIn()
With silent sign-in, users can sign in without using their credentials for consecutive sign-ins
JavaScript:
import HMSAccount, { HMSAuthParamConstants } from "react-native-hms-account";
let silentSignInData = {
huaweiIdAuthParams: HMSAuthParamConstants.DEFAULT_AUTH_REQUEST_PARAM,
};
HMSAccount.silentSignIn(silentSignInData)
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
});
4. cancelAuthorization()
Revoking authorization is intended to increase security by forcing the users to use sign-in credentials while signing in.
JavaScript:
HMSAccount.cancelAuthorization()
.then(() => {
console.log("cancelAuthorization -> Success")
})
.catch((err) => {
console.log(err)
});
5. HMSReadSMSManager
Read SMS manager is a service that listens to verification code SMS events.
JavaScript:
import { HMSReadSMSManager } from "react-native-hms-account";
HMSReadSMSManager.smsVerificationCode()
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
});
Testing
Run the android App using the below command.
Code:
react-native run-android
Result
Conclusion
In this article, we have learnt that how to integrate HMS Account Kit using React Native. HMS Toolkit helps us to Connects users from a wide range of devices, including phones, tablets, and smart displays. It serves over 900 million users from 190+ countries and regions worldwide and supports 70+ Languages. It guarantees two-factor authentication, real-time risk prediction, and GDPR compliance.
Reference
Account Kit: Documentation
Account Kit: Training Video
Related
More information like this, you can visit HUAWEI Developer Forum
HUAWEI Account Kit offers very simple, quick and secure sign in and authorization functionalities which help many developers to implement hassle free and quick sign in functionalities for their applications.
HUAWEI Account Kit offers services on different parameters as
Quick and Standard
Massive user base and global services
Secure, reliable, and compliant with international standards
Quick sign-in to apps
Development Overview
Prerequisite
1. Must have a Huawei Developer Account
2. Must have a Huawei phone with HMS 4.0.0.300 or later
3. React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
1. React Native CLI : 2.0.1
2. Gradle Version: 6.0.1
3. Gradle Plugin Version: 3.5.2
4. React Native Account Kit SDK : 5.0.0.300
5. React-native-hms-account kit gradle dependency
6. AGCP gradle dependency
7. Enable Auth Services
Preparation
1. Create an app or project in the Huawei app gallery connect.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Describes the Step 1.0
Describes the Step 1.1
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
Describes the Step 2.0
Describes the Step 2.1
Describes the Step 2.2
Describes the Step 2.3: Enable Account Kit Api on Manage Api page
Describes the Step 2.4: Put SHA signature generated using Android Studio
Describes the Step 2.5: Download agc services file and paste it under App folder of the project.
3. Create a react native project, use the below command
Code:
“react-native init project name”
4. Download the React Native Account Kit SDK and paste it under Node Modules directory of React Native project.
5. Enable Auth services
Describes the Step 5.1: Redirect to Auth Services and enable the required authorization service.
Describes the Step 5.2: copy the App ID and App Secret from “My Apps “ page and paste them here.
Tips
1. agconnect-services.json is not required for integrating the hms-ads-sdk.
2. Run below command under project directory using CLI if you cannot find node modules.
Code:
“npm install” & “npm link”
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“: react-native-hms-ads”)
3. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
Development Process
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
Import the SDK
Sign In
Sign Out
Testing
Import the SDK
Add below line of code in the app.js file
Code:
import RNHMSAccount from "react-native-hms-account";
Sign In
To sign in, create a signInData object and set the field values. Then invoke the signIn method of the HMSAccount module, setting the signInData object as the argument. If the sign in is successful, an AuthHuaweiId object will be returned, an exception object is returned otherwise.
Add below code on the “SIGN IN” button click
Code:
const onSignIn = () => {
let signInData = {
huaweiIdAuthParams:
RNHMSAccount.HmsAccount
.CONSTANT_HUAWEI_ID_AUTH_PARAMS_DEFAULT_AUTH_REQUEST_PARAM,
scopes: [RNHMSAccount.HmsAccount.SCOPE_ID_TOKEN],
};
RNHMSAccount.HmsAccount.signIn(signInData)
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
Sign Out
To sign out, invoke the signOut method of the HMSAccount module. The promise is resolved if the sign in is successful, is rejected otherwise.
Add below code on the “SIGN OUT” button click.
Code:
const onSignOut = () => {
RNHMSAccount.HmsAccount.signOut()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
Testing
Run the below command to build the project
Code:
React-native run-android
Upon successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
References
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050725712
Conclusion
Adding SignIn and SignOut functionalities seems easy.
thanks. very helpful.
Useful sharing, thanks!!
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201346110142010150&fid=0101187876626530001
HUAWEI Account Kit offers very simple, quick and secure sign in and authorization functionalities which help developers to implement hassle free and quick sign in functionalities for applications.
HUAWEI Account Kit offers services on different parameters as
Quick and Standard
Massive user base and global services
Secure, reliable, and compliant with international standards
Quick sign-in to apps
Development Overview
Prerequisite
1. Must have a Huawei Developer Account
2. Must have a Huawei phone with HMS 4.0.0.300 or later
3. React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
1. React Native CLI : 2.0.1
2. Gradle Version: 6.0.1
3. Gradle Plugin Version: 3.5.2
4. React Native Account Kit SDK : 5.0.0.300
5. React-native-hms-account kit gradle dependency
6. AGCP gradle dependency
Preparation
1. Create an app or project in the Huawei app gallery connect, click My apps, as shown below.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
1.0 Click on New app.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
2.0 Add the below information to create a new app and project
2.1 Once app is created, navigate to My projects
2.2 Click on the created project, as shown below.
2.3 Enable the AccountKit API
2.4 Put SHA signature generated using Android Studio
2.5 Download agconnect-services.json services file and paste it under App folder of the project.
3. Create a react native project, use the below command
Code:
“react-native init project name”
4. Download the React Native Account Kit SDK and paste it under Node Modules directory of React Native project.
Tips
1. Run below command under project directory using CLI if you cannot find node modules.
Code:
“npm install” & “npm link”
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“:react-native-hms-account”)
3. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
Adding permissions
Add below permissions to Android.manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development Process
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
Import the SDK
Silent Sign In
On Cancel Authorization
On Adding Authorization Scopes
Retrieve SMS Verification Code
Testing
Import the SDK
Add below line of code in the app.js file
Code:
import RNHMSAccount from "react-native-hms-account";
Silent Sign In
With silent sign in, the users can sign in without using their login credientials for consecutive sign-ins. To silent sign in, invoke the silentSignIn method of the HMSAccount module. The promise is resolved if the silent sign in is successful, is rejected otherwise.
Add below code on the “SILENT SIGN IN” button click
Code:
const onSilentSignIn = () => {
RNHMSAccount.HmsAccount.silentSignIn()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
On Cancel Authorization
Cancelling authorization is intended to increase security by forcing the users to use login credentials while signing in. To cancel authorization, invoke the cancel Authorization method of the HMSAccount module. The promise is resolved if the silent sign in is successful, is rejected otherwise.
Add below code on the “ONCANCELAUTHORIZATION” button click.
Code:
const onCancelAuthorization = () => {
RNHMSAccount.HmsAccount.cancelAuthorization()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
On Adding Authorization Scopes
Auth Manager class is responsible for creating the authorization scopes to build the data.
Add below code on the “ONADDAUTHSCOPES” button click.
Code:
const onAddAuthScopes = () => {
let buildData = {
requestCode: 888,
scopes: [RNHMSAccount.HmsAccount.SCOPE_ID_TOKEN],
};
RNHMSAccount.HuaweiIdAuthManager.addAuthScopes(buildData)
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
Retrieve SMS Verification Code
Read SMS manager is a service to listen verification code SMS events. To start read SMS manager, invoke the startReadSMSManager method of the module.
Code:
const onStartReadSMSManager = () => {
RNHMSAccount.SMSManager.startReadSMSManager()
.then((response) => {
logger(JSON.stringify(response));
})
.catch((err) => {
logger(err);
});
};
Testing
Run the below command to build the project
Code:
React-native run-android.
After successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
References
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050725712
Conclusion
Adding Account kit functions seem easy.
In this article, I am going to create a Flutter project –actually a tiny game- and explain how to implement Analytics Kit. But first, let me inform you about Huawei Analytics Kit a little.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Huawei Analytics Kit
Huawei Analytics Kit offers you a range of analytics models that help you not only to analyze users’ behavior with preset and custom events, but also gain an insight into your products and contents. So that you can improve your skills about marketing your apps and optimizing your products.
HUAWEI Analytics Kit identifies users and collects statistics on users by anonymous application identifier (AAID). The AAID is reset in the following scenarios:
1) Uninstall or reinstall the app.
2) The user clears the app data.
After the AAID is reset, the user will be counted as a new user.
HUAWEI Analytics Kit supports event management. For each event, maximum 25 parameters; for each app maximum 100 parameters can be defined.
There are 3 types of events: Automatically collected, predefined and custom.
Automatically collected events are collected from the moment you enable the kit in your code. Event IDs are already reserved by HUAWEI Analytics Kit and cannot be reused.
Predefined events include their own Event IDs which are predefined by the HMS Core Analytics SDK based on common application scenarios. The ID of a custom event cannot be the same as a predefined event’s ID. If so, you will create a predefined event instead of a custom event.
Custom events are the events that you can create for your own requirements.
More info about the kit and events.
Configuration in AppGallery Connect
Firstly, you will need a Huawei developer account. If you don’t have one, click here and register. It will be activated in 1–2 days.
After signing in to AppGallery Connect, you can add a new project or select an existing project. In the project you choose, add an app. While adding app, make sure you enter the package name right. It should be the same as your Flutter project’s package name.
Also, make sure you set data storage location, enable Analytics kit and add SHA-256 fingerprint to AppGallery Connect.
How to generate SHA-256 Fingerprint?
In Android Studio, right click on android folder under your project and select Flutter > Open Android module in Android Studio.
On the right panel, select Gradle and follow the steps that are shown in the picture below. Open signingReport and there is your SHA-256 fingerprint.
Copy the code and paste it on the project settings in the AppGallery Connect.
Integrate HMS to your project
Download agconnect-services.json file and place it under project_name > android > app.
Add Signing Configuration
Create a file named key.properties under android folder and add your signing configs here.
Code:
storeFile file(‘<keystore_file>.jks’)
storePassword ‘<keystore_password>’
keyAlias ‘<key_alias>’
keyPassword ‘<key_password>’
Define your key.properties file by adding the code below, before android block in your app-level build.gradle file.
Code:
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file(‘key.properties’)
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
TO-DOs in project-level build.gradle
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'} //add this line
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath 'com.huawei.agconnect:agcp:1.1.1.300' //add this line
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'} //add this line
}
}
TO-DOs in app-level build.gradle
Code:
defaultConfig {
...
minSdkVersion 19 //Increase this to 19
}
//Add these lines
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
//Edit buildTypes
buildTypes {
debug {
signingConfig signingConfigs.release
}
release {
signingConfig signingConfigs.release
}
}
//Add dependencies
dependencies {
implementation 'com.huawei.agconnect:agconnect-core:1.0.0.300'
implementation 'com.huawei.hms:hianalytics:5.0.1.300'
}
apply plugin: 'com.huawei.agconnect' //Add this line to the bottom of the page
Add Analytics Kit to your project
There are 2 ways to do this step.
1) Go to developer website and download plugin. In Android Studio create a new folder in your root directory and name it “hms”. Unzip the plugin and paste it in “hms” folder.
Then, go to pubspec.yaml and add the plugin under dependencies.
2) This way is much easier and also more familiar to Flutter developers. In pub.dev copy the plugin and add it under dependencies as usual.
For both ways, after running pub get command, the plugin is ready to use!
For more information about HMS Core integration, click.
We are all done. Let’s begin coding.
I will make a tiny and very easy game that I belive most of you know the concept: Guess the number!
As you play the game and try to guess the number, Huawei Analytics Kit will collect statistics how many times you guessed.
In this article, we’ll be looking at some of the APIs that Account Kit provides and learn how to use them in our Flutter projects.
Huawei Account Kit
Account Kit provides a simple and quick authorization experience to users. It enables to save time from long authorization periods and it’s two factor authentication process keeps users information safe. Account Kit allows you to connect to the Huawei ecosystem using your Huawei Id from a range of devices, such as mobile phones and tablets. Users can quickly and conveniently sign in to apps with their Huawei Ids after granting an initial access permission.
Configuring the project
Registering as a Developer
As first, you need to create a Huawei developer account and complete the identity verification. For details, please refer to Registering a Huawei Id.
Creating an APP
Sign in AppGallery Connect and create a new project.
Add a new app to your project by clicking the Add App button.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Generating a Signing Certificate Fingerprinter
Signing certificate fingerprints are used to verify the authenticity of an App when it attempts to access an HMS Core service through the HMS Core SDK. So before using the HMS Core service, you must generate a signing certificate fingerprint and configure it in AppGallery Connect.
Generate a Signing Certificate by referring here.
Then you’ll need to export the SHA256 Fingerprint by using keytool provided by JDK. You can find detailed steps here.
Adding Fingerprint Certificate to AppGallery Connect
On the application information page of the project, click to add your SHA256 fingerprint. Then click ✓ to save fingerprint.
Enabling Account Kit Service
On the application information page, click Manage APIs and make sure Account Kit is enabled.
Integrating HMS and Account Plugin to Flutter Project
Open pubspec.yaml file of your project and add Huawei Account Plugin as a dependency.
Code:
dependencies:
flutter:
sdk: flutter
huawei_account: ^5.0.0+300
Download agconnect-services.json file from application information page.
Move the file to the android/app directory with the signing certificate file you’ve created.
Open the android/build.gradle file and configure the Maven repository address and agconnect plugin for the HMS Core SDK.
Code:
buildscript {
repositories {
// Other repositories
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
// Other dependencies
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
// Other repositories
maven { url 'https://developer.huawei.com/repo/' }
}
}
Add the AppGallery Connect plugin to your app level build.gradle file.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
Then add the signing configurations in the same file. Don’t forget that your applicationId must be same as the one you created in AppGallery Connect. Also change your minSdkVersion to 19.
Code:
android {
defaultConfig {
applicationId "<application_id>"
minSdkVersion 19
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
signingConfigs {
config {
storeFile file('<keystore_file>')
storePassword '<keystore_password>'
keyAlias '<key_alias>'
keyPassword '<key_password>'
}
}
buildTypes {
debug {
signingConfig signingConfigs.config
}
release {
signingConfig signingConfigs.config
}
}
}
Now we’re done with the integration part and ready to use the Account Plugin in our application.
Using Huawei Account Kit Flutter Plugin
Setting Up The Authorization
Account Plugin allows you to customize the authorization. You can request users to authorize their email addresses, profile information or access tokens. To accomplish that, you can use AuthParamHelper class.
Create an instance of AuthParamHelper class. Then set the parameters you want to customize.
Code:
AuthParamHelper helper = new AuthParamHelper();
// You can set many options by using cascades
helper..setEmail()..setRequestCode(8888);
Signing In
Now we’re going to call signIn method through HmsAccount class and pass our helper instance to it. In return, this method gives us the Huawei Id information through AuthHuaweiId class.
Code:
try {
// Make sure you handle the possible exceptions.
final AuthHuaweiId authHuaweiId = await HmsAccount.signIn(helper);
} on Exception catch (e) {
print(e.toString());
}
As this method is triggered, an authorization screen shows up. After clicking the login button, you can see the Huawei Id information is received.
Account Plugin has signOut method which clears the user’s Huawei Id information when it comes to sign out from an app. But the information is not permanently deleted.
Code:
try {
// Make sure you handle possible exceptions.
final bool result = await HmsAccount.signOut();
} on Exception catch (e) {
print(e.toString());
}
Revoking Authorization
After signing in for the first time, when users try to sign in again, the authorization screen will not show up unless users revoke it. Huawei Id information will be received directly. Once the authorization is revoked, logged id information will be deleted. And the authorization screen will be shown on another login attempt.
Code:
try {
// Make sure you handle possible exceptions.
final bool result = await HmsAccount.revokeAuthorization();
} on Exception catch (e) {
print(e.toString());
}
Sms Verification
One of the options that Account Plugin provides us is the sms verification. This service can catch sms messages in certain formats. Unlike the other authorization methods, you should be able to send sms messages for this special service.
Obtaining Application’s Hash Code
To catch upcoming sms messages, we need to know the hash code value which is unique in each app. Account Plugin provides obtainHashcode method to get that.
Code:
try {
// Make sure you handle possible exceptions.
final String hashcode = await HmsAccount.obtainHashCode();
} on Exception catch (e) {
print(e.toString());
}
Sending Sms Messages
The messages you’ll send should be as follows:
Code:
prefix_flag short message verification code is ****** hash_code
prefix_flag indicates the prefix of an SMS message, which can be <#>, [#], or \u200b\u200b. \u200b\u200b are invisible Unicode characters.
short message verification code is indicates the content of an SMS message, which is user-defined.
****** indicates the verification code.
Receiving Sms Messages
Account Plugin comes with smsVerification method to listen and catch the right formatted messages. Once it is called, the app starts listening. Waits for the messages for five minutes before timing out. Returns the message or error code depending on the situation.
Code:
HmsAccount.smsVerification(({errorCode, message}){
if (message != null) {
// Use the message
} else {
print("Error: $errorCode");
}
});
It’s all done. Now you’re ready to use Account Plugin in your Flutter applications.
Conclusion
Huawei Account Kit is such an easy and secure way to carry out authorization processes, along many other kits with powerful solutions. I think these services will keep providing a nice experience for both developers and users as they get bigger and better.
You can check some other articles about Hms Core Plugins below, and feel free to ask any question about this article in the comments.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will be integrating Huawei Account Kit in a Travel application. Account Kit provides you with simple, secure and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their HUAWEI IDs.
React Native
REACT Native helps you 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
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Account Kit.
React Native Project Preparation
9. Environment set up, refer below link.
Setting up the development environment · React Native
This page will help you install and build your first React Native app.
reactnative.dev
10. Create project using below command.
Code:
react-native init project name
11. Download the React Native Account Kit SDK 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.
Code:
“npm install” & “npm link”
12. Configure android level build.gradle
Code:
Add to buildscript/repositories and allprojects/repositories
maven {url 'http://developer.huawei.com/repo/'}
13. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“:react-native-hms-account”)
14. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
15. Add below permissions to Android.manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development
Sign in and sign out (Without Auth Button)
signIn()
Sign In securely to the application using Huawei ID.
JavaScript:
import HMSAccount, {
HMSAuthParamConstants,
HMSAuthRequestOptionConstants,
} from "react-native-hms-account";
let signInData = {
huaweiIdAuthParams: HMSAuthParamConstants.DEFAULT_AUTH_REQUEST_PARAM,
authRequestOption: [
HMSAuthRequestOptionConstants.ID_TOKEN,
HMSAuthRequestOptionConstants.EMAIL,
],
};
HMSAccount.signIn(signInData)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
Sign Out
JavaScript:
HMSAccount.signOut()
.then(() => {
console.log("signOut -> Success")
})
.catch((err) => {
console.log(err)
});
Sign in using HMSAuthButton
JavaScript:
import HMSAccount, { HMSAccountAuthService, HMSAuthParamConstants, HMSAuthScopeListConstants, HMSAuthRequestOptionConstants } from "@hmscore/react-native-hms-account";
signIn = () => {
let signInData = {
accountAuthParams: HMSAuthParamConstants.DEFAULT_AUTH_REQUEST_PARAM,
authRequestOption: [HMSAuthRequestOptionConstants.ID_TOKEN, HMSAuthRequestOptionConstants.ACCESS_TOKEN],
authScopeList: [HMSAuthScopeListConstants.EMAIL]
};
HMSAccountAuthService.signIn(signInData)
.then((response) => { console.log(response) })
.catch((err) => { console.log(err) });
};
...
<HMSAuthButton
style={styles.viewcontainer}
colorPolicy={
HMSAccount.HUAWEI_ID_AUTH_BUTTON_COLOR_POLICY_RED
}
enabled={true}
theme={HMSAccount.HUAWEI_ID_AUTH_BUTTON_THEME_FULL_TITLE}
cornerRadius={
HMSAccount.HUAWEI_ID_AUTH_BUTTON_CORNER_RADIUS_MEDIUM
}
onPress={signIn}
/>
Testing
Run the android App using the below command.
react-native run-android
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. Make sure you have added the agconnect-services.json file to app folder.
3. Make sure you have added SHA-256 fingerprint without fail.
4. Make sure all the dependencies are added properly.
5. For project cleaning navigate to android directory and run the below command.
gradlew clean
Conclusion
In this article, we have learnt that how to integrate HMS Account Kit using React Native. HMS Toolkit helps us to Connects users from a wide range of devices, including phones, tablets, and smart displays. It serves over 900 million users from 190+ countries and regions worldwide and supports 70+ Languages. It guarantees two-factor authentication, real-time risk prediction, and GDPR compliance.
Reference
Account Kit: Documentation
Account Kit: Training Video