Detailed explanation of Huawei's in app payment from scratch - product creation and test on the shelf

When users download apps in the application market and experience free basic functions and services, they can choose to pay by themselves to obtain and use the value-added services provided in the application - in APP purchases (IAP) is required for the completion of users' in APP purchases.

In app payment has rich usage scenarios and needs, including the purchase of equipment and virtual currency in game applications, subscription of members in video applications, one-time purchase of advanced services and functions in knowledge tool applications... In app payment has greatly broadened the profit model of mobile development and increased the flexibility of APP revenue.

In Huawei's mobile ecosystem, we provide developers with safe and easy-to-use basic development services for in app payment, help developers reduce costs and increase efficiency, and realize payment conversion and sustainable revenue. Developers can easily master the steps of Huawei's application generation and payment in the whole process of application generation and payment, so that they can easily master the steps of Huawei's in shelf application and payment management.

Launch of IAP and commodity management method

Enable service

1. Turn on the service switch

1.1. Sign in AppGallery Connect website , select "my project", find the corresponding project in the project list, and select the application to be opened in the application list under the project.

1.2. On the selected application page, click < my project >, enter the "API management" tab, and turn on the switch of the line in which the service needs to be opened.

*API Management: confirm and open the required service capability on this tab. It supports that a service has multiple API switches, which can individually control the opening or closing of each API, or open or close all APIs under the service with one key through the API master switch on the right side of the service.

2. Configure payment service parameters
2.1. Select [profit > in app payment service] in the navigation bar on the left side of the selected application page and click [settings].
If it is configured for the first time, the sign agreement pop-up box will pop up.

2.2. Click after "subscription notification address"“ ✔” Icon to configure the subscription notification address.

2.3. After configuration, click“ ✔”.

Create commodity and sandbox test

1. Create goods: global pricing, one version done
Log in to AppAallery Connect, select an application in the [my application] interface and enter the [operation] page.

*The data information is analog

On the left navigation bar of the [operation] page, select [product operation > commodity management], select [commodity list], and click [add commodity].

1.1 description of relevant parameters:
① Confirm the created commodity type: Huawei in app payment supports three commodity types:
Consumer goods: goods that can be consumed, such as gold coins, diamonds, coupons, etc. in game applications, which can be used to exchange and buy virtual services and goods in the application.
Non expendable goods: goods that are permanently used after purchase. For example, special levels in the game, unlimited course learning permission in educational applications, etc
Subscription type goods: that is, a predetermined payment method, which allows access to value-added products or content for a period of time after purchase, and automatically renews the purchase of services for the next period after the end of the cycle. For example, monthly members in audio and video applications and educational courses.
Check the commodity type according to the commodity attribute you need to add for further filling.

② Commodity ID: starts with upper and lower case letters and numbers, and consists of letters, numbers and underscores () And period (.) Composition, with a maximum of 148 characters. The commodity ID in an application cannot be repeated, cannot be modified after saving, and cannot be used again after deletion.

③ Language: click [manage language list] and check the language type to be supported
④ Commodity name: cannot be blank. The maximum number of characters is 55. Special characters are not supported|
⑤ Product introduction: cannot be blank, the maximum number of characters is 100, and special characters are not supported|
⑥ Commodity price: click "view and edit" to adapt the appropriate price for the commodity.

1.2 global oriented commodity information setting: if your application development is oriented to multiple countries around the world, there is no need to maintain and manage multiple regional versions.

Mu lt i language setting: when creating a product, check the country language to be supported in the < language > column, and enter the product name and information of the corresponding country language in the < product name > column.

Global real-time exchange rate pricing reference: for the price settings of different countries and regions, only one commodity price needs to be defined. The prices of different countries and regions will be calculated and displayed according to the local exchange rate to provide developers with local pricing basis. You can also customize the pricing of a single region.

After filling in the commodity information, click [edit price] to enter the commodity price editing interface.

According to the above operation steps, complete the creation of goods, return to the goods list page to edit the status of goods, and click < effective >, that is, the addition of goods is completed.  

