Send messages in App! Integrate Huawei In App Messaging services using React Native - Huawei Developers

{
"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 learn how to implement In App Messaging service provided by Huawei. App Messaging of AppGallery Connect to send relevant messages to target users actively using your app to encourage them to use key app functions, or send attractive promotion activities to enhance user loyalty.
Requirements
1. JDK version: 1.7 or later
2. Android Studio version: 3.X or later
3. minSdkVersion: 21 or later
4. targetSdkVersion: 31 (recommended)
5. compileSdkVersion: 29 (recommended)
6. Gradle: 4.1 or later (recommended)
7. Must have a Huawei Developer Account.
8. Must have a Huawei phone with HMS 4.0.0.300 or later and running EMUI 4.0 or later.
9. React Native environment with Android Studio, Node Js and Visual Studio code.
Preparation
1. Create an app or project in the Huawei App Gallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the App Messaging API.
3. Download the agconnect-services.json file.
4. Create an Android project.
Integration process
Create a react native project using below command:
Code:
react-native init Project Name
Add below to build.gradle (project) file under buildscript/repositories and allprojects/repositories.
Code:
Maven {url 'http://developer.huawei.com/repo/'}
Add below to build.gradle(app) file, under dependencies to use the App Messaging Sdk.
dependencies{
// Import the App Messaging SDK.
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.5.1.300'
Note>> to use the Analytics, please add Analytics SDK
Code:
implementation 'com.huawei.hms:hianalytics:5.2.0.300'
}
Add below permissions to manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE"/>
Open the build.gradle file in the android directory of your React Native project, and change the value of minSdkVersion in buildscript to 19.
Development Process
To make your app's orientation work by default, orientation keywords should be removed from android:configChanges property of the activity tag in AndroidManifest.xml file.
An example of your AndroidManifest.xml is as follows:
Code:
<!-- AndroidManifest.xml. -->
<activity
android:name="com.huawei.agc.rn.appmessaging.example.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Import the following into APP.js file.
Code:
import AGCAppMessaging from '@react-native agconnect/appmessaging';
import {Alert} from 'react-native';
The React Native App Messaging plugin allows you to enable or disable data synchronization from the AppGallery Connect server. The function is enabled by default. The AGCAppMessaging.setFetchMessageEnable API can be called to enable or disable data synchronization from the AppGallery Connect server.
Code:
import AGCAppMessaging from '@react-native-agconnect/appmessaging';
import {Alert} from 'react-native';
AGCAppMessaging.setFetchMessageEnable(true).then(result => {
Alert.alert("[setFetchMessageEnable] " + JSON.stringify(result));
}).catch((err) => {
Alert.alert("[setFetchMessageEnable] Error/Exception: " + JSON.stringify(err));
});
The AGCAppMessaging.setDisplayEnable API can be called to set whether to enable message display.
Code:
import AGCAppMessaging from '@react-native-agconnect/appmessaging';
import {Alert} from 'react-native';
AGCAppMessaging.setDisplayEnable(false).then(result => {
Alert.alert("[setDisplayEnable] " + JSON.stringify(result));
}).catch((err) => {
Alert.alert("[setDisplayEnable] Error/Exception: " + JSON.stringify(err));
});
Add a listener to obtain app message events.
Code:
const eventEmitter = new NativeEventEmitter(AGCAppMessaging);
this.eventListener = eventEmitter.addListener(AGCAppMessaging.EventTypes.ON_MESSAGE_DISPLAY,
(event) => {
Alert.alert("[onMessageDisplay] " + JSON.stringify(event));
console.log("[onMessageDisplay] " + JSON.stringify(event));
})
Call the AGCAppMessaging.setForceFetch API in the testing code to specify that the in-app message data must be obtained from the AppGallery Connect server forcibly.
Sending App Message to our App Users
Choose Your Project in App-Gallery Connect and select the application which you want to test an in-app message of the project.
Choose Grow > App Messaging > New
Enter the information required to send App Messages.
On SELECT SENDING TARGET, Choose your application as Target and click Next.
Select Target users by referring to this document.
Now Set Schedule time and click Next.
Click on OK and then Publish.
Now navigate to Management > Operation column and click Test.
Click Add test user and enter the AAID of the test device in the text box. Click Save.
Now in your APP, Test whether the message can be properly displayed and operated.
Output
You can check the action in your console log
Tips and Tricks
1. Set minSdkVersion to 19 or higher.
2. To view the events of App Messaging, Huawei Analytics needs to be enabled and configured.
Conclusion
In this article, we have learned how to integrate IN APP Messaging service by Huawei. APP Messages are very useful for delivering the right message to the target user. It encourages them to use key app functions, or send attractive promotion activities to enhance user loyalty.
Reference
In App Messaging: Documentation
In App Messaging : Training Video

Related

Dynamic Tag Manger implement tag tracking and event reporting | Kotlin

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202333697950470040&fid=0101187876626530001
Introduction
Dynamic Tag Manager allows the developers to deploy and configure information securely on web-based UI. It helps to track the user activities.
Use cases
1. Deliver an ad advertising app to the ad platform.
2. When user taps the ad download app and use.
3. Using DTM configure the rules and release configuration.
4. Automatically app updates the configuration.
5. Daily monitoring reports.
Advantages
1. Faster configuration file updates.
2. More third-party platforms.
3. Free-of-charge
4. Enterprise-level support and service
5. Simple and easy-to-use UI
6. Multiple data centers around the world
Steps
  1. Create App in Android.
  2. Configure App in AGC.
  3. Integrate the SDK in our new Android project.
  4. Integrate the dependencies.
  5. Sync project.
Dynamic Tag Manager Setup
  1. Open AppGallery Connect, select DTM Application and select Dynamic Tag Manager.
Choose My Projects > Growing >Dynamic Tag Manager
{
"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"
}
2. Click Create Configuration, enter required information in displayed dialogue-box and click OK.
3. Click Configuration name.
4. Click Configure, enter required details in Preset variables and Custom variables.
Click Name and click Variable tab to find Preset variables and Custom variables nodes.
Note: Preset variables is predefined variables and Custom variables is user defined variables.
5. A condition is the prerequisite for triggering a tag when the tag is executed. Click Create Condition tab, click Create to enter Name, Type and Trigger, and then click Save.
6. Click Create, enter the Name, Extensions and Operation in Configure tab.
Note: Tag is used to track events
7. Click Version tab and click Create.
Enter Name and Description, and then click OK.
Note: A version is a snapshot of a configuration at a time point, it can be used to record different phases of configuration.
8. Click a version in Version tab, to find Version details such as Overview and Operation records.
9. Click Download/Export version details paste into assets/containers folder.
Integration
App level gradle dependencies.
Code:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
Dtm kit dependencies
Code:
implementation 'com.huawei.hms:hianalytics:5.0.1.300'
implementation 'com.huawei.hms:dtm-api:5.0.0.302'
Kotlin dependencies
Code:
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
Root level gradle dependencies
Code:
maven {url 'http://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
Add the below permissions in Android Manifest file
Code:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ...
</manifest>
After configurations successfully done create instance for HiAnalyticsInstance in activity
Code:
private var mInstance: HiAnalyticsInstance? = null
mInstance = HiAnalytics.getInstance(this)
HiAnalyticsTools.enableLog()
Below snippet for the event trigger method.
Code:
fun updateEvent() {
val bundle = Bundle()
bundle.putString("user_name", userName.editText?.text.toString())
bundle.putString("user_mail", userMail.editText?.text.toString())
bundle.putString("user_number", userNumber.editText?.text.toString())
mInstance!!.onEvent("USERDINFO", bundle)
}
Using debug you can monitor real time data follow steps to enable debug mode.
Command for enabling the debug mode: adb shell setprop debug.huawei.hms.analytics.app <package_name>
Command for disabling the debug mode: adb shell setprop debug.huawei.hms.analytics.app .none.
After debug mode is enabled, all events
Result:
Reference:
To know more about DTM kit, check below URL.
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050043907

Delimiting Huawei Account Kit feat. React Native

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.

Using Huawei App Messaging in Flutter

Huawei AppGallery Connect’s App Messaging service allows you to send targeted, useful in-app messages to your users.
The look and content of messages are completely customisable, and there is a wide range of triggers and filters that can be used to decide who will receive a message and when.
Let's take a look today at how we can set this up to work within a flutter project.
As always we will start with a fresh project but of course, you can just as easily use this guide to build the service into an app you already have!
Installing the Flutter Environment​
Download the Flutter SDK.
Decompress the package to any directory.
Add the Flutter command file to the environment variable.
Download the Flutter and Dart plugins in Android Studio.
{
"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"
}
Enabling the Service and Creating a Flutter project​Sign in to AppGallery Connect, click My projects, click your project, go to Grow > App Messaging, and click Use now. For more information, please refer to App Messaging.
If you do not have an Android project, create one first.
After completing these steps, you can start creating an in-app message.
Click New in the upper right corner.
Set Name and Description
Set the style and content and click Next.
Select a message type from the Layout drop-down list, and set its style and content. Currently, the Modal, Image, and Banner message types are supported.
Set target users and click Next.
In App, select the name of the app package for which you need to publish the in-app message.
You can click New condition to add a condition for matching target users, which include app version, OS version, language, country/region, audience, and more. Among the types, User attributes are defined under HUAWEI Analytics > Management > User attributes, and Prediction is defined by creating prediction tasks under My projects > Grow > Prediction.
Set the message sending time
Message display is triggered by specific events. App Messaging supports two types of trigger events: preset events and HUAWEI Analytics events.
(Optional) Set conversion events. Before setting a conversion event, you need to toggle it on first, which can be done as follows:
Go to HUAWEI Analytics > Management > Events and toggle Mark as conversion event and Event switch on for the specified event. In addition to the events the SDK collects, you can also create a preset or custom event for event tracking and analysis.
Finally, Click Save or Publish.
Integrating the Service SDK​Add dependencies​Start by creating a Flutter project in Android Studio (or opening one).
Then add the agconnect-services.json file from your AppGallery project to the android/app directory
Within the project level build.gradle file make sure to include the huawei maven repo and add the agcp package as a dependency.
Code:
buildscript {
repositories {
google()
mavenCentral()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.huawei.agconnect:agcp:1.6.2.300'
}
}
Next in your app level build.gradle apply the agconnect plugin as so:
Code:
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.huawei.agconnect'
Then in your pubspec.yaml file add the App Messaging SDK dependency.
Code:
dependencies:
flutter:
sdk: flutter
agconnect_appmessaging: ^1.2.0+300
Displaying an In-App Message​If you choose to display a message using the default message layout, the development process is totally coding-free.
By integrating the SDK as above you are all good to go, your creating message will be displayed as per its filters and triggers.
You can also call APIs provided by the service SDK to customize your in-app message.
Customising the Message Layout​Add the following code to onCreate in MainActivity,
Code:
AGCAppMessagingCustomEventStreamHandler.addCustomView();
so that the service SDK can listen to the corresponding event and apply the customized layout.
Code:
streamSubscriptionDisplay = agconnectAppmessaging.customEvent.listen((event) {
showDialog(context ,event.toString());
agconnectAppmessaging.handleCustomViewMessageEvent
(AppMessagingEventType.onMessageDismiss(AppMessagingDismissTypeConstants.CLICK));
});
Then the message is displayed in your app.
Code:
void _showDialog(BuildContext context, String content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
key: Key("dialog"),
title: Text("Result"),
content: Text(content),
actions: <Widget>[
FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
Testing an In-App Message​App Messaging allows you to test an in-app message before it is published. You need to obtain the Anonymous Application Identifier (AAID) of your test device by adding the following code to your Android app module.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
textView.setText(aaid);
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
Sign in to AppGallery Connect, go to Grow > App Messaging > Messages, find the message that you created, click and select Test in the Operation column.
Click Add test user and enter the AAID
Click Save. Check whether the test message is properly displayed on your test device

Beginner: Guideline to Integrate Huawei Mobile Services Account Kit using React Native

{
"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

Guideline to Integrate Huawei ID button to Sign in (Account Kit) using React Native

{
"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

Categories

Resources