import
{ iap }
from
'@kit.IAPKit'
;
import
{ BusinessError }
from
'@kit.BasicServicesKit'
;
/
/
JWTUtil为自定义类,可参见Sample Code工程。
import
{ JWTUtil }
from
'../commom/JWTUtil'
;
subscribe() {
const createPurchaseParam: iap.PurchaseParameter
=
{
/
/
购买的商品必须是开发者在AppGallery Connect网站配置的商品
productId:
'test001'
,
productType: iap.ProductType.AUTORENEWABLE
}
const context: common.UIAbilityContext
=
getContext(this) as common.UIAbilityContext;
iap.createPurchase(context, createPurchaseParam).then(async (result)
=
> {
console.info(
'Succeeded in creating purchase.'
);
const jwsSubscriptionStatus: string
=
JSON.parse(result.purchaseData).jwsSubscriptionStatus;
if
(!jwsSubscriptionStatus) {
return
;
}
const subscriptionStatus: string
=
JWTUtil.decodeJwtObj(jwsSubscriptionStatus);
if
(!subscriptionStatus) {
return
;
}
/
/
需自定义SubGroupStatusPayload类,包含的信息请参见SubGroupStatusPayload
const subGroupStatusPayload: SubGroupStatusPayload
=
JSON.parse(subscriptionStatus);
const lastSubscriptionStatus
=
subGroupStatusPayload.lastSubscriptionStatus;
if
(!lastSubscriptionStatus || !lastSubscriptionStatus.status) {
return
;
}
const purchaseOrderPayload
=
lastSubscriptionStatus.lastPurchaseOrder;
if
(purchaseOrderPayload
=
=
=
undefined) {
return
;
}
/
/
处理发货
/
/
...
/
/
发货成功后向IAP Kit发送finishPurchase请求,确认发货,完成购买
/
/
finishPurchase请求的参数来源于lastSubscriptionStatus.lastPurchaseOrder
/
/
发起finishPurchase请求
/
/
...
}).catch((err: BusinessError)
=
> {
/
/
请求失败
console.error(`Failed to create purchase. Code
is
${err.code}, message
is
${err.message}`);
if
(err.code
=
=
=
iap.IAPErrorCode.PRODUCT_OWNED || err.code
=
=
=
iap.IAPErrorCode.SYSTEM_ERROR) {
/
/
参见确保权益发放检查是否需要补发货,确保权益发放
/
/
...
}
})
}