Description of relevant parameters:

  • Common currency requirement country / region: integer or two decimal places are supported. If 1.34 is entered, 1.34 is selected by default as the input price of the commodity;
  • Countries / regions with special currency requirements:

-Only integer countries / regions are supported. Integer or rounding up is used as the input price. If 5.02 is entered, 6.00 is selected by default as the input price of the commodity;
-For countries / regions with only one-fifth as the minimum unit, integer or take the value meeting the one-fifth requirement upward as the input price. If 1.23 is entered, 1.40 is selected by default as the input price of the commodity.

1.3 product activation
Fill in the information and click [save] to return to the commodity list. The newly added commodity will be displayed in [invalid] status. Click [activate] to confirm that the commodity will take effect.

2. Client access, payment process development guide

2.1 judge whether intra app payment is supported

Before using intra app payment, your application needs to send to Huawei intra app payment isEnvReady Request to determine whether the service location of the user's currently logged in Huawei account is in the country / region where Huawei IAP supports settlement. If the application is not connected to the login interface of Huawei account, the login operation can be completed through this interface.

The development steps are as follows:

launch isEnvReady Request, and set two callback listeners to receive the result of the interface request.
• when the interface request is successful, your application will get a IsEnvReadyResult The instance object indicates that the service location of the Huawei account currently logged in by the user supports IAP.
• when the interface request fails, IAP will return an Exception object. If the object is IapApiException Object, you can use its getStatusCode() method to get the return code of this request.
When the return account is not logged in (OrderStatusCode.ORDER_HWID_NOT_LOGIN), you can use IapApiException The status in the object pulls up the login page of Huawei account, and then obtains the result information in the onActivityResult method of Activity. Resolve the returnCode from the intent returned by onActivityResult when returnCode = orderstatuscode ORDER_ STATE_ Success indicates that the service location of the current account supports IAP, while others indicate that the request is abnormal.
*Status does not support serialization. Please do not serialize the status object returned by IAP interface.

// Gets the Activity object of the calling interface
final Activity activity = getActivity();
Task<IsEnvReadyResult> task = Iap.getIapClient(activity).isEnvReady();
task.addOnSuccessListener(new OnSuccessListener<IsEnvReadyResult>() {
    @Override
    public void onSuccess(IsEnvReadyResult result) {
        // Get the result of the interface request
        int accountFlag = result.getAccountFlag();
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        if (e instanceof IapApiException) {
            IapApiException apiException = (IapApiException) e;
            Status status = apiException.getStatus();
            if (status.getStatusCode() == OrderStatusCode.ORDER_HWID_NOT_LOGIN) {
                // No login account
                if (status.hasResolution()) {
                    try {
                        // 6666 is your custom constant
                        // Launch the login page returned by IAP
                        status.startResolutionForResult(activity, 6666);
                    } catch (IntentSender.SendIntentException exp) {
                    }
                }
            } else if (status.getStatusCode() == OrderStatusCode.ORDER_ACCOUNT_AREA_NOT_SUPPORTED) {
                // The service location of the user's current login Huawei account is not in the country / region where Huawei IAP supports settlement
            }
        } else {
            // Other external errors
        }
    }
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 6666) {
        if (data != null) {
            // Use the parseRespCodeFromIntent method to obtain the interface request result
            int returnCode = IapClientHelper.parseRespCodeFromIntent(data);
            // Use the parseAccountFlagFromIntent method to obtain the account type returned by the interface
            int accountFlag = IapClientHelper.parseAccountFlagFromIntent(data);
        }
    }
}

2.2 display commodity information

After configuring the products on the Huawei AppGallery Connect website, they need to be used in your application obtainProductInfo Interface to get the details of such goods.

The development steps are as follows:

1. Build request parameters ProductInfoReq , initiate obtainProductInfo Request and set OnSuccessListener and OnFailureListener callback listeners to receive the results of interface requests. You need to ProductInfoReq Carry the product ID you have previously defined and effective on Huawei AppGallery Connect website, and specify its priceType according to the actually configured products.
*obtainProductInfo can only query one type of goods at a time.
2. When the interface request is successful, IAP will return a ProductInfoResult Object, your application can obtain the information of a single commodity through the getProductInfoList method of this object ProductInfo List of objects. You can use ProductInfo The object contains information such as commodity price, name and description, and shows the user a list of commodities available for purchase.

