目录

This section describes how to develop an app that connects to HUAWEI IAP, helping you quickly understand client APIs provided by HUAWEI IAP and their call method.

Checking the Support for HUAWEI IAP

Before using HUAWEI IAP on your app, send an isEnvReady request from your app to HUAWEI IAP to check whether the currently signed-in HUAWEI ID is located in a country or region where HUAWEI IAP is available.

If your app does not connect to the HUAWEI ID sign-in API, connect to this API to sign in.

Perform the following steps for your development:

Send an isEnvReady request and set two callback listeners to receive the request result.

● If the request result is Succeeded, your app will obtain an IsEnvReadyResult instance, indicating that the country or region where the currently signed-in HUAWEI ID is located supports HUAWEI IAP.

● If the request result is Failed, HUAWEI IAP will return an Exception object. If the object is IapApiException, use its getStatusCode() method to obtain the result code of the request.

If the result code is OrderStatusCode.ORDER_HWID_NOT_LOGIN (no HUAWEI ID signed in), use status in the IapApiException object to bring up the HUAWEI ID sign-in screen. Then, obtain the result in the onActivityResult method of Activity. Parse returnCode from the intent returned by onActivityResult. If returnCode is OrderStatusCode.SUCCESS, the country or region where the currently signed-in HUAWEI ID is located supports HUAWEI IAP. If returnCode is not OrderStatusCode.SUCCESS, an exception occurs.

  1. // To get the Activity instance that calls this API.
  2. Activity activity = getActivity();
  3. Task<IsEnvReadyResult> task = Iap.getIapClient(activity).isEnvReady();
  4. task.addOnSuccessListener(new OnSuccessListener<IsEnvReadyResult>() {
  5.    @Override
  6.    public void onSuccess(IsEnvReadyResult result) {
  7.        // Obtain the execution result.
  8.    }
  9. }).addOnFailureListener(new OnFailureListener() {
  10.    @Override
  11.    public void onFailure(Exception e) {
  12.        if (e instanceof IapApiException) {
  13.            IapApiException apiException = (IapApiException) e;
  14.            Status status = apiException.getStatus();
  15.            if (status.getStatusCode() == OrderStatusCode.ORDER_HWID_NOT_LOGIN) {
  16.                // Not logged in.
  17.                if (status.hasResolution()) {
  18.                    try {
  19.                        // 6666 is an int constant defined by the developer.
  20.                        status.startResolutionForResult(getActivity(), 6666);
  21.                    } catch (IntentSender.SendIntentException exp) {
  22.                    }
  23.                }
  24.            } else if (status.getStatusCode() == OrderStatusCode.ORDER_ACCOUNT_AREA_NOT_SUPPORTED) {
  25.                // The current region does not support HUAWEI IAP.
  26.            }
  27.        }
  28.    }
  29. });
  30. @Override
  31. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  32.    super.onActivityResult(requestCode, resultCode, data);
  33.    if (requestCode == 6666) {
  34.        if (data != null) {
  35.            // Obtain the execution result.
  36.            int returnCode = data.getIntExtra("returnCode", 1);
  37.        }
  38.    }
  39. }

Presenting Product Information

If you use in-app products configured in AppGallery Connect, you need to use the obtainProductInfo API of your app to obtain details of these products.

Perform the following steps for your development:

1. Construct a ProductInfoReq object, send an obtainProductInfo request, and set callback listeners OnSuccessListener and OnFailureListener to receive the request result. Transfer the product ID that has been defined and takes effect in AppGallery Connect to the ProductInfoReq object, and specify priceType for a product.

Note:
Only one type of products can be queried each time an obtainProductInfo request is sent.

