Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201309395572810143&fid=0101187876626530001
When using the HMS Drive Kit, if the user's cloud storage is insufficient, the developer can determine whether the user has installed the HUAWEI MOBILE CLOUD app on the mobile phone through PackageManager.
If the app has been installed, the developer can invoke the upgrade purchase page of the Huawei MOBILE Cloud app in intent mode.
There is advised developer to use the dialog pop-up mode, which can allow users to determine whether to invoke the intent to access the HUAWEI MOBILE CLOUD upgrade page.
The core code for determining whether the HUAWEI MOBILE CLOUD app has been installed is as follows:
Code:
final PackageManager packageManager = activity.getPackageManager();
// Obtaining the Package Information of All Installed Programs
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
for (PackageInfo info : pinfo) {
if (info.packageName.equals("com.huawei.hidisk")) {
// Here is used to process the logic of the Huawei Mobile Cloud app that has been installed.
}
}
The core code for invoking the upgrade purchase page of the Huawei Mobile Cloud app is as follows:
Code:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("hicloud://cloudDrive/getInfo?path=PackageInfoActivity"));
startActivity(intent);
For more details, you can go to:
Official website
Development Documentation page, to find the documents you need
Reddit to join our developer discussion
GitHub to download demos and sample codes
Stack Overflow to solve any integration problems
Related
More information about the AppsUP contest, you can visit HUAWEI Developer Forum.
The AppsUP contest has already been online. Maybe many developers encounter the following questions in the process. Today I want to share the frequently asked questions of Map Kit with you. Hope they can help you.
Q: Can I transfer a mark in Google Map to HUAWEI Map?
A: The mark in Google Map cannot be transferred to HUAWEI Map as Google Map does not support data export.
Q: Huawei map not working after upload the app to Huawei gallery. If i installed the same apk directly to phone everything working perfectly.
A: The fingerprint signatures of the two apps are different. That means you can use them separately.
Q: I am using HMS Map kit in my application when i open the particular activity. i am getting some messages repeatedly and UI is getting hanged and ANR is happening.
A: This issue can occur when the UI thread is blocked.
There could be below reasons for this issue:
1> Not using the MapAsync for handlling the callback.
2> While using the MapInitializer, context is null.
3> This provided URL is not correct.
Please check below for the reference
https://developer.huawei.com/consumer/en/doc/development/HMS-References/hms-map-mapsinitializer
https://developer.huawei.com/consumer/en/doc/development/HMS-References/hms-map-return-codes
Q: Map is not rendering and displays white screen returns http status code 502
A: If HTTP status code 502 is returned, a network error has occurred. Check your network environment.
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/open-platform-error-0000001050121484-V5
Q: I find gesturing on Map Kit a bit difficult? Is there a solution to make the gesturing similar to what is available on the Google Maps?
A: Some check points for you:
1. Please download sample code and use SupportMapFragment by referring to sample code. Link: https://developer.huawei.com/consumer/en/doc/development/HMS-Examples/hms-map-v4-example
2. Also please update the HMS Core version to the lastest and try.
Q: I followed tutorial about Map Kit , i check everything are same with the tutorial but , my map still blank
A: 1. Check wether you declared app id in manifest.xml file; 2. Enable map service in AGC.
Q: Is it possible to tilt the map more than 45 degrees?
A: Different tilt angles are required for different zoom levels.
when zoom < 10: it not allowed to tilt.
when zoom >= 10: 0 <= tilt <= 45.
So when you set tile to 70f, it can be max to 45f.
Q: I am developing an app with flutter and I decided to link it to a map kit, I followed the documentation and I still get this black screen that shows blank cells and I can't fix this problem
A: You probably haven't set up your signature certificate fingerprint
Please have a look at this guide:
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/config-agc-0000001050296920
Q: map kit 'integrated with flutter' doesn't work with all mobile phones
A: For the build apk, you should config your build.gradle like this (https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201289420207900111&fid=0101187876626530001)
Q: I couldn't find the complete list of mapFeatures in MapStyle JSON. Can I know where can I obtain the MapStyle JSON with all the mapFeatures?
A: You can refer to the official website:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-map-style-customization-0000001050728424
There is also a Style Editor that can be used to generate the JSON files in a quick manner located at the bottom of the documentation.
Q: How to convert from com.huawei.hms.maps.model.PointOfInterest to com.huawei.hms.site.api.model.Site ?
A: You can use the Site Kit Place Details to obtain the site for a given POI
Code:
<p style="line-height: 1.5em;">override fun onPoiClick(poi: PointOfInterest) {
//Obtain a Search service Instance
val searchService = SearchServiceFactory.create(requireContext(),
URLEncoder.encode(API_KEY, "UTF-8") )
//Create the request for the given POI
val request = DetailSearchRequest()
request.setSiteId(poi.placeId)
// Create a search result listener.
val resultListener =
object : SearchResultListener<DetailSearchResponse?> {
// Return search results upon a successful search.
override fun onSearchResult(result: DetailSearchResponse?) {
var site: Site?=null
if (result == null || result.site.also { site = it } == null) {
return
}
//here you can get the site information
Log.i("SITE","${site?.formatAddress}")
}
// Return the result code and description upon a search exception.
override fun onSearchError(status: SearchStatus) {
Log.e(
"TAG",
"Error : " + status.errorCode + " " + status.errorMessage
)
}
}
searchService.detailSearch(request, resultListener)
}</p>
You can check the guide here:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/android-sdk-place-details-0000001050156636-V5
More information like above, follow me. You can get the updated collection about HMS Kits.
Any doubts or questions about this, you can leave your comment below.
More information like this, you can visit HUAWEI Developer Forum
Opportunity
The vast number of apps are available for download. There are apps intended for specific purposes and there are similar apps intended for the same purposes. As more apps are available, there is a tendency for users to download more apps to address specific needs or maximize the unique features of similar apps for addressing their needs.
Having an immense number of apps brings stiff competition among developers to ensure that their apps stand out among the other apps. For app users, having a lot of apps in their devices could lead to increased password fatigue and complicated username and password management. It would be a win-win solution for both developers and app end users to have a way that enables app users to sign-in to apps in a fast, simple, and secure manner to have a positive user experience resulting to possible faster app adoption.
What is HUAWEI Account Kit?
HUAWEI Account Kit enables developers to add simple, secure, and quick sign-in and authorization functions to their apps. These functions are achieved by the HUAWEI ID sign-in and authorization solution that complies with OAuth.20 and OpenID Connect. The HUAWEI ID sign-in and authorization solution enables stand-alone apps and apps running on independent developer servers to access user authentication information such as an ID token to enable users to quickly and securely sign-in to apps using their HUAWEI IDs.
How to sign in with HUAWEI ID (ID Token)?
Service process for signing in with HUAWEI ID (ID Token)
The following steps explain the process flow for signing in with HUAWEI ID (ID Token):
1. The app sends a sign-in request to HUAWEI Account SDK upon user sign-in using HUAWEI ID.
2. HUAWEI Account SDK informs the user about the content to be authorized using a user sign-in authorization interface based on the authorization scope in the sign-in request.
3. HUAWEI Account SDK sends an ID token to the app after the user authorizes the app to access the content.
4. The app verifies the ID token.
To request authorization for obtaining an ID token:
1. Present the HUAWEI ID sign-in icon on a sign-in page.
2. Send an authorization request by calling HuaweiIdAuthParamsHelper.setIdToken.
Code:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
3. Initialize HuaweiIdAuthService using getService method of HuaweiIdAuthManager.
Code:
HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
4. Bring up the HUAWEI ID sign-in authorization interface using HuaweiIdAuthService.getSignInIntent.
Code:
startActivityForResult(authService.getSignInIntent(), 8888);
5. Obtain HUAWEI ID from the sign-in result by calling HuaweiIdAuthManager.parseAuthResultFromIntent of onActivityResult after completing sign-in authorization.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//Process the sign-in and authorization result and obtain an ID token from AuthHuaweiId.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
//The sign-in is successful, and the user's HUAWEI ID information and ID token are obtained.
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "idToken:" + huaweiAccount.getIdToken());
} else {
//The sign-in failed.
Log.e(TAG, "sign in failed : " +((ApiException)authHuaweiIdTask.getException()).getStatusCode());
}
}
}
To verify ID token validity via local verification
Note: Local verification might fail if the current time of the mobile phone is not in sync with the standard time. Make sure that the current time of the mobile phone to be used for local verification is in sync with the standard time.
1. Obtain a public key from the URI obtained from the jwks_uri field at https://oauth-login.cloud.huawei.com/.well-known/openid-configuration.
Code:
private void getJwks(ICallBack iCallBack) {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(Constant.CERT_URL)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "Get ID Token failed.");
iCallBack.onFailed();
}
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
try {
String res = response.body().string();
JSONObject jsonObject = new JSONObject(res);
mJsonArray = jsonObject.getJSONArray("keys");
iCallBack.onSuccess();
} catch (NullPointerException | JSONException | IOException e) {
Log.i(TAG, "parse JsonArray failed." + e.getMessage());
iCallBack.onFailed();
}
}
}
});
}
NOTE: The public key is updated daily and is cached in the app server.
2. Verify the ID token using JWT library such as jwt.io.
Code:
DecodedJWT decoder = JWT.decode(idToken);
Algorithm algorithm = Algorithm.RSA256(mRSAPublicKey , null);
JWTVerifier verifier = JWT.require(algorithm).build();
// verify signature
verifier.verify(decoder);
3. Check if the value of iss is https://accounts.huawei.com.
Code:
decoder.getIssuer().equals(ID_TOKEN_ISSUE);
4. Check if the value of aud is the same as the client_id of the app.
Code:
decoder.getAudience().get(0).equals(CLIENT_ID);
5. Check if the expiration of the ID token is based on the value of exp.
Code:
// Expired, throws TokenExpiredException
verifier.verify(decoder);
If the values of the iss and aud checks out and the expiration of the ID Token is based on the value of exp, the ID token is successfully verified, and the app can use the user information in the sign-in result.
Code:
JSONObject jsonObject = new JSONObject(new String(Base64.decode(decoder.getPayload(), Base64.URL_SAFE), DEFAULT_CHARSET));
For the code, you can refer to IDTokenParser.java in the Client Sample Code.
The Benefits
To the developers
Developers can provide a positive user experience to their app users since the app users do not need to undergo a registration and verification process when signing-in to apps using their HUAWEI ID.
To the end user
End users can sign-in to apps in a fast, simple, and secure manner. Minimizes username and password management since end users can sign-in to different apps integrating the Account Kit just by using their HUAWEI ID.
Learn More
To know more information on how to maximize the features and advantages of HUAWEI Account Kit, go to https://developer.huawei.com/consumer/en/hms/huawei-accountkit
Thank you so much for the post. It is very useful
Is there any image or icons specification like facebook login button has?
More information like this, you can visit HUAWEI Developer Forum
What is SafetyDetect?
SafetyDetect is an API or Kits that provide security checks to your application. This will help to protect your app against security threats or malicious programs.
The kits consists of 5 main APIs:
SysIntegrity API: Checks whether the device running your app is secure, for example, whether it is rooted.
AppsCheck API: Obtains a list of malicious apps.
URLCheck API: Determines the threat type of a specific URL.
UserDetect API: Checks whether your app is interacting with a fake user.
WifiDetect API: Checks whether the Wi-Fi to be connected is secure.
Why SafetyDetect?
Why do you want to use safetydetect?
Imagine that if your app deals with sensitive data and/or provide transactional capabilities, you would not want your app security to be compromised.
SafetyDetect will provide the security (device, url, apps, wifi) to your app so that you can ensure that your app and data is not compromised when infected device access your apps.
Using SysIntegrity API
To use SysIntegrity API, there are only a few simple steps.
First, add the required app gallery plugin and safety detect dependency to your build.gradle
Project build.gradle:
Code:
dependencies {
implementation 'com.huawei.hms:safetydetect:{version}'
}
Module build.gradle:
Code:
implementation 'com.huawei.hms:safetydetect:5.0.1.300'
Next, to call the API you will need to generate a nonce value, this value must be at least 16 bytes and is only valid once. This value will be returned also within the SafetyDetect response, so you can use this value to check the validity of the Response.
A nonce can be the app username appended with the timestamp of the request, or any unique value of the application.
Code:
fun invokeSysIntegrityCheck() {
val mClient = SafetyDetect.getClient(this)
val nonce = "This Is Just A Test Nonce".toByteArray(Charsets.UTF_8)
val task = mClient.sysIntegrity(nonce, "your app id")
task.addOnSuccessListener {res ->
// sys integrity call success, result is returned
val result = res.result
}.addOnFailureListener {
// something went wrong, please check your app id and if you have enabled the safety detect api in developer console
it.printStackTrace()
}
}
The result of the check is returned in a json format, sample is below:
Code:
{
"advice":"RESTORE_TO_FACTORY_ROM",
"apkCertificateDigestSha256":[
"yT5JtXRgeIgXssx1gQTsMA9GzM9ER4xAgCsCC69Fz3I="
],
"apkDigestSha256":"6Ihk8Wcv1MLm0O5KUCEVYCI/0KWzAHn9DyN38R3WYu8=",
"apkPackageName":"com.huawei.hms.safetydetectsample",
"basicIntegrity":false,
"nonce":"R2Rra24fVm5xa2Mg",
"timestampMs":1571708929141
}
If the basicIntegrity parameter is false, the user device is at risk. You can choose to notify the user or block the access of the app if you think it’s necessary.
Using AppsCheck API
AppsCheck api is a service where it will detect if any malicious apps are installed on the device. The signature of this malicious apps is stored in the cloud and is periodically updated.
Code:
fun invokeAppsCheck() {
val mClient = SafetyDetect.getClient(this)
val task = mClient.maliciousAppsList
task.addOnSuccessListener {
// service call is successful. we will need to check the app lsit response to see if there is any malicious app installed
val appDataList = it.maliciousAppsList
if (it.rtnCode == CommonCode.OK) {
if (appDataList.isEmpty()){
// malicious apps list is empty, device is safe.
}
else {
// malicious apps is detected on the device
appDataList.forEach {
Log.w("warn", "Malicious app detected: ${it.apkCategory}, ${it.apkPackageName}, ${it.apkSha256}")
}
}
}
}.addOnFailureListener {
// something went wrong
}
}
Using URLCheck API
URLCheck is a service which allows the app to check a particular URL for malicious URL. This is very useful for app that re-directs the user to a lot of other 3rd party URL, such as barcode scanner.
To use URL Check Api:
Code:
fun doUrlCheck(url: String) {
val mClient = SafetyDetect.getClient(this)
// Check the URL
// Param1: URL To be checked
// Param2: your Huawei App ID
// Param3&4: Types of threat to be checked
mClient.urlCheck(url, "your app id here",
UrlCheckThreat.MALWARE,
UrlCheckThreat.PHISHING)
.addOnSuccessListener {
if (it.urlCheckResponse.isEmpty()) {
// No threat or phishing detected
} else {
// Threat detected
}
}
}
So there we have it. Safety Detect is really useful to secure your apps from threats when user is using the app.
For more information, please see the developer link:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050156325
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
What Is App LinkingApp Linking allows you to create redirection links that work across multiple platforms including Android, iOS, HarmonyOS, and web. With links of App Linking, you can redirect users to ads, or native app content that they can share with each other. You can create app links and send them to users, or allow users to share links dynamically generated in your app. Anyone who receives a link can tap it to access the specific app content.
Enabling App Linking and Integrating the App Linking SDK1. Click My projects in AppGallery Connect, click your project card, and select your app for which you want to enable App Linking from the drop-down list on the top.
2. Go to Grow > App Linking. If it is the first time that you use the service, click Use now.
3. Enter the App Store ID and team ID used in your signing certificate, and then click ☑.
4. Go to Project settings > General information, and download the agconnect-services.plist file under App information.
5. Open the CLI and navigate to the location of your Xcode project. Then, create a Podfile. Skip this step if a Podfile already exists.
cd project-directory
pod init
6. Edit the Podfile to add the pod dependency AGConnectAppLinking.
target 'AGC-AppLinking-2' do
pod 'AGConnectAppLinking'
end
7. Install the pod and open the .xcworkspace file to view the project.
pod install
Designing the UIYou can create a page layout in your iOS project and design the UI according to the following figure. On the page, a link of App Linking can be received and displayed.
Requesting a URL Prefix1. Go to Grow > App Linking. Click the URL prefixes tab and click New URL prefix.
2. In the Set domain name area, enter a URL prefix.
3. Click Next. The system automatically checks whether the URL prefix is available.
Creating a Link of App Linking in Your App1. Import AGConnectCore and AGConnectAppLinking to the AppDelegate class of the app, and call AGCInstance.startUp in the didFinishLaunchingWithOptions method for initialization.
import AGConnectCore
import AGConnectAppLinking
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AGCInstance.startUp()
return true
}
2. Create an object named AGCAppLinkingComponents, and set urlPrefix to the URL prefix requested in AppGallery Connect. Set deepLink. Set iOS app parameters, where iosBundleId is the app package name, and iosDeepLink is the redirection link to your iOS app.
let components = AGCAppLinkingComponents()
components.uriPrefix = "https://codelab.drcn.agconnect.link"
components.deepLink = "https://developer.huawei.com/consumer/cn"
components.iosBundleId = Bundle.main.bundleIdentifier
components.iosDeepLink = "AppLinking://ios/test2=456"
components.socialTitle = "AppLinking"
3. Call components.buildLongLink to generate and obtain a long link.
longLinkLabel.text = components.buildLongLink().absoluteString
4. Call components.buildShortLink to generate and obtain a short link.
components.buildShortLink { [self] (shortLink, error) in
if let e = error {
let alert = UIAlertController.init(title: "Error", message: e.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
shortAppLinking = shortLink?.url.absoluteString
shortLinkLabel.text = shortAppLinking
}
5. In the method of sharing a link, the short link, generated by the App Linking SDK, is copied to the system clipboard.
@objc func shareLink() {
UIPasteboard.general.string = shortAppLinking
}
Receiving a Link of App Linking in Your App1. If you want the link of App Linking to be a custom URL, set a custom URL scheme under TARGETS > Info > URL Types in Xcode. Set URL Schemes to AppLinking.
2. Import AGConnectCore and AGConnectAppLinking to the AppDelegate class of the app, and call AGCInstance.startUp in the didFinishLaunchingWithOptions method for initialization.
import AGConnectCore
import AGConnectAppLinking
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AGCInstance.startUp()
}
3. Call the AGCAppLinking.instance().handle method, and process the received link event in the callback.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
self.window?.rootViewController = nav
AGCInstance.startUp()
AGCAppLinking.instance().handle { (link, error) in
let deepLink = link?.deepLink
vc.getDeepLink(deeplink: deepLink)
}
self.window?.makeKeyAndVisible()
return true
}
4. Implement the application: openURL: options: method, and return the value of AGCAppLinking.instance().openDeepLinkURL(url).
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let isAppLinking = AGCAppLinking.instance().openDeepLinkURL(url)
return isAppLinking
}
Compiling and Testing Your App1. In Xcode, run your app on a mobile phone or simulator.
2. Click Create App Linking to generate a long link and a short link using the App Linking SDK.
3. Click Share short App Linking to copy the short link to the clipboard.
4. Paste the short link to a browser and access the link. Click Open to launch your app as prompted.
CongratulationsWell done. You have successfully built an app that integrates App Linking of AppGallery Connect and learned how to:
Create a sharable link using the App Linking SDK.
Launch your app through the configured link and receive the deep link using the App Linking SDK.