List<String> productIdList = new ArrayList<>();
// The products queried must be the products you configured on the AppGallery Connect website
productIdList.add("ConsumeProduct1001");
ProductInfoReq req = new ProductInfoReq();
// priceType: 0: consumer goods; 1: Non expendable goods; 2: Subscription products
req.setPriceType(0);
req.setProductIds(productIdList);
// Gets the Activity object of the calling interface
final Activity activity = getActivity();
// Call the obtainProductInfo interface to obtain the details of the products configured on the AppGallery Connect website
Task<ProductInfoResult> task = Iap.getIapClient(activity).obtainProductInfo(req);
task.addOnSuccessListener(new OnSuccessListener<ProductInfoResult>() {
    @Override
    public void onSuccess(ProductInfoResult result) {
        // Get the product details returned when the interface request is successful
        List<ProductInfo> productList = result.getProductInfoList();
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        if (e instanceof IapApiException) {
            IapApiException apiException = (IapApiException) e;
            int returnCode = apiException.getStatusCode();
        } else {
            // Other external errors
        }
    }
});

2.3 initiate purchase

The AppGallery Connect website supports hosted goods, including consumer goods, non consumer goods and subscription goods. Your app can be accessed via createPurchaseIntent The interface initiates a purchase request. The development steps are as follows:
1. Build request parameters PurchaseIntentReq , initiate createPurchaseIntent Request. You need to PurchaseIntentReq Carry the product ID you have previously defined and effective on AGC website. When the interface request is successful, you can get a PurchaseIntentResult Object whose getStatus method returns a Status object. Your application needs to start the Huawei IAP cashier through the startResolutionForResult method of the Status object.
*Status does not support serialization. Please do not serialize the status object returned by IAP interface.

// Construct a PurchaseIntentReq object
PurchaseIntentReq req = new PurchaseIntentReq();
// The products purchased through the createPurchaseIntent interface must be those configured on the AppGallery Connect website.
req.setProductId("CProduct1");
// priceType: 0: consumer goods; 1: Non expendable goods; 2: Subscription products
req.setPriceType(0);
req.setDeveloperPayload("test");
// Gets the Activity object of the calling interface
final Activity activity = getActivity();
// Call the createPurchaseIntent interface to create a managed goods order
Task<PurchaseIntentResult> task = Iap.getIapClient(activity).createPurchaseIntent(req);
task.addOnSuccessListener(new OnSuccessListener<PurchaseIntentResult>() {
    @Override
    public void onSuccess(PurchaseIntentResult result) {
        // Get the result of creating the order
        Status status = result.getStatus();
        if (status.hasResolution()) {
            try {
                // 6666 is your custom constant
                // Launch the cashier page returned by IAP
                status.startResolutionForResult(activity, 6666);
            } catch (IntentSender.SendIntentException exp) {
            }
        }
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        if (e instanceof IapApiException) {
            IapApiException apiException = (IapApiException) e;
            Status status = apiException.getStatus();
            int returnCode = apiException.getStatusCode();
        } else {
            // Other external errors
        }
    }
});

2. Pull up the cashier in your application and when the user completes the payment (successfully purchases goods or cancels the purchase), Huawei IAP will return the payment result to the application through onActivityResult. Available parsePurchaseResultInfoFromIntent Method to get the information containing the result PurchaseResultInfo Object.