2. If the request is successful, HUAWEI IAP will return a ProductInfoResult object. Using the getProductInfoList method of this object, your app can obtain the list of ProductInfo objects, each of which contains the information about a specific product, including the product price, name, and description. Based on the information, the list of products that are available for purchase can be presented to users.

  1. // Pass in the productId list of products to be queried.
  2. List<String> productIdList = new ArrayList<>();
  3. // The product ID is the same as that set by a developer when configuring product information in AppGallery Connect.
  4. productIdList.add("ConsumeProduct1001");
  5. ProductInfoReq req = new ProductInfoReq();
  6. // priceType: 0: consumable; 1: non-consumable; 2: auto-renewable subscription
  7. req.setPriceType(0);
  8. req.setProductIds(productIdList);
  9. // to call the obtainProductInfo API.
  10. // To get the Activity instance that calls this API.
  11. Activity activity = getActivity();
  12. Task<ProductInfoResult> task = Iap.getIapClient(activity).obtainProductInfo(req);
  13. task.addOnSuccessListener(new OnSuccessListener<ProductInfoResult>() {
  14.    @Override
  15.    public void onSuccess(ProductInfoResult result) {
  16.        // Obtain the result
  17.        List<ProductInfo> productList = result.getProductInfoList();
  18.    }
  19. }).addOnFailureListener(new OnFailureListener() {
  20.    @Override
  21.    public void onFailure(Exception e) {
  22.        if (e instanceof IapApiException) {
  23.            IapApiException apiException = (IapApiException)e;
  24.            int returnCode = apiException.getStatusCode();
  25.        } else {
  26.            // Other external errors
  27.        }
  28.    }
  29. });

Initiating a Purchase

AppGallery Connect allows for purchases of consumable and non-consumable products and also for subscriptions. Your app can initiate a purchase request through the createPurchaseIntent API. Perform the following steps for your development:

1. Construct a PurchaseIntentReq object to send a createPurchaseIntent request. Transfer the product ID that has been defined and takes effect in AppGallery Connect to the PurchaseIntentReq object.

If the request is successful, your app will receive a PurchaseIntentResult object. Its getStatus method returns a Status object. Your app will display the checkout page of HUAWEI IAP using the startResolutionForResult method of the Status object.

  1. // Constructs a PurchaseIntentReq object.
  2. PurchaseIntentReq req = new PurchaseIntentReq();
  3. // The product ID is the same as that set by a developer when configuring product information in AppGallery Connect.
  4. req.setProductId("CProduct1");
  5. // In-app product type contains:
  6. // priceType: 0: consumable; 1: non-consumable; 2: auto-renewable subscription
  7. req.setPriceType(0);
  8. req.setDeveloperPayload("test");
  9. // to call the createPurchaseIntent API.
  10. // To get the Activity instance that calls this API.
  11. final Activity activity = getActivity();
  12. Task<PurchaseIntentResult> task = Iap.getIapClient(activity).createPurchaseIntent(req);
  13. task.addOnSuccessListener(new OnSuccessListener<PurchaseIntentResult>() {
  14.    @Override
  15.    public void onSuccess(PurchaseIntentResult result) {
  16.        // Obtain the payment result.
  17.        Status status = result.getStatus();
  18.        if (status.hasResolution()) {
  19.            try {
  20.                // 6666 is an int constant defined by the developer.
  21.                status.startResolutionForResult(activity, 6666);
  22.            } catch (IntentSender.SendIntentException exp) {
  23.            }
  24.        }
  25.    }
  26. }).addOnFailureListener(new OnFailureListener() {
  27.    @Override
  28.    public void onFailure(Exception e) {
  29.        if (e instanceof IapApiException) {
  30.            IapApiException apiException = (IapApiException)e;
  31.            Status status = apiException.getStatus();
  32.            int returnCode = apiException.getStatusCode();
  33.        } else {
  34.            // Other external errors
  35.        }
  36.    }
  37. });

2. After your app opens the checkout page of HUAWEI IAP and the user completes the payment process (that is, successfully purchases a product or cancels the purchase), HUAWEI IAP will return the payment result to your app through onActivityResult. You can use the parsePurchaseResultInfoFromIntent method to obtain the PurchaseResultInfo object that contains the result information.

● If the purchase is successful, obtain the purchase data InAppPurchaseData and its signature data from the PurchaseResultInfo object. Use the public key allocated by AppGallery Connect to verify the signature. For more information on the verification method, please refer to Verifying the Signature in the Returned Result.

