With the unveiling of so many new functions and pages on HUAWEI AppGallery, it’s required a wide range of new redirection solutions on the platform.
However, the types of links, functions, apps, and scenarios that they are used, can vary great. It can be quite confusing sorting this all out, so I’ve outlined some common redirection scenarios for your reference.
Feel free to correct me, if you think that I’ve got something wrong, or am missing something.
1. Redirecting to the AppGallery Home Page
Usage case: You want to redirect the user from an app to the AppGallery home page, so that the user can search for related apps or activities quickly.
Method: Use the action method from Intent to implement the function.
action: com.huawei.appmarket.intent.action.MainActivity
Example:
Java:
public void launchAGHomePage() {
Intent intent = new Intent("com.huawei.appmarket.intent.action.MainActivity");
startActivity(intent);
}
2. Redirecting to an App’s Details Page on AppGallery
2.1 Intent-based Redirection from an In-App Page
Usage case: You want to redirect the user from an in-app page to the app’s details page, so the user can rate or comment on the app.
Methods: Use the action method from Intent to implement the function.
1. Method 1: by app ID
action:com.huawei.appmarket.appmarket.intent.action.AppDetail. withid
setPackage("com.huawei.appmarket");
name: "appId", value: "C100170981"
2. Method 2: by package name
action: com.huawei.appmarket.intent.action.AppDetail
setPackage("com.huawei.appmarket");
name: "APP_PACKAGENAME", value: "com.huawei.browser"
Note: Compared with method 2, method 1 includes additional appmarket and withid parameters from the action method.
Parameters involved:
{
"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"
}
Examples:
Method 1:by app ID
Java:
public void launchAppDetilPage1() {
Intent intent = new Intent("com.huawei.appmarket.appmarket.intent.action.AppDetail.withid");
intent.setPackage("com.huawei.appmarket");
intent.putExtra("appId", "C100170981");
startActivity(intent);
}
Method 2:by package name
Java:
public void launchAppDetilPage2() {
Intent intent = new Intent("com.huawei.appmarket.intent.action.AppDetail");
intent.setPackage("com.huawei.appmarket");
intent.putExtra("APP_PACKAGENAME", "com.huawei.browser");
startActivity(intent);
}
2.2 URL-based Redirection
Usage case: You want to redirect a user who clicks on a shared URL to an app’s details page.
Method: Create a URL with the following format:
hiapplink://com.huawei.appmarket?appId=yourAppID&channelId=yourChannelId&referrer=yourReferrer
Note: You’ll need to change the strings in either italic or bold only.
Parameters involved:
Example:
By app id
Java:
public void launchAppDetilWithURL1() {
String text1 = "hiapplink://com.huawei.appmarket?appId=C100170981&channelId=HwBrowserSearch&referrer=Keywords";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
3. Launching All App Stores Installed on a Device to Redirect Users to an App’s Details Page in an App Store via MARKET
Usage case: You want to launch all app stores installed on the user’s device by passing a package name or app ID, so that the user can choose to go to the app’s details page in a desired app store.
Methods: Pass the link whose scheme is market://. Android supports the standard MARKET protocol, to ensure that all app stores can be launched on Android devices. The methods are as follows:
Method 1: market://details?id=pkgName // for all stores
Method 2: appmarket://details?id=pkgName // only for AppGallery
Method 3: market://com.huawei.appmarket.applink?appId=App ID" // only for AppGallery
Note: Method 1 is a standard method for Android devices, and is applicable to all app stores, such as Google Play and Tecent Appstore.
Parameters involved:
Examples:
// Method 1
Java:
public void launchAppDetilOnMarket1() {
String text1 = "market://details?id=com.huawei.browser";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
// Method 2
Java:
public void launchAppDetilOnMarket2() {
String text1 = "appmarket://details?id=com.huawei.browser";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
// Method 3
Java:
public void launchAppDetilOnMarket3() {
String text1 = "market://com.huawei.appmarket.applink?appId=C100170981";
Uri uri = Uri.parse(text1);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
4. Redirecting from a Web Link to an App’s Detail Page on the Web Version of AppGallery
Usage case: You want to redirect the user to an app’s details page on the web version of AppGallery, when the user clicks on a web link from the app’s official website, or a promotional web page.
Methods:
Method 1:https://appgallery.huawei.com/#/app/YOUR_APPID
Method 2::https://appgallery.cloud.huawei.com/appDetail?pkgName=pkgName
Method 3:https://appgallery.huawei.com/#/app/YOUR_APPID?pkgName=pkgName
Method 4:https://appgallery.cloud.huawei.com/marketshare/app/ YOUR_APPID?locale=LOCALE&shareTo=WAP&shareFrom=channeID
Parameters involved:
Examples:
// Method 1: by app ID
https://appgallery.huawei.com/#/app/C100170981
// Method 2: by package name
https://appgallery.cloud.huawei.com/appDetail?pkgName=com.huawei.browser
// Method 3: by app ID and package name
https://appgallery.huawei.com/#/app/C100170981?pkgName=com.huawei.browser
// Method 4: by complete link with optional parameters (not commonly used, and generally used for badge-based promotions).
HUAWEI Browser
Huawei AppGallery
appgallery.cloud.huawei.com
5. Redirecting from a Badge Link to the App Detail Page on AppGallery
When a badge link of AppGallery appears as an image of AppGallery, by clicking this link, the user will be redirected to an app’s details page on AppGallery. If you hope to market your app, you can use this badge directly. In essence, it still functions as a link, no different than any other web link.
Use cases: If you have developed and released an app, and want to divert traffic from your website or another source to AppGallery, a badge can be ideal.
How to make a badge: The method for creating a badge is rather simple. You only need to sign in to AppGallery Connect, and click AppGallery Download. Then you proceed to make the badge as prompted.
Restrictions: You can only make a badge for apps that have been released, with a maximum of one badge for each app. Once a badge has been created, you can query for it on the Search badge tab page.
Badge use instructions:
You can find a created badge on the Search badge tab page, and download the badge or copy its link. I’ll walk you through some common operations:
Badge download: You will obtain a PNG image, which can be displayed on your website, or on a marketing HTML5 page.
Link creation: You can create a link for a specific channel, for example, Facebook or Baidu.
Link copying: You can download a link for a specific channel.
Usage example:
// 1. Typical link
https://appgallery.huawei.com/#/app...EDCCBCD90A86F29A8DA2400AA4163&detailType=0&v=
// 2. Typical badge with a link, which can be clicked
6. App Linking, with Cross-Platform Link Support
App Linking is a new service provided by AppGallery Connect. Since it’s new, I’ll give you a brief overview of what it is.
The service provides links that can work on a diverse range of platforms, such as Android, iOS, and PC browsers, making it similar in this way to Dynamic Links of Firebase, enabling you to quickly build cross-platform links, which can be easily shared.
In what scenarios can I use App Linking? I’ll give you an example to help illustrate how the service can be used. It’s an app that’s available on both Android and iOS devices, and thus requires a promotional activity that reaches users on both platforms. To engage users, we’ll need to send them an activity invitation link that works on Android and iOS alike. Also, some users may be opening the link in a PC browser, and in this case, that link should also support an HTML5 page for the activity.
What benefits does App Linking offer? Here, two scenarios should be considered:
The user’s device has already installed the app: App Linking will automatically open the app, and show the user the target page.
The user’s device has not installed the app: The link will prompt the user to open the app’s details page on AppGallery, or any other app store (configurable), and download the app. Then, when the user opens the downloaded app, the target page will appear.
How does App Linking work? Links of App Linking can be created in any of the following ways:
Creation on the console: All operations are performed in AppGallery Connect. You’ll need to click My projects, click your project, and go to Grow > App Linking. To create a link of App Linking, create a URL prefix first.This mode is recommended if you’re not familiar with coding. A step will require you to provide a deep link, which will need to be obtained from your R&D personnel.
Creation in your iOS app: This mode is similar to the previous one.
The only difference is that these links are for iOS users.
What if the user’s device is not a Huawei device?
Since App Linking supports both Android and iOS, many of you may be wondering how this service works on non-Huawei Android devices.
1. Can App Linking work for non-Huawei devices? You can be rest assured App Linking is not dependent on HMS Core, and thus is supported on all Android devices, regardless of whether they are running GMS or HMS.
2. What if the user has not installed the app and AppGallery? For Android devices that don’t have AppGallery installed, you can choose to open the link in the local app store that is installed. As long as your package name on that app store is the same as that on AppGallery, the user will be able to open your app’s details page on that app store.
Usage example:
// 1. Typical URL prefix
https://photoplaza.drcn.agconnect.link // In the prefix, photoplaza is unique to the app, and drcn.agconnect.link is a fixed.
// 2. Typical link of App Linking
https://photoplaza.drcn.agconnect.link/vm3Y
// 3. Code for creating a typical link of App Linking for Android
Java:
private static final String DOMAIN_URI_PREFIX = "https://photoplaza.drcn.agconnect.link";private static final String DEEP_LINK = "https://developer.huawei.com";public void createAppLinking() {
AppLinking.Builder builder = new AppLinking.Builder()
.setUriPrefix(DOMAIN_URI_PREFIX)
.setDeepLink(Uri.parse(DEEP_LINK))
.setAndroidLinkInfo(new AppLinking.AndroidLinkInfo.Builder().build());
String LongAppLinking = builder.buildAppLinking().getUri().toString();
}
// 4. Typical link of App Linking for iOS
Objective-C:
- (IBAction)CreatLink:(id)sender {
AGCAppLinkingComponents *component = [[AGCAppLinkingComponents alloc] init];
component.uriPrefix = @"https://photoplaza.drcn.agconnect.link";
component.deepLink = @"https://www.developer.huawei.com";
component.iosBundleId = @"com.lucky.agc.demo";
component.iosDeepLink = @"agckit://ios/detail"; self.longlink.text = component.buildLongLink.absoluteString;
}
7. For Reference
Badge link document: https://developer.huawei.com/consum...ct-Guides/appgallery-agd-introduction-stamped
App Linking document: https://developer.huawei.com/consum.../agc-applinking-introduction-0000001054143215
Guide for adding a referrer: https://developer.huawei.com/consum...connect-Guides/appgallery-referrer-createlink
Guide for querying attribution information: https://developer.huawei.com/consum...ry-connect-Guides/appgallery-referrer-develop
Related
More information like this, you can visit HUAWEI Developer Forum
Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate app messaging and analytics into demo flight booking application.
UseCase
1. We will show app-messaging image on app screen showing list of searched flight. When user tap on app-messaging image, it will redirect to webpage showing guidelines for international arrivals and departures. Add following image URL on Huawei App gallery connect.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2. We will use Huawei analytics to report few events like successful sign in and number of flights available between source destination.
For prerequisite and set up, refer to part 1.
Huawei App messaging
App Messaging of AppGallery Connect used to send relevant messages to target users actively using your app to encourage them to use key app functions. For example, you can send in-app messages to encourage users to subscribe certain products, provide tips on passing a game level, or recommend activities of a restaurant.
Implemetation
1. Add dependency in the app build.gradle file.
Code:
dependencies {
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
}
2. We need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
3. Add following code in your project to obtain AAID.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
4. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
5. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
6. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
7. To specify that the in-app message data must be obtained from the AppGallery Connect server by force we will use.
Code:
appMessaging.setForceFetch();
Since we are using a test device to demonstrate the use of In-App Messaging, so we use setForceFetch API. The setForceFetch API can be used only for message testing. Also In-app messages can only be displayed to users who have installed our officially released app version.
Creating Image In-App Messaging on App Gallery connect
1. Sign in to AppGallery Connect and select My projects.
2. Select your project from the project list.
3. Navigate Growing > App Messaging and click New.
4. Set Name and Description for your in-app message.
5. Provide the in-app message Type. For image in-app message, select type as Image.
6. Provide image URL.
7. Provide the action for image tapping.
8. Click Next to move on to the next section, that is, Select Sending Target section. Here we can define Condition for matching target users. In this article, we did not use any condition.
9. The next section is the Set Sending Time section.
We can schedule a date and time to send in-app message.
We can also provide an End data and time to stop sending message.
We can also display message on an events by using trigger event functionality.
Also we can flexibly set the frequency for displaying the in-app message.
10. Click Next, find Set conversation events. It associates the display or tap of the app message with a conversion event. The conversion relationship will be displayed in statistics. As off now we will keep it as none.
11. Click Save in the upper-right corner to complete message creation.
12. In-app messages can only be displayed to users who have installed our officially released app version. App Messaging allows us to test an in-app message when our app is still under tests. Find the message that you need to test, and click Test in the Operation column as shown below.
13. Provide the AAID of the test device in the text box. Click Save.
14. Click Publish.
Huawei Analytics
In this section, will show you how to use main APIs of HUAWEI Analytics Kit to report some custom events. App will report event like successful login, number of search flights.
1. Add the dependencies in app build.gradle file.
Code:
implementation 'com.huawei.hms:hianalytics:5.0.1.301'
2. The MainActivity.java is launched once user has successfully signed in. In onCreate(), we will call initializeAnalytics()to report successful signed in event.
Code:
private void initializeAnalytics() {
//Enable Analytics Kit Log
HiAnalyticsTools.enableLog();
//Generate the Analytics Instance
instance = HiAnalytics.getInstance(this);
//Parameter definition
Bundle bundle = new Bundle();
bundle.putBoolean("IsLoggedIn", true);
//Reporting event
instance.onEvent("LoginStatus", bundle);
}
3. To report number of flight available between origin and destination.
Code:
httpHandler.setFlightSearchListner(new OnFightSearchListner() {
@Override
public void onSuccess(ArrayList<Quote> quoteList) {
if(quoteList!= null && quoteList.size() > 0) {
Bundle bundle = new Bundle();
bundle.putBoolean("FlightSearchStatus", true);
bundle.putInt("FlightSearchCount", quoteList.size());
//Reporting event
instance.onEvent("FlightSearchStatus", bundle);
}
adapter = new OneWayFlightAdapter(quoteList);
recyclerView.setAdapter(adapter);
}
@Override
public void OnFailure(Exception e) {
// not implemented yet.. will do later
Log.e(TAG, e.getMessage());
}
});
To Check Analysis on App Gallery Connect
1. On the left side panel, click on Huawei Analyze > Behaviour Analysis > Event Analysis.
Conclusion:
In this article, we learnt how to integrate Huawei app-messaging and analytics to report event in application.
Can we integrate push messages along with in-app messaging?
well explained, can we load gifs also?
These posts have shown the first few steps of developing a Unity game:
Unity Editor Installation and APK Packaging
How Can I Use the HUAWEI Game Service Demo Provided by Unity
Initializing a Huawei Game and Implementing HUAWEI ID Sign-in Using Unity
I tried to upload the packaged APK file to AppGallery Connect. Let’s see how it went.
Based on Unity documents, I first completed my game information in UDP, and uploaded its demo package. But the upload failed and UdpSdkNotDetectedError was displayed.
{
"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"
}
I asked Unity technical support for help, and they told me to also integrate the UDP SDK.
The UDP SDK is used for in-app purchases. You can learn more about it from this document:
https://docs.unity3d.com/Packages/[email protected]/manual/index.html
Integration of the UDP SDK
According to the Unity documents, there are three ways to integrate the UDP SDK:
Using Unity IAP (Unity IAP adds another layer to the UDP APIs.)
UDP is included in Unity IAP from version 1.22.0 to 1.23.5. If you use the Unity IAP package (1.22.0–1.23.5), do not install the UDP separately.
Using the UDP package
Using the UDP package and Unity IAP
The package of the Unity IAP 2.0.0 and later does not contain the UDP package. You need to download them both.
Latest version of Unity Asset Store (2020–11–24)
UDP version: 2.0.0
Unity IAP version: 2.2.2
Unity official documentation:
https://docs.unity3d.com/Packages/[email protected]/manual/index.html
https://distribute.dashboard.unity.com/udp/guideDoc/HUAWEI
Importing a UDP Package
If it’s your first time integrating the UDP SDK, just download the latest version of UDP package from Unity Asset Store.
Here’s the address:
https://assetstore.unity.com/packages/add-ons/services/billing/unity-distribution-portal-138507
Import the resource to Unity Editor.
If you see Unity Distribution Portal here, the resource has been imported.
Associating a Unity Project with a UDP Client ID
Document: https://docs.unity3d.com/Packages/[email protected]/manual/games-with-iap.html
Before you integrate Unity IAP, you need to associate your Unity project with a UDP client ID. Follow the instructions below.
Integrating the Unity IAP API.
Reference:
https://docs.unity3d.com/Packages/[email protected]/manual/games-with-iap.html
Before You Start
If you’re still confused by now, don’t worry, check the sample code provided by Unity. You can view it here after you downloaded the UDP package.
Integrating and Testing the StoreService.Initialize API
Integration
According to Unity, this API must be called before your game is released to other app stores using UDP.
I will continue with my earlier integrations, and here’s a few tips for you:
1. Add a button. Right-click HeaderPanel and choose UI > Button. Rename it Initialize.
2. Write code for the button.
Key points:
1) Add a namespace for UDP.
2) Declare the Initialize button, the callback listener of the API, and the boolean value.
C#:
private static InitListener m_InitListener=new InitListener();
// IAP initialized flag
private static bool m_Initialized;
private static Button initialize_button;
3) Capture the Initialize button in initUI().
C#:
initialize_button= GameObject.Find(“Initialize”).GetComponent<Button>();
4) Add the following code to private void initListeners():
C#:
initialize_button.onClick.AddListener(() =>
{
Show("starting initialize");
StoreService.Initialize(m_InitListener);
Show("initialize finished");
});
5) If you want the StoreService.Initialize API to be automatically called at app launch, add the highlighted code here:
C#:
void Start()
{
initUI();
initListeners();
// Call the Appinit method in your game code
appInit();
// Call the Initialize method in your game code
initialize();
}
private void initialize()
{
m_Initialized = false;
Debug.Log("Init button is clicked.");
Show("Initializing");
StoreService.Initialize(m_InitListener);
}
6) Edit the callback processing logic.
C#:
public class InitListener : IInitListener
{
public void OnInitialized(UserInfo userInfo)
{
Debug.Log("[Game]On Initialized suceeded");
Show("Initialize succeeded");
m_Initialized = true;
}
public void OnInitializeFailed(string message)
{
Debug.Log("[Game]OnInitializeFailed: " + message);
Show("Initialize Failed: " + message);
}
}
Packaging and Testing
The following information indicates that the API is called successfully.
Adding a Sandbox Test Account
If the following message is displayed, you need to add a sandbox account to check whether the IAP API is integrated successfully before app release.
Check this document:
https://docs.unity3d.com/Packages/[email protected]/manual/creating-a-game-on-udp.html
Make sure to click SAVE after adding the account.
The following information indicates that the API is called successfully.
Integrating and Testing the StoreService.QueryInventory API
API Functions
This API is used to query HUAWEI IAP for any missing transactions.
For consumables, if a product is purchased but not delivered, this API returns the product ID. Which means, it returns the consumable with a payment exception.
For non-consumables, this API returns all non-consumables that have been purchased by the player.
Integration
Similar to the integration of StoreService.Initialize.
Packaging and Testing
When calling this API, you can pass the product ID you want to query. If you pass one, you’ll see the corresponding information here.
After launching the app, you’ll see the following screen:
Creating a Product
To better test the IAP API, you can create a few products. Check this document:
https://docs.unity3d.com/Packages/c...#managing-in-app-purchases-on-the-udp-console
Here, I created two products.
Note: Currently, Unity IAP does not support subscriptions for games released on HUAWEI AppGallery.
Integrating and Testing the StoreService.Purchase API
Integration
Similar to the integration of StoreService.Initialize.
Packaging and TestingNon-consumables
StoreService.Purchase(“non_consumable_product01”, “payload”, m_PurchaseListener);
Here, non_consumable_product01 is a non-consumable I created in UDP.
After a successfull purchase is successful, call the API again. The following message is displayed.
Call StoreService.QueryInventory(productIds,m_PurchaseListener);.
Define productIds as follows:
List<string> productIds = new List<string> { “consumable_product01”, “non_consumable_product01” };
Now, you can see the information of the two products I created and the non-consumable I just purchased.
Consumables
After a consumable is purchased, it will be delivered and consumed.
If a consumable fails to be delivered after being purchased, you can call the StoreService.QueryInventory API to query its information, which is similar to HUAWEI IAP.
1) The consumable is not consumed after purchase.
Call this API:
StoreService.Purchase("non_consumable_product01", "payload", m_PurchaseListener);
A message is displayed, indicating that the product needs to be consumed before another purchase.
2) StoreService.QueryInventory(productIds,m_PurchaseListener);
Define productIds as follows:
C#:
List<string> productIds = new List<string> { "consumable_product01", "non_consumable_product01" };
The consumable is included in the purchased products that are returned.
3) Call this API to consume the product:
C#:
StoreService.ConsumePurchase(PurchaseInfo,IPurchaseListener)
According to the official document, PurchaseInfo is returned using the onPurchase method. You can obtain this method from the callback of StoreService.QueryInventory or StoreService.Purchase.
Here, I called the StoreService.QueryInventory API, obtained the consumable, and consumed it:
C#:
StoreService.ConsumePurchase(inventory.GetPurchaseInfo("consumable_product01"), this);
The following information indicates that the product is consumed.
Note:
After the consumption, if you call the StoreService.QueryInventory API again, you’ll see that there’s no consumable left. The query and redeliver process is complete.
Server APIs involved in Unity IAP
According to Unity, if the server APIs fail to receive the callback, no matter what the payment result is, from an app store, payment failure will be returned by UDP. Unity also provides some server APIs for you to integrate.
I’m not going to show you the demo test. You can try it on your own.
Payment Callback API
If you have your own game server, you can receive successful payment notifications sent by UDP.
For details, check this document:
https://docs.unity3d.com/Packages/c...ames-with-iap.html#game-client-implementation
Configure the callback URL here.
Order Query API
You can also send an HTTP GET request for order details and verify its information.
For details, check this document:
https://docs.unity3d.com/Packages/c...ames-with-iap.html#server-side-implementation
Very useful if you use unity.
Rebis said:
Very useful if you use unity.
Click to expand...
Click to collapse
Thank you for your liking appreciation.
f users have not installed GMS on their phones, they cannot directly sign in to your app using a Google account. In this case, you can let them sign in to your app in web mode by obtaining the access token for sign-in authentication from Google. The procedure is as follows:
Sign in to the Google Play Console, click Credentials, and create an OAuth 2.0 client ID with Type set to Web application.
{
"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"
}
Go to the settings page and find Client ID and Client secret on the right side of the page, which are needed for integrating Google sign-in. Add a URI of the page to be displayed after the web sign-in is complete to Authorized redirect URIs.
When users want to sign in with their Google accounts, the web page domain name that is https://accounts.google.com/o/oauth2/v2/auth, query should be opened. Add the following parameters to it.
client_id — Required — The client ID for your application. You can find this value in the API Console Credentials page.
redirect_uri — Required — Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in your client’s API Console Credentials page. If this value doesn’t match an authorized redirect URI for the provided client_id you will get a redirect_uri_mismatch error.
Note that the http or https scheme, case, and trailing slash (‘/’) must all match.
response_type — Required — Determines whether the Google OAuth 2.0 endpoint returns an authorization code.
Set the parameter value to code for web server applications.
scope — Required — A space-delimited list of scopes that identify the resources that your application could access on the user’s behalf. These values inform the consent screen that Google displays to the user.
Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there is an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.
We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization, you help users to more easily understand why your application needs the access it is requesting.
access_type — Recommended — Indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are online, which is the default value, and offline.
Set the value to offline if your application needs to refresh access tokens when the user is not present at the browser. This is the method of refreshing access tokens described later in this document. This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.
state — Recommended — Specifies any string value that your application uses to maintain state between your authorization request and the authorization server’s response. The server returns the exact value that you send as a name=value pair in the URL fragment identifier (#) of the redirect_uri after the user consents to or denies your application’s access request.
You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client’s state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery. See the OpenID Connect documentation for an example of how to create and confirm a state token.
include_granted_scopes — Optional — Enables applications to use incremental authorization to request access to additional scopes in context. If you set this parameter’s value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.
login_hint — Optional — If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.
Set the parameter value to an email address or sub identifier, which is equivalent to the user’s Google ID.
prompt — Optional — A space-delimited, case-sensitive list of prompts to present the user. If you don’t specify this parameter, the user will be prompted only the first time your project requests access.
Possible values are:
none Do not display any authentication or consent screens. Must not be specified with other values.
consent Prompt the user for consent.
select_account Prompt the user to select an account.
Examples
Code:
https://accounts.google.com/o/oauth2/v2/auth?
scope=profile&
access_type=offline&
include_granted_scopes=true&
response_type=code&
state=state_parameter_passthrough_value&
redirect_uri=https%3A//oauth2.example.com/code&
client_id=342746900306-vmpmbn8dgulp7eun1i8haiu86kocn8t6.apps.googleusercontent.com
redirect_uri is the URI we configured in step 2.
When the web page we generated in step 3 is opened, the Google account sign-in page is displayed. Once users are signed in, they will be redirected to the URI we set for redirect_uri. You should save the code value that clings to this domain name.
Example:
Code:
https://oauth2.example.com/code?
state=state_parameter_passthrough_value&
code=4%2FzAFyRfnDjPJKLRlkcZCedy-P6GpYbmAPpOvbmeUwXCfv0lXkUWjjHRXGtrwpoordursX2wfKShoGakKbLGzS4Ac&
scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile
&authuser=0
&prompt=none
In this case, the code value is as follows:
4%2FzAFyRfnDjPJKLRlkcZCedy-P6GpYbmAPpOvbmeUwXCfv0lXkUWjjHRXGtrwpoordursX2wfKShoGakKbLGzS4Ac
After obtaining the code value, send an HTTP request to https://oauth2.googleapis.com/token to obtain the value of access_token required for AppGallery Connect authentication.
The parameters are as follows.
client_id — The client ID obtained from the API Console Credentials page.
client_secret — The client secret obtained from the API Console Credentials page.
code — The authorization code returned from the initial request.
grant_type — As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code.
redirect_uri — One of the redirect URIs listed for your project in the API Console Credentials page for the given client_id.
Example:
Code:
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4%2FzAFyRfnDjPJKLRlkcZCedy-P6GpYbmAPpOvbmeUwXCfv0lXkUWjjHRXGtrwpoordursX2wfKShoGakKbLGzS4Ac
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https%3A//oauth2.example.com/code&
grant_type=authorization_code
The return result of the request carries the access_token you need.
Example of the return result:
JSON:
{
"access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in": 3920,
"token_type": "Bearer",
"scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
"refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}
Use the token to pass the AppGallery Connect authentication. Sample code
Java:
// accesstoken is the value of access_token obtained in the previous step.
AGConnectAuthCredential credential = GoogleAuthProvider.credentialWithToken(accesstoken);
AGConnectAuth.getInstance().signIn(credential)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
}
});
References
Create a client ID on Google Play Console
Sign in to AppGallery Connect with a Google account
Can we use both HMS and GMS in application?
Basavaraj.navi said:
Can we use both HMS and GMS in application?
Click to expand...
Click to collapse
You certainly can! there are lots of ways you could implement this https://stackoverflow.com/questions/59974428/have-both-gms-and-hms-in-the-project has some great examples on how you might check for which services to use on a specific device.
{
"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"
}
With the increasing popularity of the mobile Internet, mobile apps are now becoming an integral part of our daily lives and provide increasingly more diverse functions that bring many benefits to users. One such function is searching for Point of Interests (POIs) or places, such as banks and restaurants, in an app.
When a user searches for a POI in an app, besides general information about the POI, such as the name and location, they also expect to be shown other relevant details. For example, when searching for a POI in a taxi-hailing app, a user usually expects the app to display both the searched POI and other nearby POIs, so that the user can select the most convenient pick-up and drop-off point. When searching for a bank branch in a mobile banking app, a user usually wants the app to show both the searched bank branch and nearby POIs of a similar type and their details such as business hours, telephone numbers, and nearby roads.
However, showing POI details in an app is usually a challenge for developers of non-map-related apps, because it requires a large amount of detailed POI data that is generally hard to collect for most app developers. So, wouldn't it be great if there was a service which an app can use to provide users with information about POI (such as the business hours and ratings) when they search for different types of POIs (such as hotels, restaurants, and scenic spots) in the app?
Fortunately, HMS Core Site Kit provides a one-stop POI search service, which boasts more than 260 million POIs in over 200 countries and regions around the world. In addition, the service supports more than 70 languages, empowering users to search for places in their own native languages. The place detail search function in the kit allows an app to obtain information about a POI, such as the name, address, and longitude and latitude, based on the unique ID of the POI. For example, a user can search for nearby bank branches in a mobile banking app, and view information about each branch, such as their business hours and telephone numbers, or search for the location of a scenic spot and view information about nearby hotels and weather forecasts in a travel app, thanks to the place detail search function. The place detail search function can even be utilized by location-based games that can use the function to show in-game tasks and rankings of other players at a POI when a player searches for the POI in the game.
Th integration process for this kit is straightforward, which I'll demonstrate below.
Demo
Integration Procedure
PreparationsBefore getting started, you'll need to make some preparations, such as configuring your app information in AppGallery Connect, integrating the Site SDK, and configuring the obfuscation configuration file.
If you use Android Studio, you can integrate the SDK into your project via the Maven repository. The purpose of configuring the obfuscation configuration file is to prevent the SDK from being obfuscated.
You can follow instructions here to make relevant preparations. In this article, I won't be describing the preparation steps.
Developing Place Detail SearchAfter making relevant preparations, you will need to implement the place detail search function for obtaining POI details. The process is as follows:
1. Declare a SearchService object and use SearchServiceFactory to instantiate the object.
2. Create a DetailSearchRequest object and set relevant parameters.
The object will be used as the request body for searching for POI details. Relevant parameters are as follows:
siteId: ID of a POI. This parameter is mandatory.
language: language in which search results are displayed. English will be used if no language is specified, and if English is unavailable, the local language will be used.
children: indicates whether to return information about child nodes of the POI. The default value is false, indicating that child node information is not returned. If this parameter is set to true, all information about child nodes of the POI will be returned.
3. Create a SearchResultListener object to listen for the search result.
4. Use the created SearchService object to call the detailSearch() method and pass the created DetailSearchRequest and SearchResultListener objects to the method.
5. Obtain the DetailSearchResponse object using the created SearchResultListener object. You can obtain a Site object from the DetailSearchResponse object and then parse it to obtain the search results.
The sample code is as follows:
Code:
// Declare a SearchService object.
private SearchService searchService;
// Create a SearchService instance.
searchService = SearchServiceFactory.create(this, "
API key
");
// Create a request body.
DetailSearchRequest request = new DetailSearchRequest();
request.setSiteId("
C2B922CC4651907A1C463127836D3957
");
request.setLanguage("
fr
");
request.setChildren(
false
);
// Create a search result listener.
SearchResultListener<DetailSearchResponse> resultListener = new SearchResultListener<DetailSearchResponse>() {
// Return the search result when the search is successful.
@Override
public void onSearchResult(DetailSearchResponse result) {
Site site;
if (result == null || (site = result.getSite()) == null) {
return;
}
Log.i("TAG", String.format("siteId: '%s', name: %s\r\n", site.getSiteId(), site.getName()));
}
// Return the result code and description when a search exception occurs.
@Override
public void onSearchError(SearchStatus status) {
Log.i("TAG", "Error : " + status.getErrorCode() + " " + status.getErrorMessage());
}
};
// Call the place detail search API.
searchService.detailSearch(request, resultListener);
You have now completed the integration process and your app should be able to show users details about the POIs they search for.
Conclusion
Mobile apps are now an integral part of our daily life. To improve user experience and provide users with a more convenient experience, mobile apps are providing more and more functions such as POI search.
When searching for POIs in an app, besides general information such as the name and location of the POI, users usually expect to be shown other context-relevant information as well, such as business hours and similar POIs nearby. However, showing POI details in an app can be challenging for developers of non-map-related apps, because it requires a large amount of detailed POI data that is usually hard to collect for most app developers.
In this article, I demonstrated how I solved this challenge using the place detail search function, which allows my app to show POI details to users. The whole integration process is straightforward and cost-efficient, and is an effective way to show POI details to users.
Conventional pop-up ads and roll ads in apps not only frustrate users, but are a headache for advertisers. This is because on the one hand, advertising is expensive, but on the other hand, these ads do not necessarily reach their target audience. The emergence of personalized ads has proved a game changer.
To ensure ads are actually sent to their intended audience, publishers usually need to collect the personal data of users to determine their characteristics, hobbies, recent requirements, and more, and then push targeted ads in apps. Some users are unwilling to share privacy data to receive personalized ads. Therefore, if an app needs to collect, use, and share users' personal data for the purpose of personalized ads, valid consent from users must be obtained first.
HUAWEI Ads provides the capability of obtaining user consent. In countries/regions with strict privacy requirements, it is recommended that publishers access the personalized ad service through the HUAWEI Ads SDK and share personal data that has been collected and processed with HUAWEI Ads. HUAWEI Ads reserves the right to monitor the privacy and data compliance of publishers. By default, personalized ads are returned for ad requests to HUAWEI Ads, and the ads are filtered based on the user's previously collected data. HUAWEI Ads also supports ad request settings for non-personalized ads. For details, please refer to "Personalized Ads and Non-personalized Ads" in the HUAWEI Ads Privacy and Data Security Policies.
To obtain user consent, you can use the Consent SDK provided by HUAWEI Ads or the CMP that complies with IAB TCF v2.0. For details, see Integration with IAB TCF v2.0.
Let's see how the Consent SDK can be used to request user consent and how to request ads accordingly.
Development ProcedureTo begin with, you will need to integrate the HMS Core SDK and HUAWEI Ads SDK. For details, see the development guide.
Using the Consent SDK
1. Integrate the Consent SDK.
a. Configure the Maven repository address.
The code library configuration of Android Studio is different in versions earlier than Gradle 7.0, Gradle 7.0, and Gradle 7.1 and later versions. Select the corresponding configuration procedure based on your Gradle plugin version.
b. Add build dependencies to the app-level build.gradle file.
{
"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"
}
Replace {version} with the actual version number. For details about the version number, please refer to the version updates. The sample code is as follows:
Code:
dependencies {
implementation 'com.huawei.hms:ads-consent:3.4.54.300'
}
After completing all the preceding configurations, click
on the toolbar to synchronize the build.gradle file and download the dependencies.
2. Update the user consent status.
When using the Consent SDK, ensure that the Consent SDK obtains the latest information about the ad technology providers of HUAWEI Ads. If the list of ad technology providers changes after the user consent is obtained, the Consent SDK will automatically set the user consent status to UNKNOWN. This means that every time the app is launched, you should call the requestConsentUpdate() method to determine the user consent status. The sample code is as follows:
Code:
...
import com.huawei.hms.ads.consent.*;
...
public class ConsentActivity extends BaseActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Check the user consent status.
checkConsentStatus();
...
}
...
private void checkConsentStatus() {
...
Consent consentInfo = Consent.getInstance(this);
...
consentInfo.requestConsentUpdate(new ConsentUpdateListener() {
@Override
public void onSuccess(ConsentStatus consentStatus, boolean isNeedConsent, List<AdProvider> adProviders) {
// User consent status successfully updated.
...
}
@Override
public void onFail(String errorDescription) {
// Failed to update user consent status.
...
}
});
...
}
...
}
If the user consent status is successfully updated, the onSuccess() method of ConsentUpdateListener provides the updated ConsentStatus (specifies the consent status), isNeedConsent (specifies whether consent is required), and adProviders (specifies the list of ad technology providers).
3. Obtain user consent.
You need to obtain the consent (for example, in a dialog box) of a user and display a complete list of ad technology providers. The following example shows how to obtain user consent in a dialog box:
a. Collect consent in a dialog box.
The sample code is as follows:
Code:
...
import com.huawei.hms.ads.consent.*;
...
public class ConsentActivity extends BaseActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Check the user consent status.
checkConsentStatus();
...
}
...
private void checkConsentStatus() {
...
Consent consentInfo = Consent.getInstance(this);
...
consentInfo.requestConsentUpdate(new ConsentUpdateListener() {
@Override
public void onSuccess(ConsentStatus consentStatus, boolean isNeedConsent, List<AdProvider> adProviders) {
...
// The parameter indicating whether the consent is required is returned.
if (isNeedConsent) {
// If ConsentStatus is set to UNKNOWN, ask for user consent again.
if (consentStatus == ConsentStatus.UNKNOWN) {
...
showConsentDialog();
}
// If ConsentStatus is set to PERSONALIZED or NON_PERSONALIZED, no dialog box is displayed to ask for user consent.
else {
...
}
} else {
...
}
}
@Override
public void onFail(String errorDescription) {
...
}
});
...
}
...
private void showConsentDialog() {
// Start to process the consent dialog box.
ConsentDialog dialog = new ConsentDialog(this, mAdProviders);
dialog.setCallback(this);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
Sample dialog box
Note: This image is for reference only. Design the UI based on the privacy page.
More information will be displayed if users tap here.
Note: This image is for reference only. Design the UI based on the privacy page.
b. Display the list of ad technology providers.
Display the names of ad technology providers to the user and allow the user to access the privacy policies of the ad technology providers.
After a user taps here on the information screen, the list of ad technology providers should appear in a dialog box, as shown in the following figure.
Note: This image is for reference only. Design the UI based on the privacy page.
c. Set consent status.
After obtaining the user's consent, use the setConsentStatus() method to set their content status. The sample code is as follows:
Code:
Consent.getInstance(getApplicationContext()).setConsentStatus(ConsentStatus.PERSONALIZED);
d. Set the tag indicating whether a user is under the age of consent.
If you want to request ads for users under the age of consent, call setUnderAgeOfPromise to set the tag for such users before calling requestConsentUpdate().
Code:
// Set the tag indicating whether a user is under the age of consent.
Consent.getInstance(getApplicationContext()).setUnderAgeOfPromise(true);
If setUnderAgeOfPromise is set to true, the onFail (String errorDescription) method is called back each time requestConsentUpdate() is called, and the errorDescription parameter is provided. In this case, do not display the dialog box for obtaining consent. The value false indicates that a user has reached the age of consent.
4. Load ads according to user consent.
By default, the setNonPersonalizedAd method is not called for requesting ads. In this case, personalized and non-personalized ads are requested, so if a user has not selected a consent option, only non-personalized ads can be requested.
The parameter of the setNonPersonalizedAd method can be set to the following values:
ALLOW_ALL: personalized and non-personalized ads.
ALLOW_NON_PERSONALIZED: non-personalized ads.
The sample code is as follows:
Code:
// Set the parameter in setNonPersonalizedAd to ALLOW_NON_PERSONALIZED to request only non-personalized ads.
RequestOptions requestOptions = HwAds.getRequestOptions();
requestOptions = requestOptions.toBuilder().setNonPersonalizedAd(ALLOW_NON_PERSONALIZED).build();
HwAds.setRequestOptions(requestOptions);
AdParam adParam = new AdParam.Builder().build();
adView.loadAd(adParam);
Testing the Consent SDK
To simplify app testing, the Consent SDK provides debug options that you can set.
1. Call getTestDeviceId() to obtain the ID of your device.
The sample code is as follows:
Code:
String testDeviceId = Consent.getInstance(getApplicationContext()).getTestDeviceId();
2. Use the obtained device ID to add your device as a test device to the trustlist.
The sample code is as follows:
Code:
Consent.getInstance(getApplicationContext()).addTestDeviceId(testDeviceId);
3. Call setDebugNeedConsent to set whether consent is required.
The sample code is as follows:
Code:
// Require consent for debugging. In this case, the value of isNeedConsent returned by the ConsentUpdateListener method is true.
Consent.getInstance(getApplicationContext()).setDebugNeedConsent(DebugNeedConsent.DEBUG_NEED_CONSENT);
// Not to require consent for debugging. In this case, the value of isNeedConsent returned by the ConsentUpdateListener method is false.
Consent.getInstance(getApplicationContext()).setDebugNeedConsent(DebugNeedConsent.DEBUG_NOT_NEED_CONSENT);
After these steps are complete, the value of isNeedConsent will be returned based on your debug status when calls are made to update the consent status.
For more information about the Consent SDK, please refer to the sample code.
References
Ads Kit
Development Guide of Ads Kit