• when users purchase successfully, they can PurchaseResultInfo Object InAppPurchaseData And its signature data, you need to use the public key allocated in Huawei AppGallery Connect for signature verification. For public key acquisition and verification methods, see Check and sign the returned results.
• when purchasing consumable goods, if the following payment exceptions are returned, you need to check whether there is a bill drop. For details, see Replenishment process of consumable goods.
• payment failed (OrderStatusCode.ORDER_STATE_FAILED)
• already own the product (OrderStatusCode.ORDER_PRODUCT_OWNED)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 6666) {
        if (data == null) {
            Log.e("onActivityResult", "data is null");
            return;
        }
        // Call the parsePurchaseResultInfoFromIntent method to parse the payment result data
        PurchaseResultInfo purchaseResultInfo = Iap.getIapClient(this).parsePurchaseResultInfoFromIntent(data);
        switch(purchaseResultInfo.getReturnCode()) {
            case OrderStatusCode.ORDER_STATE_CANCEL:
                // User cancel
                break;
            case OrderStatusCode.ORDER_STATE_FAILED:
            case OrderStatusCode.ORDER_PRODUCT_OWNED:
                // Check for undelivered items
                break;
            case OrderStatusCode.ORDER_STATE_SUCCESS:
                // Payment successful
                String inAppPurchaseData = purchaseResultInfo.getInAppPurchaseData();
                String inAppPurchaseDataSignature = purchaseResultInfo.getInAppDataSignature();
                // Verify the signature using your app's IAP public key
                // If the inspection is successful, the goods will be delivered
                // If the user purchases goods for expendable goods, you need to call the consumeOwnedPurchase interface after the shipment is successful.
                break;
            default:
                break;
        }
    }
}

2.4 confirmation of transactions

After the user completes a payment, you need to according to the purchase data InAppPurchaseData To determine whether the order has been successfully paid. If the purchaseState is paid (value is 0), you need to issue corresponding goods or provide corresponding services, and then you need to send a delivery confirmation request to Huawei IAP.

  • For consumer goods, you need to InAppPurchaseData The purchaseToken information is parsed from the JSON string to confirm the delivery status of the goods. After successfully shipping and recording the purchaseToken of the delivered goods, your application needs to use consumeOwnedPurchase The interface consumes the commodity to notify the payment server in Huawei's application to update the delivery status of the commodity. send out consumeOwnedPurchase Please carry the purchase token parameter in the request. After the application successfully executes consumption, the payment server in Huawei's application will reset the corresponding commodity to the purchasable state, and the user can purchase the commodity again.
// Construct ConsumeOwnedPurchaseReq object
ConsumeOwnedPurchaseReq req = new ConsumeOwnedPurchaseReq();
String purchaseToken = "";
try {
    // purchaseToken should be obtained from the purchase information InAppPurchaseData
    InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
    purchaseToken = inAppPurchaseDataBean.getPurchaseToken();
} catch (JSONException e) {
}
req.setPurchaseToken(purchaseToken);
// Gets the Activity object of the calling interface
final Activity activity = getActivity();
// After the consumable goods are delivered successfully, the consumeOwnedPurchase interface needs to be called for consumption
Task<ConsumeOwnedPurchaseResult> task = Iap.getIapClient(activity).consumeOwnedPurchase(req);
task.addOnSuccessListener(new OnSuccessListener<ConsumeOwnedPurchaseResult>() {
    @Override
    public void onSuccess(ConsumeOwnedPurchaseResult result) {
        // Get interface request result
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        if (e instanceof IapApiException) {
            IapApiException apiException = (IapApiException) e;
            Status status = apiException.getStatus();
            int returnCode = apiException.getStatusCode();
        } else {
            // Other external errors
        }
    }
});
  • For non consumer goods, the Huawei in app payment server returns the confirmed order data by default. After the user purchases successfully, there is no need to confirm the transaction. You need to continue to provide users with corresponding goods and services after successful purchase. For details, see Provide services corresponding to non expendable goods.
  • For subscription products, after the user purchases successfully, you do not need to perform additional transaction confirmation operations, but you need to continue to provide users with corresponding goods and services during the effective period of the subscription. For details, see Subscription specific function description - provide services corresponding to goods.

2.5 provide services corresponding to non expendable goods

If your application provides users with non consumable goods, you can use it when the application starts obtainOwnedPurchases Interface to obtain the purchase information of non expendable goods purchased by the user. For the format, see InAppPurchaseData . If the returned purchase information list is not empty, please confirm the purchaseState field of each purchase information. If purchaseState is 0, you need to provide corresponding goods and services.

The development steps are as follows:

1. Use obtainOwnedPurchases Get the information of non consumable goods purchased by the user.
2. Your application needs parameters in the request OwnedPurchasesReq The priceType of the query specified in is 1.
3. You can parse the purchaseState from each returned product information to judge the purchase status of the current product, which can be used as the shipping mark of your application.

// Construct an OwnedPurchasesReq object
OwnedPurchasesReq ownedPurchasesReq = new OwnedPurchasesReq();
// priceType: 1: non consumable goods
ownedPurchasesReq.setPriceType(1);
// Gets the Activity object of the calling interface
final Activity activity = getActivity();
// Call the obtainOwnedPurchases interface
Task<OwnedPurchasesResult> task = Iap.getIapClient(activity).obtainOwnedPurchases(ownedPurchasesReq);
task.addOnSuccessListener(new OnSuccessListener<OwnedPurchasesResult>() {
    @Override
    public void onSuccess(OwnedPurchasesResult result) {
        // Get interface request result
        if (result != null && result.getInAppPurchaseDataList() != null) {
            for (int i = 0; i < result.getInAppPurchaseDataList().size(); i++) {
                String inAppPurchaseData = result.getInAppPurchaseDataList().get(i);
                String inAppSignature = result.getInAppSignature().get(i);
                // You need to use your app's IAP public key to verify the signature of inAppPurchaseData
                // If the signature verification is successful, please check the payment status
                try {
                    InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
                    int purchaseState = inAppPurchaseDataBean.getPurchaseState();
                } catch (JSONException e) {
                }
            }
        }
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        if (e instanceof IapApiException) {
            IapApiException apiException = (IapApiException) e;
            Status status = apiException.getStatus();
            int returnCode = apiException.getStatusCode();
        } else {
            // Other external errors
        }
    }
});

3. Sandbox test: complete the end-to-end payment test without real payment

After adding goods, you can conduct end-to-end payment phase detection through sandbox test without real payment. Sandbox test steps are as follows:

3.1 configure sandbox test environment

·Set up test account.
Before testing, you need to add test accounts in the user and access in AppGallery Connect. These test accounts are real Huawei accounts. For details, see< Manage test accounts>.

*Note: it takes 30min~1h to take effect after the sandbox test account is added. When using, please check whether the current account supports sandbox testing.

·Configure sandbox test version.
If the application package to be tested has not been installed on AGC before, just ensure that the versionCode of the test package is greater than 0; If there is a version on the shelf, the version code of the test package needs to be greater than that of the version on the shelf.

3.2 test non subscription commodity payment

You can log in the configured test account on the device and install the application to be tested. When initiating the purchase of non subscription goods, Huawei IAP will detect that the user is a test user, skip the actual payment phase and pay directly.
Examples of effects are as follows:

3.3 renewal of test subscription products

The purchase process of subscription goods is similar to that of ordinary goods (non subscription), but there are other detailed scenarios of subscription, such as success or failure of renewal and the duration of renewal cycle. In order to help developers quickly test the subscription scenario of the application, the subscription renewal time in the sandbox environment will be faster than normal. The concept of "time machine" is introduced.
Time machine: it only refers to the renewal time of subscription goods and does not affect the effective time of subscription goods (for example, if the subscription period is 1 week and the goods are renewed after 3 minutes, the validity of subscription goods is extended by 1 week).
Examples of effects are as follows:

After completing the above steps, you can successfully create and test the products in the application. In the commodity management link, we will continue the operation steps such as modifying commodity information, activating invalid commodities and deleting commodities in the next period.
Huawei's in app payment also provides the ability of "zero drop order" order management and enhanced subscription service for revenue growth. We will also push you a detailed explanation later. Please look forward to it~

For more details, please stamp:

>>Official website of Huawei in app payment service
>>Get development guidance documents
>>Huawei mobile service open source warehouse address: GitHub,Gitee

Click the attention on the right side of the avatar in the upper right corner to learn about the latest technologies of Huawei mobile services for the first time~

Keywords: Android github gitee

Added by hothientuan on Tue, 08 Mar 2022 05:46:21 +0200