Note:
The HMS Core IAP SDK provides the auxiliary tool class InAppPurchaseData for parsing the InAppPurchaseData character string. You can also use this class to construct an InAppPurchaseData object and obtain related information from the InAppPurchaseData object.

● When a user purchases a consumable, if the following payment exception is returned, check whether the delivery is successful. For details, please refer to Redelivering a Consumable Product.

- Payment failure (OrderStatusCode.ORDER_STATE_FAILED, -1).

- A user has the product (OrderStatusCode.ORDER_PRODUCT_OWNED, 60051).

  1. @Override
  2. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  3.    super.onActivityResult(requestCode, resultCode, data);
  4.    if (requestCode == 6666) {
  5.        if (data == null) {
  6.            Log.e("onActivityResult", "data is null");
  7.            return;
  8.        }
  9.        PurchaseResultInfo purchaseResultInfo = Iap.getIapClient(this).parsePurchaseResultInfoFromIntent(data);
  10.        switch(purchaseResultInfo.getReturnCode()) {
  11.            case OrderStatusCode.ORDER_STATE_CANCEL:
  12.                // User cancel payment.
  13.                break;
  14.            case OrderStatusCode.ORDER_STATE_FAILED:
  15.            case OrderStatusCode.ORDER_PRODUCT_OWNED:
  16.                // to check if there exists undelivered products.
  17.                break;
  18.            case OrderStatusCode.ORDER_STATE_SUCCESS:
  19.                // pay success.
  20.                String inAppPurchaseData = purchaseResultInfo.getInAppPurchaseData();
  21.                String inAppPurchaseDataSignature = purchaseResultInfo.getInAppDataSignature();
  22.                // use the public key of your app to verify the signature.
  23.                // If ok, you can deliver your products.
  24.                // If the user purchased a consumable product, call the consumeOwnedPurchase API to consume it after successfully delivering the product.
  25.                break;
  26.            default:
  27.                break;
  28.        }
  29.        return;
  30.    }
  31. }

Confirming a Purchase

After a user pays for a purchase or subscription, your app checks whether the payment is successful based on the purchaseState field in InAppPurchaseData. If purchaseState is 0 (already paid), your app will deliver the purchased product or service to the user, then send a delivery confirmation request to HUAWEI IAP.

Note:
See InAppPurchaseData for the information contained in InAppPurchaseData.

1. For a consumable product, parse purchaseToken from InAppPurchaseData in JSON format to check the delivery status of the product.

After the product is successfully delivered and its purchaseToken is obtained, your app needs to use the consumeOwnedPurchase API to consume the product and instruct the Huawei IAP server to update the delivery status of the product. purchaseToken is transferred to the API call request. After the consumption is complete, the Huawei IAP server resets the product status to available for purchase. Then the product can be purchased again.

  1. // Constructs a ConsumeOwnedPurchaseReq object.
  2. String purchaseToken = "";
  3. try {
  4.    InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
  5.    purchaseToken = inAppPurchaseDataBean.getPurchaseToken();
  6. } catch (JSONException e) {
  7. }
  8. ConsumeOwnedPurchaseReq req = new ConsumeOwnedPurchaseReq();
  9. req.setPurchaseToken(purchaseToken);
  10. // to call the consumeOwnedPurchase API.
  11. // To get the Activity instance that calls this API.
  12. Activity activity = getActivity();
  13. Task<ConsumeOwnedPurchaseResult> task = Iap.getIapClient(activity).consumeOwnedPurchase(req);
  14. task.addOnSuccessListener(new OnSuccessListener<ConsumeOwnedPurchaseResult>() {
  15.    @Override
  16.    public void onSuccess(ConsumeOwnedPurchaseResult result) {
  17.        // Obtain the result
  18.    }
  19. }).addOnFailureListener(new OnFailureListener() {
  20.    @Override
  21.    public void onFailure(Exception e) {
  22.        if (e instanceof IapApiException) {
  23.            IapApiException apiException = (IapApiException)e;
  24.            Status status = apiException.getStatus();
  25.            int returnCode = apiException.getStatusCode();
  26.        } else {
  27.            // Other external errors
  28.        }
  29.    }
  30. });

