With the development of mobile Internet, in-app payment has become an important part of the digital economy. Users are increasingly pursuing a convenient payment experience, and the ability to purchase and subscribe provided by in-app payment services meets users' needs for quick and seamless payment, facilitates one-stop completion of transactions, and helps developers diversify their revenues.
HarmonyOS SDKIn-app payment services(IAP Kit) crafts a smooth and efficient in-app payment experience for users, while providing developers with a convenient and fast access guide. Developers are able to devote more energy to improving the quality and innovation of their core business, thus facilitating the realization and growth of business value.
By integrating the system-level APIs provided by the in-app payment service, developers can quickly deploy a fully functional payment platform that seamlessly implements in-app purchasing functionality. Users can easily purchase a range of virtual goods within the app, with a wide variety of categories including, but not limited to, consumables for one-time use, non-consumables for long-term use, auto-renewable subscriptions that provide ongoing value, and more. The focus of this article is to take developers through how to accessPurchase of expendable/non-expendable goods。
Scene Introduction
The in-app payment service allows users to purchase various types of virtual goods within the app, including consumable goods, non-consumable goods and auto-renewal subscriptions.
-Consumable goods: goods that are consumed after one use, and need to be purchased again as the use decreases. Example: game currency, game props, etc.
-Non-consumable goods: one-time purchase, permanent ownership, no need to consume. Example: extra game levels in games, premium memberships in apps with no time limit, etc.
-Auto-Renewal Subscription Goods: Users are allowed to access value-added features or content for a period of time after purchase, and at the end of the cycle, they can choose to auto-renew to purchase the next installment of the service. Example: video continuous monthly membership.
Purchase of consumable/non-consumable goods access process
Before accessing the ability to purchase consumable/non-consumable goods, you need to be in the HuaweiAppGallery ConnectnodeConfiguration Commodities, enter information such as product ID and product price. When a user initiates a purchase within the developer's app, the app needs to call thecreatePurchaseThe interface comes to pull up the IAP Kit cash register, which displays the name of the product, the price of the product and other information, and the user can complete the purchase of the product at the cash register.
development step
1. Determine whether the place of service where the currently logged-in Huawei account is located supports in-app payments.
Before using in-app payments, the app needs to send the IAP Kit thequeryEnvironmentStatusThe request is used to determine whether the place of service where the user's currently logged-in Huawei account is located is among the countries/regions supported by the IAP Kit for billing.
import { iap } from '@';
import { common } from '@';
import { BusinessError } from '@';
queryEnvironmentStatus() {
const context: = getContext(this) as ;
(context).then(() => {
// Request successful
('Succeeded in querying environment status.');
}).catch((err: BusinessError) => {
// Request Failed
(`Failed to query environment status. Code is ${}, message is ${}`);
});
}
}
2. Search for product information
pass (a bill or inspection etc)queryProductsto get the product information configured on AppGallery Connect. When initiating a request, you need to add the request parameterQueryProductsParameterThe product ID is carried in the productType, and its productType is specified according to the actual configuration.
When the interface request is successful, the IAP Kit will return the product informationProductThe list of products. The application can use information such as the price, name, and description of the item contained in the Product to show the user a list of items available for purchase.
import { iap } from '@';
import { BusinessError } from '@';
queryProducts() {
const queryProductParam: = {
// :Expendable commodities;
// :非Expendable commodities;
productType: ,
// The query must be for a product that the developer has specified in theAppGallery ConnectCommodities configured on the website
productIds: ['ohos_consume_001']
};
const context: = getContext(this) as ;
(context, queryProductParam).then((result) => {
// Request successful
('Succeeded in querying products.');
// Display product information
// ...
}).catch((err: BusinessError) => {
// Request Failed
(`Failed to query products. Code is ${}, message is ${}`);
});
}
3. Initiate a purchase
When a user initiates a purchase, the app can send the IAP Kit a message by sending thecreatePurchaserequest to pull up the IAP Kit cash register. To initiate the request, you need to add the request parameterPurchaseParameterCarry in the product ID that has been previously configured and validated on the Huawei AppGallery Connect website, and specify its productType according to the actual configuration.
When the user makes a successful purchase, the app receives aCreatePurchaseResultobject whosepurchaseDatafield includes information about the results of this purchase. See alsoSignature checking of returned resultsDecode and validate the signature, successful validation can get thePurchaseOrderPayloadof the JSON string.
When a user's purchase fails, it is necessary to target the code for the.PRODUCT_OWNEDcap (a poem).SYSTEM_ERRORscenarios, check if you need to make up the shipment to ensure that the entitlement is issued, see theEquity release。
import { iap } from '@';
import { BusinessError } from '@';
// JWTUtil is a custom class, see the Sample Code project.
import { JWTUtil } from '. /commom/JWTUtil'; // JWTUtil is a custom class, see the Sample Code project.
createPurchase() {
const createPurchaseParam: = {
// The purchased product must be the one that the developer has configured on the AppGallery Connect site
productId: 'ohos_consume_001',
// : Consumable product; // : Non-consumable product; // : Non-consumable product.
productId: 'ohos_consume_001', //: Non-consumable product; //: Non-consumable product; //: Non-consumable product.
productType.
}
const context: = getContext(this) as ;
(context, createPurchaseParam).then(async (result) => {
('Succeeded in creating purchase.'); }
const jwsPurchaseOrder: string = ().
const purchaseStr = (jwsPurchaseOrder);
// The PurchaseOrderPayload class needs to be customized, see PurchaseOrderPayload for information on what it contains.
const purchaseOrderPayload = (purchaseStr) as PurchaseOrderPayload; // Process the shipment.
// Processing the shipment
// ...
// After a successful shipment send a finishPurchase request to the IAP Kit to confirm the shipment and complete the purchase
// The finishPurchase request takes its parameters from purchaseOrderPayload.
// ...
}).catch((err: BusinessError) => {
// The request failed
(`Failed to create purchase. Code is ${}, message is ${}`);
if ( === .PRODUCT_OWNED || === .SYSTEM_ERROR) {
// See the entitlement release to check if a replacement shipment is needed to make sure the entitlement is released.
// ...
}
})
}
4. Complete the purchase
After the success of the decoding signature check, if it is empty, it means that the purchase is successful and the relevant rights can be issued. If the developer also accesses theServer-side critical event notificationIn order to avoid duplicate shipments, it is recommended to check whether this order has been shipped first, and then issue the relevant benefits if it has not been shipped. PurchaseOrderPayload and other information is recorded after successful shipment for subsequent checking whether the order has been shipped.
After successful shipment, the application needs to sendfinishPurchaseThe request confirms the shipment, which notifies the IAP server to update the shipment status of the product and completes the purchase process. When sending a finishPurchase request, you need to add the request parameterFinishPurchaseParameterThe IAP server carries the productType, purchaseToken, and purchaseOrderId from the PurchaseOrderPayload in the PurchaseOrderPayload. after the request is successful, the IAP server will mark the corresponding product as shipped.
For consumable products, after the application successfully executes finishPurchase, the IAP server will reset the corresponding product to the purchasable status, and the user can purchase the product again.
import { iap } from '@';
import { BusinessError } from '@';
/**
* Confirmation of shipment,Complete the purchase
*
* @param purchaseOrder Purchase data,Sourced from purchase requests
*/
finishPurchase(purchaseOrder: PurchaseOrderPayload) {
const finishPurchaseParam: = {
productType: ,
purchaseToken: ,
purchaseOrderId:
};
const context: = getContext(this) as ;
(context, finishPurchaseParam).then((result) => {
// Request successful
('Succeeded in finishing purchase.');
}).catch((err: BusinessError) => {
// Request Failed
(`Failed to finish purchase. Code is ${}, message is ${}`);
});
}
Learn more >>
interviewsIn-App Payment Service Alliance Official Website
gainAccess to purchase of consumable/non-consumable goods development guidance document
gainEquity Release Development Guidance Document