Related
Your HUAWEI ID is the account that can be used to access all Huawei services, for example, the HUAWEI Consumer Cloud service, GameCenter, and AppGallery.
The use of HUAWEI IDs is based on the OAuth2.0 protocol. After obtaining authorization from users, apps can obtain users' basic information from the HUAWEI ID system, including OpenID, access tokens, nicknames, and avatars.
OpenID: After a user signs in using a HUAWEI ID, an app can obtain a unique ID opened by the HUAWEI ID. This unique ID is the OpenID. For the same HUAWEI ID, an OpenID is unique for each app and will always be the same for the same app, that is, the OpenID varies according to the app.
Difference between UnionID and OpenID: When the same HUAWEI ID is used to sign in to different apps, the returned OpenID values are different, but the UnionID values are the same. Therefore, if you need to uniquely identify a user among multiple apps, UnionID can be used.
You can obtain the OpenID after accessing HUAWEI Account Kit. However, to obtain the UnionID, you need to select Enable for Enable UnionID when applying for a HUAWEI ID.
Currently, the following two access token grant types are available for your now: implicit and authorization code.
● Implicit:
A quick app can directly call the authorize API to obtain an access token, which has a default validity period of 3600 seconds. When the access token expires, the quick app needs to call the API to obtain authorization again.
● Authorization code:
The authorization process adopting this grant type is also referred to as the web server flow. It applies to all apps with a server.
The web server flow consists of two steps:
1. A quick app calls the authorize API to obtain an authorization code.
2. The quick app calls the API provided by Huawei server to exchange the authorization code for information including an access token and a refresh token.
Preparations
1. Ensure that you have applied for HUAWEI Account Kit on HUAWEI Developer.
For details, please refer to Applying for HUAWEI Account Kit.
2. Install the development tool by referring to Installing the Development Tool.
HUAWEI Account Kit is extended by HUAWEI and does not comply with vendors' standards. You need to access the kit through Huawei quick app IDE.
Accessing HUAWEI Account Kit
Implicit Grant Type
You must be a company developer whose identity has been verified by HUAWEI Developer.
The app ID for which you need to apply for the permission must be created by the developer account that you have provided.
The app for which you need to apply for the permission is not a finance app.
Application method: Download the Quick App - HUAWEI ID-associated Mobile Number and Email Address Access Permission Application Form (App Name & App ID).xlsx, fill in the form, and send it to [email protected]. Then your application will be reviewed and handled.
1. Call the account.getProvider API in your quick app to check whether the current device supports HUAWEI Account Kit.
Only the return value huawei indicates that the device supports HUAWEI Account Kit. To support HUAWEI Account Kit is the premise on which the following function development and API calls can continue.
2. Call the account.authorize API in the quick app to obtain an access token.
3. Call the account.getProfile API to obtain basic user information, including the OpenID, nickname, and avatar of the user.
Import the following API to the quick app and call the getProfile method.
4. Call account.getPhoneNumber API to obtain the user's mobile number. Before using this function, you need to apply to Huawei for related permissions.Before calling getPhoneNumber, call authorize to obtain the access token again by passing the value scope.mobileNumber for the scope parameter.Import the following API to the quick app and call the getPhoneNumber method.
Authorization Code Grant Type
1. Call the account.getProvider API in your quick app to check whether the current device supports HUAWEI Account Kit.
Only the return value huawei indicates that the device supports HUAWEI Account Kit. To support HUAWEI Account Kit is the premise on which the following function development and API calls can continue.
2. Check whether the authorization code needs to be obtained again.
● If the authorization code has not been obtained or the authorization code has expired according to the response of the account.checkUserSession API, go to Step 3.
● If the current session is still valid according to the response of the account.checkUserSession API, go to Step 5.
3. Call the account.authorize API in the quick app to obtain an authorization code.
import account from '@service.account'
account.authorize(OBJECT)
OBJECT Parameter
ParameterTypeMandatory or OptionalDescriptionappidStringMandatoryUnique ID allocated to a quick app created on HUAWEI Developer. For details, please refer to section "Obtaining the APP ID" in Creating a Quick App.typeStringMandatoryThe parameter has a fixed value of code for the authorization code type.redirectUriUriOptionalLeave this parameter empty.scopeStringYesScope of the permissions that are applied. Currently, only cope.baseProfile is supported.
A success response to the calling of the authorize API in the authorization code grant type contains the following parameters.
ParameterTypeDescriptioncodeStringAuthorization code returned when the authorization code grant type is adopted.
Caution:
An authorization code is valid only for five minutes and can be used only once.
4. Call the API for exchanging the authorization code for an access token from the server.
To obtain an access token, send a request using the POST method from the app's server to the Huawei OAuth 2.0 authorization service address https://oauth-login.cloud.huawei.com/oauth2/v2/token with the following mandatory parameters contained in the request body:
Caution:
Input parameters must be urlencoded.
● grant_type: This parameter has a fixed value of authorization_code.
● code: authorization code obtained in the previous step.
● client_id: app ID obtained when you create an app on HUAWEI Developer.
● client_secret: app secret obtained when you create an app on HUAWEI Developer. This parameter is mandatory.
● redirect_uri: This parameter has a fixed value of hms://redirect_url.
POST /oauth2/v2/token HTTP/1.1
Host: login.cloud.huawei.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=Etersdfasgh74ddga%3d&client_id=12345&client_secret=0rDdfgyhytRtznPQSzr5pVw2&redirect_uri=hms%3A%2F%2Fredirect_url
If there are no errors in the request, the authentication server will send a JSON string consisting of the following parameters:
● access_token: access token to be obtained. If an access_token contains backslashes (\), remove all of them.
● expires_in: validity period of the access token, in seconds.
● refresh_token: token used to obtain a new access token. This parameter is returned for all apps.
● scope: access scope of the access token, that is, the list of permissions granted by the user.
Sample code:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token": "346346sdxcdfsa3566546dfdfgfg=",
"expires_in": 3600,
"refresh_token": "68dieddfg08349786gdgfsdfa=",
"scope": "base"
}
If there are errors in the request, the authentication server will send a JSON string consisting of the following parameters.
● error: result code.
● error_description: error description.
Sample code:
HTTP/1.1 400 Bad Request
Content-Type: application/json
Cache-Control: no-store
{
"error": "1102",
"error_description": " The request is missing a required parameter"
}
The default validity period of an access token is 3600 seconds. When the access token expires, you need to use the refresh token to obtain a new access token. To obtain a new access token using the refresh token, go to Step 5.
5. Call the API for obtaining a new access token using the refresh token.The validity period of a refresh token is six months. If the refresh token has expired, go to Step 3.
To obtain a new access token using the refresh token, send a request using the POST method from the app's server to the Huawei OAuth 2.0 authorization service address https://login.cloud.huawei.com/oauth2/v2/token with the following parameters:
● grant_type: This parameter is mandatory and has a fixed value of refresh_token.
● refresh_token: refresh token used to obtain a new access token. This parameter is mandatory.
● client_id: app ID obtained when you create an app on HUAWEI Developer. This parameter is mandatory.
● client_secret: app secret obtained when you create an app on HUAWEI Developer. This parameter is mandatory.
Sample code:
POST /oauth2/v2/token HTTP/1.1
Host: login.cloud.huawei.com
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&client_id=12345&client_secret=bKaZ0VE3EYrXaXCdCe3d2k9few&refresh_token=2O9BSX675FGAJYK92KKGG
Caution:
Input parameters must be urlencoded.
If there are no errors in the request, the authentication server will send a JSON string consisting of the following parameters:
● access_token: new access token to be obtained. If an access_token contains backslashes (\), remove all of them.
● expires_in: validity period of the access token, in seconds.
● refresh_token: refresh token used to obtain a new access token. The refresh token has a validity period of six months and is returned only for some apps.
● scope: list of permissions granted by the user.
Sample code:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token": "346346sdxcdfsa3566546dfdfgfg=",
"expires_in": 3600,
"refresh_token": "68dieddfg08349786gdgfsdfa=",
"scope": "email",
}
If there are errors in the request, the authentication server will send a JSON string consisting of the following parameters.
● error: result code.
● error_description: error description.
HTTP/1.1 400 Bad Request
Content-Type: application/json
Cache-Control: no-store
{
"error": "1102",
"error_description": "The request is missing a required parameter "
}
6. Call the getaccountinfo API with the access token to obtain HUAWEI ID information of the user from Huawei server, including the user name, OpenID, and avatar. To obtain union_id, call the getTokenInfo API.
Debugging HUAWEI Account Kit
1. Start Huawei quick app IDE.
2. Copy the formal certificate file from the release folder under the sign directory of the project to the debug folder.
3. Choose Build > Run Build to debug the app.
If an exception occurs, perform the following operations to locate the fault:
1. Check whether you have applied for a Huawei ID from HUAWEI Developer. For details, please refer to Applying for HUAWEI Account Kit.
2. Call the account.getProvider API to obtain the service provider information. Ensure that the return value is huawei before invoking other APIs. For details about APIs related to HUAWEI Account Kit, please refer to API > Huawei Services > Account.
3. If the result code 1002 is returned, check whether the signature generated by Huawei quick app IDE is consistent with the certificate fingerprint configured on HUAWEI Developer, and whether the formal certificate file in the release folder under the sign directory of the project is copied to the debug folder.
4. Rectify the fault according to the following result code description.
Result CodeDescriptionSuggestion200Common error. The error is usually caused by a gateway request network error. For details, check the error message.If the status code 403 is displayed, switch the network or check whether the scope parameter has been passed.201The user refused to authorize.202Incorrect input parameter.Verify the input parameters.1002Failed to verify the signature.Check whether the RPK is of a formal build version and whether the signature is the same as that configured on HUAWEI Developer.OthersPlease refer to the result codes in Common Result Codes.
FAQ
Q: What can I do if I cannot access my Huawei ID?
The Huawei ID interface is customized by the vendor. To facilitate fault location, install the Huawei Quick App IDE for debugging.
If an exception occurs, perform the following operations to locate the fault:
Check whether you have applied for a Huawei ID to HUAWEI Developer. For details, see Applying for HUAWEI Account Kit.
Invoke the account.getProvider interface. Ensure that the return value ishuaweibefore invoking other interfaces. For details about interfaces related to Huawei IDs, see API > Huawei Mobile Service > Account.
If the error code 1002 is displayed, check whether the signature information generated by the IDE is consistent with the certificate fingerprint configured on HUAWEI Developer. If you debug aquickapp underBuild>RunBuild, copy the formal certificate file from thereleasefolder in thesigndirectory of the IDE project to thedebugfolder.
If other error codes are displayed, rectify the fault by referring to "HMSSDK Framework Error Codes" in Common Error Codes about Huawei accounts.
For details about Huawei developers and HMS, visit the website.
HUAWEI Developer Forum | HUAWEI Developer
forums.developer.huawei.com
There are two key steps required for integrating HUAWEI Game Service. The first is adding code to the onCreate method of the Application class to register the callback listening function for the activity. And the second is calling the JosAppsClient.init method to initialize the game.
Cocos SDKHub helps you complete the first step and provides the initialization method you need for the second step.
Here’s the sample code for calling the method:
JavaScript:
sdkhub.getUserPlugin().callFuncWithParam(“init”);
Please note that your game should be initialized prior to its launch. Furthermore, if the method contains a user privacy agreement, it will need to be called upon the user’s consent. This method is used to display bulletins.
After initialization, the following information is recorded in the log:
Wiki:
I/HMSSDK_HMSBIInitializer: Builder->biInitFlag :true
I/HMSSDK_JosAppsClientImpl: request Jos Notice.
I/HMSSDK_HmsClient: post msg api_name:core.getNoticeIntent, app_id:103468471|, pkg_name:com.cocos2d.checkUpdate, sdk_version:50000302, session_id:*, transaction_id:103468471Intent20201214203645835197672, kitSdkVersion:50001302, apiLevel:1
I/HMSSDK_BaseAdapter: in baseRequest + uri is :core.getNoticeIntent, transactionId is : 103468471Intent20201214203645835197672
I/HMSSDK_PendingResultImpl: init uri:core.getNoticeIntent
I/HMSSDK_PendingResultImpl: setResultCallback
I/HMSSDK_PendingResultImpl: setResult:0
I/HMSSDK_BaseAdapter: baseCallBack.onComplete
I/HMSSDK_HmsClient: receive msg status_code:0, error_code8002, api_name:core.getNoticeIntent, app_id:103468471|, pkg_name:com.cocos2d.checkUpdate, session_id:*, transaction_id:103468471Intent20201214203645835197672, resolution:null
W/HMSSDK_NoticeTaskApiCall: Jos Notice onResult failed:8002,ErrReason:
Note: No results will display after init is called, and no action is required from your app.
Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article, I have implemented Analytics kit and Site Kit.
{
"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"
}
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Analytics and Site Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
XML:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
...
</manifest>
3. Refer below URL for cross-platform plugins. Download required plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001051088628-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: hotelbooking
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_ads:
path: ../huawei_ads/
huawei_account:
path: ../huawei_account/
huawei_site:
path: ../huawei_site/
huawei_analytics:
path: ../huawei_analytics/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Analytics kit
Account kit is valuable in terms of analysis and reporting that we use frequently in our application. Using analytics we can check user behavior custom events and predefined events.
Service Features
By integrating the HMS Core Analytics SDK, you can:
1. Collect and report custom events through coding.
2. Set a maximum of 25 user attributes.
3. Automate event collection and session calculation with predefined event IDs and parameters.
HUAWEI Analytics Kit identifies users and collects statistics on users by an 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.
There are 3 types of events:
Automatically collected
Predefined
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.
Integration
What is AAID?
Anonymous device ID opened to third-party apps. Each app is allocated with a unique AAID on the same device, so that statistics can be collected and analyzed for different apps.
Code:
void getAAID() async{
String aaid = await mAnalytics.getAAID();
print(aaid);
}
Custom Events
Such events can be used to meet personalized analysis requirements that cannot be met by automatically collected events and predefined events.
Note: The ID of a custom event cannot be the same as that of a predefined event. Otherwise, the custom event will be identified as a predefined event
Adding Custom Events
In AppGallery Connect from left side panel open Huawei Analytics > Management > Events
Code:
void customEvent() async {
String name = "Custom";
dynamic value = {'customEvent': "custom Event posted"};
await _hmsAnalytics.onEvent(name, value);
}
Predefined Events
Such events have been predefined by the HMS Core Analytics SDK based on common application scenarios. It is recommended you use predefined event IDs for event collection and analysis.
Code:
void logEvent() async{
String name = HAEventType.SUBMITSCORE;
dynamic value = {HAParamType.SCORE: 15};
await mAnalytics.onEvent(name, value);
}
Site kit
This kit basically provide users with easy and reliable access to related locations and places. With the HMS Site kit we can provide them below features.
1. We can take place suggestions according to the keywords that we have determined.
2. According to the location of the user’s device, we can search for nearby places.
3. We can get detailed information about a location.
4. We can learn the human readable address information of a coordinate point.
5. We can learn the time period where a coordinate point is found.
HMS Site kit – Nearby Search
We can search for many places such as tourist attractions, restaurants, schools and hotels by entering information such as keywords, coordinates. Using this kit we can restrict to specific types using poiType, we can easily access many different information about places such as name, address, coordinates, phone numbers, pictures, address details. Within the Address Detail model, we can easily access information about the address piece by piece through different variables and change the way the address’ notation as we wish.
We need to create a NearbySearchRequest object to perform searching by keyword. We will perform the related search criteria on this NearbySearchRequest object.
While performing this operation, we need set many different criteria as we see in the code snippet. Let us examine the duties of these criteria one by one
1. Query: Used to specify the keyword that we will use during the search process.
2. Location: It is used to specify latitude and longitude values with a Coordinate object to ensure that search results are searched as closely to the location that we want.
3. Radius: It is used to make the search results within in a radius determined in meters. It can take values between 1 and 50000, and its default value is 50000.
4. CountryCode: It is using to limit search results according to certain country borders.
5. Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, the language of the query field we have specified in the query field is accepted by default. In example code snippet in above, the language of device has been added automatically in order to get a healthy result.
6. PageSize: Results return with the Pagination structure. This parameter is used to determine the number of Sites to be found in each page.
7. PageIndex: It is used to specify the number of the page to be returned with the Pagination structure.
Code:
void loadNearBy(String value) async {
SearchService service = new SearchService();
NearbySearchRequest searchRequest = NearbySearchRequest();
searchRequest.language = "en";
searchRequest.query = value;
searchRequest.poiType = LocationType.RESTAURANT;
searchRequest.location = Coordinate(lat: 12.976507, lng: 77.7356);
searchRequest.pageIndex = 1;
searchRequest.pageSize = 15;
searchRequest.radius = 5000;
NearbySearchResponse response = await service.nearbySearch(searchRequest);
if (response != null) {
setState(() {
mSitesList = response.sites;
});
}
}
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. Enable Auto refresh in AppGallery connect it will automatically update events in console
3. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Analytics kit and Site kit in this article. We have learned how to record events and monitor them in AppGallery Connect and also we have learned how to integrated site kit and how nearby search will work.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Analytics Kit URL
Site Kit URL
Read full article.
A pop-up is repeatedly displayed to users when they sign in to the game, asking them to install or update to the latest version of HMS Core.
Log Analysis
Search for Failed to find HMS apk in the Logcat log file. Multiple results will be returned.
The following log indicates that HMS Core (APK) is not installed when the initialization API init is called to check for it:
XML:
Initializing JosAppsClient
I/HMSSDK_HuaweiApiManager: sendRequest
I/HMSSDK_BaseHmsClient: ====== HMSSDK version: 40000300 ======
I/HMSSDK_BaseHmsClient: Enter connect, Connection Status: 1
I/HMSSDK_BaseHmsClient: connect minVersion:30000000
E/HMSSDK_HMSPackageManager: skip package com.huawei.hwid for metadata is null
E/HMSSDK_HMSPackageManager: Failed to find HMS apk
The following log indicates that HMS Core (APK) is not installed when the sign-in API signIn is called to check for it:
I/HMSSDK_[HUAWEIIDSDK]HwIdSignInClientHub: onCreate
I/HMSSDK_HmsAPKVersionCheckUtil: ====== HMSSDK version: 40000300 ======
I/HMSSDK_HmsAPKVersionCheckUtil: check minVersion:30000000
E/HMSSDK_HMSPackageManager: skip package com.huawei.hwid for metadata is null
E/HMSSDK_HMSPackageManager: Failed to find HMS apk
I/HMSSDK_AvailableAdapter: main thread invokes resolution.
I/HMSSDK_AvailableAdapter: startResolution
According to the logs, both the init and signIn APIs find that HMS Core (APK) is not installed, and thus two pop-ups are displayed.
Solution
1. Update the integrated Game Service SDK to 5.0.1.301 or later. For more details, please refer to the official materials.
2. If you prefer not to update the SDK, you can also change the sequence for calling the sign-in and initialization APIs, so that the initialization API is called after the sign-in is successful.
This will ensure that the pop-up displays only once.
Symptom
I made a request to verify the purchase token by referring to the official materials, but error message "{responseCode 8 , responseMessage ERROR_INVALID_PAYMENTTOKEN}" was returned. The URL of the request API was {rootUrl}/applications/purchases/tokens/verify.
Analysis & SolutionThe official materials provide the following solutions:
1. Error code 8 indicates that a user failed to consume or confirm a product because the user does not own the product. Consume or confirm the product only after it is successfully purchased; otherwise, this error may occur. If the consumption or confirmation is indeed performed for a purchased product but this error still occurs, please ensure that the parameters passed by the corresponding APIs are correct.
Result codes
2. Check whether the {rootUrl}/applications/purchases/tokens/verify URL in the API is correct. The value of rootUrl varies depending on the site. Theoretically, if a URL is of a non-AppTouch site, all sites can be selected and Huawei server performs inter-site routing. However, when a non-AppTouch token requests an AppTouch site URL, this result code will be reported.
Reference