2. For non-consumables, Huawei IAP server returns confirmed purchase data by default. You need to continuously provide corresponding product services for users after they successfully purchase the products. For details, please refer to Providing the Service of a Non-Consumable.

3. For details about how to confirm a subscription, please refer to Subscription Functions.

Redelivering a Consumable Product

If an exception (such as network error or process killing) occurs after a payment, your app will fail to detect whether the payment is successful. The purchased product may not be delivered as expected. HUAWEI IAP enables you to redeliver a consumable product. See the following figure for the redelivery process.

Perform the following steps for your development:

1. When error code -1 or 60051 is returned during app launch or purchase request, use obtainOwnedPurchases to obtain the purchase information about the consumables that have been purchased but not delivered. Specify priceType as 0 in OwnedPurchasesReq.

If this API is successfully called, HUAWEI IAP will return an OwnedPurchasesResult object, which contains the purchase data and signature data of all products purchased but not delivered. Use the public key allocated by AppGallery Connect to verify the signature. For more information about the verification method, please refer to Verifying the Signature in the Returned Result.

The data of each purchase is a character string in JSON format and contains the parameters listed in InAppPurchaseData. Parse the purchaseState field from the InAppPurchaseData character string. If purchaseState of a purchase is 0, the purchase is successful. Deliver the required product for this purchase again.

Note:
The HMS Core IAP SDK provides the auxiliary tool class InAppPurchaseData for parsing the InAppPurchaseData character string. You can also use this class to construct an InAppPurchaseData object and obtain related information from the InAppPurchaseData object.
  1. // Constructs a OwnedPurchasesReq object.
  2. OwnedPurchasesReq ownedPurchasesReq = new OwnedPurchasesReq();
  3. // In-app product type contains:
  4. // priceType: 0: consumable; 1: non-consumable; 2: auto-renewable subscription
  5. ownedPurchasesReq.setPriceType(0);
  6. // to call the obtainOwnedPurchases API
  7. // To get the Activity instance that calls this API.
  8. Activity activity = getActivity();
  9. Task<OwnedPurchasesResult> task = Iap.getIapClient(activity).obtainOwnedPurchases(ownedPurchasesReq);
  10. task.addOnSuccessListener(new OnSuccessListener<OwnedPurchasesResult>() {
  11.    @Override
  12.    public void onSuccess(OwnedPurchasesResult result) {
  13.        // Obtain the execution result.
  14.        if (result != null && result.getInAppPurchaseDataList() != null) {
  15.            for (int i = 0; i < result.getInAppPurchaseDataList().size(); i++) {
  16.                String inAppPurchaseData = result.getInAppPurchaseDataList().get(i);
  17.                String InAppSignature = result.getInAppSignature().get(i);
  18.                // use the payment public key to verify the signature of the inAppPurchaseData.
  19.                // if success.
  20.                try {
  21.                    InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
  22.                    int purchaseState = inAppPurchaseDataBean.getPurchaseState();
  23.                } catch (JSONException e) {
  24.                }
  25.            }
  26.        }
  27.    }
  28. }).addOnFailureListener(new OnFailureListener() {
  29.    @Override
  30.    public void onFailure(Exception e) {
  31.        if (e instanceof IapApiException) {
  32.            IapApiException apiException = (IapApiException)e;
  33.            Status status = apiException.getStatus();
  34.            int returnCode = apiException.getStatusCode();
  35.        } else {
  36.            // Other external errors
  37.        }
  38.    }
  39. });

2. Call the consumeOwnedPurchase API to consume a delivered product.

Conduct a delivery confirmation for all products queried through the obtainOwnedPurchases API. If a product is already delivered, call the consumeOwnedPurchase API to consume the product and instruct the Huawei IAP server to update the delivery status. After the consumption is complete, the Huawei IAP server resets the product status to available for purchase. Then the product can be purchased again.

Delivering a Non-Consumable Product

