Account Kit provides simple, secure, and quick sign-in and authorization functions. Rather than having users enter accounts and passwords and wait for authentication, you can let your users simply tap Sign in with HUAWEI ID to quickly and securely sign in to an app with their HUAWEI IDs.
And this is the very reason why I integrated this kit into my app. While doing so, I encountered and collated some common issues related to this kit, as well as their solutions, which are all listed below. I hope you find this helpful.
1. What is redirect_url and how to configure it?redirect_url, or redirection URL, is not the real URL of a specific webpage. Its value is a character string starting with https://. Although it can be customized to whatever you want, you are advised to assign a meaningful value to this parameter according to your service's features.
According to OAuth 2.0, in a web app, redirect_url works in the following scenario: After obtaining user authorization from the OAuth server, the web app will jump to the redirection URL. The web app needs to obtain the authorization code through the URL. To obtain an access token, pass the URL as a parameter to the request that will be sent to the OAuth server. Then, the server will check whether the URL matches the authorization code. If so, the server will return an access token, but if it doesn't, it will return an error code instead.
Check out the instructions in Account Kit's documentation to learn how to set a redirection URL.
2. What's the difference between OpenID and UnionID?An OpenID uniquely identifies a user in an app, but it differs for the same user in different apps.
A UnionID uniquely identifies a user across all apps created under the same developer account.
Specifically speaking, after a user uses their HUAWEI ID to sign in to your apps that have integrated Account Kit, the apps will obtain the OpenIDs and UnionIDs of that user. The OpenIDs are different, but the UnionIDs are the same. In other words, if you adopt the OpenID to identify users of your apps, a single user will be identified as different users across your apps. However, the UnionID for a single user does not change. Therefore, if you want to uniquely identify a user across your apps, the UnionID is advised. Note that if you transfer one of your apps from one developer account to another, the UnionID will also change.
3. How do I know whether an account has been used to sign in to an app?To know this, you can call the style='mso-bidi-font-weight:normal'>silentSignIn API. If the value of the returned style='mso-bidi-font-weight:normal'>authAccount object in style='mso-bidi-font-weight:normal'>onSuccess is not null, this indicates that the account has been used to sign in to an app.
Code:
Task<AuthAccount> task = service.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
if(null != authAccount) {
showLog("success ");
}
}
});
4. What to do when error invalid session is reported after the user.getTokenInfo API is called?1. Check whether all input parameters are valid.
2. Confirm that the access_token parameter in the request body has been converted through URL encoding before it is added to the request. Otherwise, if the parameter contains special characters, invalid session will be reported during parameter parsing.
{
"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"
}
Click here to know more details about this API.
5. Is redirect_uri a mandatory parameter in the API for obtaining an access token?Whether this parameter is mandatory depends on the usage scenarios of the API. Specifically speaking:
The parameter is mandatory, when the API is called to obtain the access token, refresh token, and ID token through the authorization code that has been obtained.
The parameter is not mandatory when a refresh token is used to obtain a new access token.
Check out the official instructions for this API to learn more.
6. How long is the validity of an authorization code, an access token, and a refresh token?Authorization code: valid for 5 minutes. This code can be used only once.
Access token: valid for 1 hour.
Refresh token: valid for 180 days.
7. Common result codes and their solutions907135700This code indicates a failure to call the gateway to query scopes of the app.
To solve it, try the following solutions:
1. Check whether the device can connect to the Internet as normal. If not, this could be because the network connection is unavailable and the network connection does not allow for accessing the site for downloading scopes, due to reasons such as firewall restriction.
2. Check whether the app has been created in AppGallery Connect.
3. Check whether the system time of the device is set to the current time. If not, the device SSL certificate will expire, which will prevent the scopes from being downloaded.
907135701This code indicates that scopes are not configured on OpenGW, which may be due to the insufficient application of services for the app and inconsistent environment settings.
To solve this error, try the following solutions:
1. Verify that the app has been created in AppGallery Connect.
2. Check whether the app ID in agconnect-services.json is the same as the app ID in AppGallery Connect.
3. Check whether agconnect-services.json is placed under the app directory, as shown in the following figure.
4. Check whether the environments set for your app and HMS Core (APK) are the same, for example, whether they are all the live-network environment or testing environment.
907135702This code indicates that no certificate fingerprint is configured on OpenGW. To solve this, try the following solutions:
1. Verify that the app has been created in AppGallery Connect.
2. Verify that the SHA-256 certificate fingerprint has been configured in AppGallery Connect. Click here to learn how.
6003This code indicates certificate fingerprint verification failed.
Verify that the certificate fingerprint in your app's APK file is consistent with that configured in AppGallery Connect, by following the steps below:
1. Open the APK file of your app, extract the META-INF directory from the file, obtain the CERT.RSA file in the directory, and run the keytool -printcert -file META-INF/CERT.RSA command to get the signing certificate information.
2. Sign in to AppGallery Connect, click My projects, and select the project you want to check. On the displayed page, select the app, go to Project settings > General information, and check whether the value in SHA-256 certificate fingerprint is the same as that in the previous step.
Click here to learn more about certificate fingerprint configuration.
ReferencesHMS Core Account Kit Overview
HMS Core Account Kit Development Guide
Related
AppsUP contest has been launched since June 30. Many developers meet the following issues in the process. If you also have the same issue which needs to be resolved, these questions in the list will be timely help. Any doubts or questions about Analytics Kit, this post can be a reference.
Q: When I integrate analysis kit, the compilation errors occurs in React Native Version 0.59.8
A: If you are migrating your app to HMS, suggest you to cross reference your original project and simply add the line to the buildscript/repositories and allprojects/repositories blocks.
The details you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248163576960163&fid=0101187876626530001
Q: Can we change the data storage for Advanced Analytics and How?
A: Till now there is no option to change the Data Storage Location, but you can reset it by deleting your existing app and recreating the app. Then you will see the option to set data storage location option during configuring the developer option. At the same time you must be careful about setting of Data Storage Location because once it set you can't change or modify it.
Q: Huawei analysis shows that the user data does not match the user data displayed on the background of Huawei analysis.
A: According to Huawei analysis, all users are virtual users.
If an application is uninstalled and then reinstalled on a mobile phone, the number of users is counted as two.
Therefore, the number of users calculated by Huawei analysis is greater than or equal to the actual number of users.
Q: If developers need to report some customized user property, which API can be use?
A: You should use "setUserProfile" method of this class: com.huawei.hms.analytics.HiAnalyticsInstance
Attributes will be reported to AGC Analytics and will be usable.
API description is as 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"
}
link:
https://developer.huawei.com/consumer/en/doc/development/HMS-References/3021008#setUserProfile
Q: How to export data to an app server through the data export API provided by the Analytics Kit gateway?
A: Before calling Analytics Kit APIs, you need to obtain the token for authentication. This process involves three parameters, wherein: client_id is the app ID obtained during app creation, client_secret is the password for the app ID that can be queried on HUAWEI Developers, grant_type has a fixed value of client_credentials. In the following example, the getToken() method sends a POST request encapsulating the HTTP tool class to obtain the token and convert the obtained token into an object for subsequent authentication.
More details, you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201302699264940068&fid=0101187876626530001
Q: Integrated Analytics Kit, Why Does the Server Return Error Code 402 When Data Fails to Be Reported?
A: Developers have modified the agconnect-services.json configuration. As a result, the app fails to obtain the AGC token.
Q: Where Is Entry Menu of HUAWEI Analytics Kit?
A: HUAWEI Analytics Kit has been enhanced to provide the cross-platform analysis capabilities, allowing one-stop, unified analysis of Android and iOS users. It looks into the user-centric analysis and helps you understand user behavior on the Android and iOS platforms. For easier access, the entry menu on AppGallery Connect has been changed from Analyze > Advanced analysis (beta) to My projects > HUAWEI Analytics. You can view the overall analysis report or analysis report specific to a certain platform or app in your project. You can even compare user behaviors of different apps and platforms.
Q: Why reporting of custom events fails when I was conducting cross-platform data analysis using User-ID?
A: Event ID definition rule of HUAWEI Analytics Kit: An event ID cannot be left empty or contain spaces. It can consist of a maximum of 256 characters including digits, letters, and underscores (_) but cannot start with a digit. In addition, its value cannot be the same as the ID of an automatically collected event.
Therefore, you can change Purchase Test to Purchase_Test or any other value that complies with the preceding rule.
If you have multiple iOS and Android apps in a project, you can use the filter to view the overall analysis report or detailed report of an app. You can even link users' activity data from different devices by using User-ID to obtain cross-platform analysis data. For details about cross-platform analysis, see:
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/3021001
Q: I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
A: When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Q: What should I do if data reporting fails and the server returns error code 401?
A: Cause Analysis:
Possible causes are as follows:
HUAWEI Analytics Kit has not been enabled.
The obtained agconnect-services.json file is not the original file.
The debug mode has not been successfully enabled.
The Logcat log data on the device is not reported successfully.
Solution:
To correct the fault, perform the following steps:
Check whether HUAWEI Analytics Kit has been enabled and whether it has been turned on (default) in the API management.
Check whether the agconnect-services.json file is the original file without any modification.
Check whether the debug mode is enabled.
Check whether the log data is reported successfully. If the log contains resultCode: 200, the data is reported successfully. Possible causes are as follows:
Case 1: The tools:node parameter is set to "replace" (that is, tools:node="replace"). This causes the app configuration to conflict with AppGallery Connect SDK configurations, and therefore an exception occurs when the AppGallery Connect API is called to obtain the token.
Case 2: The configuration for excluding HUAWEI Analytics Kit from obfuscation is not added before you compile the APK. As a result, an exception occurs during the running of the APK.
Open the obfuscation script file of your project.
Add configurations to exclude HUAWEI Analytics Kit from obfuscation.
Set tools:node to "merge" (that is, tools:node="merge").
Manually write all information in the AndroidManifest.xml file of AppGallery Connect to the AndroidManifest.xml file of your app.
Code:
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.agconnect.**{*;}
-keep interface com.huawei.hms.analytics.type.HAEventType{*;}
-keep interface com.huawei.hms.analytics.type.HAParamType{*;}
Related articles you can refer:
[AppsUP] Frequently Asked Questions About Huawei Account Kit
[AppsUP] Frequently Asked Questions About Huawei Map Kit
[AppsUP] Frequently Asked Questions About Huawei Push Kit
More doubts or questions about Analytics Kit, leave your comment below or ask your questions in HUAWEI Developer Forum.
INTRODUCTION
In this article we will learn how to integrate the Push Kit into a Unity project from start to finish, constantly in groups and video game development communities questions and difficulties are triggered for developers so within this article I would like to touch on different problems that can be easily solved just by following a few steps and modifying certain values within the Unity editor.
{
"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"
}
MOST COMMON QUESTIONS IN DEV COMMUNITIES
Through the development communities, we have been presented with different questions that I have been collecting little by little, below I share some that are commonly repeated.
After importing the Evil Mind plugin, my project won't run on my device?
Add the Push Manager prefab and when I run the game in game mode it doesn't compile
How can I get the token that Push Kit returns to me when it is executed?
Unity cannot locate the Android SDK and I cannot run the project.
ARTICLE GOAL
Our goal in this article will be to be able to send a notification to our phone from App Gallery Connect using the token that HMS Push Kit gives us, we will achieve this by solving the problems that arise at the time of configuration.
STEPS
Configuration App Gallery Connect.
Configure Unity to run our project.
Import Evil Mind Plugin.
Configure our project with App Gallery Connect.
Create the class and the code to get the answer.
Obtain the log of our device
Add the token to App Gallery Connect
Try our game
APP GALLERY CONFIGURATION
As we know we must create a project in App Gallery Connect and add an app in order to configure the necessary data for our project. Let's start by logging into the AGC console to create a project.
Within the projects section we can create a new project where we must create an App which will be added to our project.
Once the application is created we must fill in the following data in the form, for this it will be necessary to create our project in Unity and assign the package name.
Let's go to unity to create the necessary data, Open unity and create a new project. Once the project is created, select Build Settings> Player Settings to assign your game data.
Remember to confirm that in Other Settings you also have your package correctly. Here we will answer one of the questions we have at the beginning of this article.
After importing the Evil Mind plugin, my project won't run on my device? This generally happens to us because we do not have the Backend value configured correctly and the minimum supported API, in the following image I share the data that you should place.
With this configuration we will be able to run our game on the device that we have connected, remember that if you are using a GMS device it will be necessary to install the HMS Core apk which you can download from this league. https://m.apkpure.com/es/hms-core/com.huawei.hwid/download once downloaded you can run huawei mobile services.
Running your project on the device should have a screen similar to this, we have not added the button yet but we will do it later, the important thing is that your scene compiles correctly.
UNITY CONFIGURATION
Let's start now with the configuration of our project in Unity. What we must do is import the Evil Mind plugin to be able to obtain the upper menu of Huawei and to be able to place the data obtained from AGC. Download the plugin from the repository that I share with you now. https://github.com/EvilMindDevs/hms-unity-plugin
Download the pcustom package to your computer and import it into Unity.
You must import it from the import tab and select custom package, once imported an option will be enabled in the upper menu with the title of Huawei, when you click on it you will get the following pop up.
Download the json file from AGC and replace it in Unity the path to find the json you can find in the following image
Open the agconnect file and start putting the necessary data to paste into the Huawei plugin. In the image I am showing you in yellow what data you must take to place them in the plugin window.
When you finish assigning the data, click on the Configure Manifest button. IMPORTANT JUST GIVE A CLICK, OTHERWISE YOU WILL ADD LINES TO YOUR MANIFEST AND THE ERROR WILL BE PRESENTED Merge Manifest.
Check your android Manifest take into account that when you import the plugin, a default Manifest will be downloaded in your project, that Manifest Default has packages that belong to the example, so it is important that you only have the following <providers> as I show in the image
Add the Push Manager prefab to your scene, you can also add a button inside a Canvas to initialize the Push Kit service, leave it in the onStart () method;
Run your project again to identify errors if they occur during the compilation and construction of the project. This will not generate any effect in Push Kit nor will it grant you the token because we have not configured the SHA256 signature, possibly the console will indicate that the fingerprint has not been configured. We are going to configure this signature. Create your keystore in your project folder, go to the folder where your project is with your console and execute the following command.
Replace the name of your keystore
keytool -list -v -keystore d:key.keystore
Get the Sha 256 and place it in AGC.
CODING
We will create a script that is responsible for initializing the service and granting us the token of our device and then sending the notification through token.
Java:
namespace HmsPlugin
{
public class PushKitManager : MonoBehaviour, IPushListener
{
public Action<string> OnTokenSuccess { get; set; }
public Action<Exception> OnTokenFailure { get; set; }
public Action<RemoteMessage> OnMessageReceivedSuccess { get; set; }
// Start is called before the first frame update
void Start()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"[HMS] Push token from GetToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnNewToken(string token)
{
Debug.Log($"[HMS] Push token from OnNewToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnTokenError(Exception e)
{
Debug.Log("Error asking for Push token");
Debug.Log(e.StackTrace);
OnTokenFailure?.Invoke(e);
}
public void OnMessageReceived(RemoteMessage remoteMessage)
{
OnMessageReceivedSuccess?.Invoke(remoteMessage);
}
}
}
We will also create a method only as an example to be able to initialize the service and obtain the token
Java:
public void StartNotificationService()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"The token {token}");
if(token != null)
{
}OnTokenSuccess?.Invoke(token);
}
Now we need to obtain the token of our phone and that the Log will return us and we will place it in the push notification service.
Fill in the necessary data to send the notification such as the Title, the Body and the name of the notification. You must also configure the device parameters. In this section is where you must add the token obtained from your device.
Now just launch the notification
TIPS AND TRICKS
I dont know how to obtain logs from my Android Device. In the following steps you'll learn how to debug from your Device.
For troubleshooting and debugging, it is often very helpful to capture the device logs. The device logs contain information about the status of a running application on the device and any errors encountered. The IAP Engineering team requires logs for open issues. It is assumed here that you have an Android device configured with Developer options and attached to a PC with a USB cable. These steps show the process on a Windows system and works similarly on a Mac
1. In Unity, find the location of the Android SDK. From the Edit menu, choose Preferences/External Tools
2. Look for the Android SDK. On my system it was C:\Users\[username]\AppData\Local\Android\sdk
3. Open a command prompt, and change to this directory.
4. Change directory to the platform-tools subdirectory.
5. You should see adb.exe in this directory.
6. With the device connected via USB, run the following command:
adb devices (Mac is ./adb devices)
7. This should return device serial number followed by the word "device"
8. Run "adb logcat | findstr -i unity" (use grep on Mac) in the terminal window. This will find anything with the word "unity" in the output, case insensitive.
9. This will provide the contents of the device log that are associated with a running Unity application
The output can be quite verbose. You can browse through the log however, looking for such words as "error" and "exception". Sometimes customer support will ask for device logs, in which case you can send the output to a text file with the command "adb logcat -d | findstr -i unity > log.txt"
CONCLUSION
Push notifications are one of the trending tools in marketing arenas. No arena has been left untouched by the tool- after engaging users brilliantly on an e-commerce store, it’s the turn of the gaming app push notifications.
Mobile gaming apps have gone too far popular in today’s arena so much so that mobiles have been developed specifically for the game, consisting of the hardware that would meet the demands of the users.In this article we learned how to implement HMS Kit Push notification in oour Unity Game an it was very fast.
REFERENCES
Push Kit - Cloud Message Push- Cross-Platform Messaging Solution - HUAWEI Developer
Push Kit can satisfy the relevance and freshness of content update that your users want. Push instant messages from the cloud to user devices.
developer.huawei.com
Read In Forum
SPANISH VIDEOTUTORIAL
If you speak or understand spanish here you have the videotutorial.
Introduction
In this article, we will cover how to verify Phone Number and Anonymous Account Login using Huawei Auth Service in Unity Project using Official Plugin (Huawei HMS Core App Services). AppGallery Connect provides a cloud-based Auth Service and SDKs to help you quickly build a secure and reliable user authentication system for your apps to verify user identity.
The AppGallery Connect Auth service supports multiple authentication methods and is seamlessly integrated with other server less services to secure user data based on simple rules that you have defined.
Key FunctionsUsing the AppGallery Auth Service SDK, you can integrate one or more of the following authentication methods into your app for achieving easy and efficient user registration and sign-in.
Self-owned account: Your self-owned account is used to support the access of your existing authentication system, so that your existing users can access other server less services in a secure manner.
Anonymous account: Anonymous accounts can be used to access your apps as visitors. The Auth service can assign user IDs to your app visitors, so that they can access other server less services in a secure manner. A visitor can be registered as a formal user and retain the original user ID to ensure service continuity.
Third-party accounts: AppGallery Connect allows user identity to be verified by third-party authentication services. The AppGallery Auth Service SDK supports the following accounts for user identity verification:
1. HUAWEI account
2. HUAWEI Game Service account
3. Phone number
4. Email account
5. WeChat account
6. Weibo account
Development Overview
You need to install Unity software and I assume that you have prior knowledge about the unity and C#.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK installation package.
Unity software installed.
Visual Studio/Code installed.
HMS Core (APK) 4.X or later.
Follows the steps.
1. Create Unity Project.
Open Unity Hub.
Click NEW, select 3D, Project Name and Location.
Click CREATE, as follows
{
"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 Asset Store, search Huawei HMS Core App Services and click Import, as follows.
3. Once import is successful, verify directory in Assets > Huawei HMS Core App Services path, as follows.
4. Choose Edit > Project Settings > Player and edit the required options in Publishing Settings, as follows.
5. Generate a SHA-256 certificate fingerprint.
To generating SHA-256 certificate fingerprint use below command
keytool -list -v -keystore D:\Unity\projects_unity\file_name.keystore -alias alias_name
6. Download agconnect-services.json and copy and paste to Assets > Plugins > Android, as follows.
7. Choose Project Settings > Player and update package name.
8. Open LauncherTemplate.gradle and add below line.
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.301'
implementation 'com.huawei.hms:base:5.2.0.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'
9. Open AndroidManifest file and add below permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
10. Open "baseProjectTemplate.gradle" and add lines, as follows.
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
maven {url 'https://developer.huawei.com/repo/'}
11. Open "mainTemplate.gradle" and add lines like shown below.
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.301'
implementation 'com.huawei.hms:base:5.2.0.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'
12. Create MainActivity.java class inside Plugin > Android folder.
13. Follow the steps, as shown in image:
a. Assign Ads script to Canvas.
b. Select Button and add onclick event
c. Assign all button to button handler as per your requirements.
14. Onclick Button Handler you find your script HMSAuthService (As per your script name) and attach method as per below screen shot.
15. To build apk and run in device, choose File > Build Settings > Build for apk or Build and Run for run on connected device.
Result
1. Click on Anonymous Login, send OTP and Verify button you can see below results.
2. Find the details in AppGallery Connect, as follows.
Tips and Tricks
Always use the latest version of the library.
Add agconnect-services.json file without fail.
Add SHA-256 fingerprint without fail.
Make sure dependencies added in build files.
Make sure that you enabled the auth service in AG-Console.
Make sure that you enabled the Authentication mode in Auth Service.
Conclusion
In this article, we have learnt integration of Huawei Auth Service-AGC anonymous account login and mobile number verification through OTP in Unity Game development. Auth Service provides secure and reliable user authentication system to your application.
Thanks for reading the article, please do like and comment your queries or suggestions.
References
Unity Auth Service Manual
Auth Service
Checkout in forum
View attachment 5589007
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
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.
View attachment 5589009
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
View attachment 5589013
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.
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.
“npm install” & “npm link”
12. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
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"/>
16. 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.
View attachment 5589017
(iv). Click Enable in the row of each authentication mode to be enabled.
View attachment 5589019
For more details visit this documentation.
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.
JavaScript:
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.
JavaScript:
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.
JavaScript:
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.
JavaScript:
AGCAuth.getInstance()
.currentUser()
.then((user) => {
if (user) {
// A user signed in
}
});
Call AGCAuth.signIn for sign-in.
JavaScript:
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.
JavaScript:
AGCAuth.getInstance()
.currentUser()
.then((user) => {
if (user) {
// A user signed in
}
});
Call PhoneAuthProvider.requestVerifyCode to apply for a verification code.
JavaScript:
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.
JavaScript:
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.
Code:
react-native run-android
Result
{
"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"
}
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
Account Kit: Training Video
HMS Core Health Kit provides REST APIs for apps to access its database and for them to provide app users with health and fitness services. As I wanted to implement health functions into my app, I chose to integrate Health Kit. While integrating the kit, I encountered and collected some common issues, as well as their solutions, related to this kit, which are all listed below. I hope you find this helpful.
Connectivity test fails after registering the subscription notification capabilityWhen you test the connectivity of the callback URL after registering as a subscriber, the system displays a message indicating that the connectivity test has failed and the returned status code is not 204.
CauseIf the HTTP status code of the callback URL is not 204, 404 will be returned, indicating that the callback URL connectivity test has failed, even if you can access the URL.
Read Subscribing to Data for reference.
SolutionMake sure that the URL is accessible and the returned status code is 204.
The total number of steps returned by the sampling data statistics API is inconsistent with the value calculated based on the step detailsObtain the total number of steps by calling the API for Querying Sampling Data Statistics.
API URL: https://health-api.cloud.huawei.com/healthkit/v1/sampleSet:polymerize
Request parameters:
Code:
{
"polymerizeWith": [
{
"dataTypeName": "com.huawei.continuous.steps.delta"
}
],
"endTime": 1651809600000,
"startTime": 1651766400000,
"groupByTime": {
"groupPeriod": {
"timeZone": "+0800",
"unit": "day",
"value": 1
}
}
}
As shown below, the total number of steps returned is 7118.
{
"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"
}
Obtain step details by calling the Querying Sampling Data Details API and calculate the total number of steps.
API URL: https://health-api.cloud.huawei.com/healthkit/v1/sampleSet:polymerize
Request parameters:
Code:
{
"polymerizeWith": [
{
"dataTypeName": "com.huawei.continuous.steps.delta"
}
],
"endTime": 1651809600000,
"startTime": 1651766400000
}
As shown below, the total number of steps calculated based on the returned result is 6280.
As we can see, the total number of steps generated in a time segment returned by the sampling data statistics API differs from the value calculated based on the step details.
CauseAs detailed data and statistical data are reported separately, detailed data delay or loss may lead to such inconsistencies.
When you query the data of a day as follows, you will obtain statistical data, rather than the value calculated based on the detailed data.
SolutionWhen querying the total number of steps, pass the groupByTime parameter, and set the duration parameter.
Request parameters:
Code:
{
"polymerizeWith": [
{
"dataTypeName": "com.huawei.continuous.steps.delta"
}
],
"endTime": 1651809600000,
"startTime": 1651766400000,
"groupByTime": {
"duration": 86400000
}
}
As shown below, the returned value is 6280, similar to what you calculated based on the detailed data.
Error code 403 is returned, with the message "Insufficient Permission: Request had insufficient authentication scopes."
CauseError 403 indicates that the request has been rejected. This error occurs when your app does not have sufficient scopes.
Solution1. Check whether you have applied for relevant scopes on the HUAWEI Developers Console.
2. Check whether you have passed the scopes during authorization, and whether users have granted your app these scopes.
The following is an example of passing the step count read scope during authorization.
Make sure that users have selected the relevant scopes when authorizing your app.
Error code 400 is returned, with the message "Insufficient Permission: Request had insufficient authentication scopes."Let us take querying step count details as an example.
Let's say that the request parameters are set as follows:
Access token: generated based on the code of the first authorization.
Time of the first authorization (time when the code is generated for the first time): about 8:00 AM on May 7, 2022.
Time range of data collection:
Start time: 2022-05-06 00:00:00 (1651766400000)
End time: 2022-05-06 12:00:00 (1651809600000)
Request:
Response:
CauseTo protect user data, you are only allowed to read data generated after a user has authorized you to do so. To read historical data generated before a user has granted authorization, you will need to obtain the read historical data scope. If the user does not grant your app this scope, and the start time you set for querying data is earlier than the time you obtained the user's authorization, the start time will revert to the time you first obtained the user's authorization. In this case, error 400 (invalid startTime or endTime) will be reported once the corrected start time is later than the end time you set, or only data generated after the authorization will be available.
In this example, the user does not grant the app the read historical data scope. The start date is May 6, whereas the date when the user authorized the app is May 7. In this case, the start date will be automatically adjusted to May 7, which is later than May 6, the end date. That is why error 400 (invalid startTime or endTime) is returned.
Suggestion1. Check whether you have applied for the read historical data scope on the HUAWEI Developers Console.
Currently, historical data is available by week, month, or year. You can query historical data generated as early as one year before a user's authorization is acquired.
ScopeDescriptionRemarks
https://www.huawei.com/healthkit/historydata.open.week
Reads the previous week's data from Health Kit.Only the previous week's data before the user authorization can be read.
https://www.huawei.com/healthkit/historydata.open.month
Reads the previous month's data from Health Kit.Only the previous month's data before the user authorization can be read.
https://www.huawei.com/healthkit/historydata.open.year
Reads the previous year's data from Health Kit.Only the previous year's data before the user authorization can be read.
2. When generating an authorization code, add the scopes listed in the preceding table, so that users can grant your app the read historical data scope after logging in to their HUAWEI ID.
Data queried after the authorization:
References HMS Core Health Kit