If your app provides non-consumable products for users, it can call the obtainOwnedPurchases API during app launch to obtain the data about non-consumable products that a user has purchased. For the data format, please refer to the description of InAppPurchaseData. If some purchase data is returned, confirm the purchaseState field of each purchase. If the value of purchaseState is 0, you need to deliver the product.

Perform the following steps for your development:

Call the obtainOwnedPurchases API to obtain the data of non-consumable products that a user has purchased.

Specify priceType as 1 in OwnedPurchasesReq. Parse purchaseState from the purchase data of a product to check the product purchase state and determine whether to deliver the product accordingly.

Note:
The HMS Core IAP SDK provides the auxiliary tool class InAppPurchaseData for parsing the InAppPurchaseData character string. You can also use this class to construct an InAppPurchaseData object and obtain related information from the InAppPurchaseData object.
  1. // Constructs a OwnedPurchasesReq object.
  2. OwnedPurchasesReq ownedPurchasesReq = new OwnedPurchasesReq();
  3. // In-app product type contains:
  4. // priceType: 0: consumable; 1: non-consumable; 2: auto-renewable subscription
  5. ownedPurchasesReq.setPriceType(1);
  6. // to call the obtainOwnedPurchases API
  7. // To get the Activity instance that calls this API.
  8. Activity activity = getActivity();
  9. Task<OwnedPurchasesResult> task = Iap.getIapClient(activity).obtainOwnedPurchases(ownedPurchasesReq);
  10. task.addOnSuccessListener(new OnSuccessListener<OwnedPurchasesResult>() {
  11.    @Override
  12.    public void onSuccess(OwnedPurchasesResult result) {
  13.        // Obtain the execution result.
  14.        if (result != null && result.getInAppPurchaseDataList() != null) {
  15.            for (int i = 0; i < result.getInAppPurchaseDataList().size(); i++) {
  16.                String inAppPurchaseData = result.getInAppPurchaseDataList().get(i);
  17.                String InAppSignature = result.getInAppSignature().get(i);
  18.                // use the payment public key to verify the signature of the inAppPurchaseData.
  19.                // if success.
  20.                try {
  21.                    InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
  22.                    int purchaseState = inAppPurchaseDataBean.getPurchaseState();
  23.                } catch (JSONException e) {
  24.                }
  25.            }
  26.        }
  27.    }
  28. }).addOnFailureListener(new OnFailureListener() {
  29.    @Override
  30.    public void onFailure(Exception e) {
  31.        if (e instanceof IapApiException) {
  32.            IapApiException apiException = (IapApiException)e;
  33.            Status status = apiException.getStatus();
  34.            int returnCode = apiException.getStatusCode();
  35.        } else {
  36.            // Other external errors
  37.        }
  38.    }
  39. });

(Optional) Viewing the Purchase History

Call the obtainOwnedPurchaseRecord API to obtain the data of all consumable products consumed by a user.

  1. // Constructs a OwnedPurchasesReq object.
  2. OwnedPurchasesReq req = new OwnedPurchasesReq();
  3. // In-app product type contains:
  4. // 0: consumable; 1: non-consumable; 2: auto-renewable subscription
  5. req.setPriceType(0);
  6. // to call the obtainOwnedPurchaseRecord API.
  7. // To get the Activity instance that calls this API.
  8. Activity activity = getActivity();
  9. Task<OwnedPurchasesResult> task = Iap.getIapClient(activity).obtainOwnedPurchaseRecord(req);
  10. task.addOnSuccessListener(new OnSuccessListener<OwnedPurchasesResult>() {
  11.    @Override
  12.    public void onSuccess(OwnedPurchasesResult result) {
  13.        // Obtain the execution result.
  14.    }
  15. }).addOnFailureListener(new OnFailureListener() {
  16.    @Override
  17.    public void onFailure(Exception e) {
  18.        if (e instanceof IapApiException) {
  19.            IapApiException apiException = (IapApiException)e;
  20.            int returnCode = apiException.getStatusCode();
  21.        } else {
  22.            // Other external errors
  23.        }
  24.    }
  25. });