nativescript-iap
NativeScript 插件,用于实现应用内购买
npm i --save nativescript-iap

NativeScript 的应用内购买插件

安装

从您项目的根目录运行以下命令

ns plugin add nativescript-iap

配置

为了让应用内购买被插件识别,您必须在 Google/AppStore 端进行配置。

使用

设置钩子

在开始购买之前,您需要连接到 purchaseUpdated 事件。这样,在交易执行期间,您将收到有关交易状态的信息,并在交易完成时采取必要的行动。您可以将钩子设置一次作为全局处理程序来处理所有传入的购买。

import inAppPurchase, { PurchaseEventData } from "nativescript-iap";

inAppPurchase.on("purchaseUpdated", async (data: PurchaseEventData) => {
for (const transaction of data.transactions) {
switch (transaction.state) {
case TransactionState.purchasing:
// ...
break;
case TransactionState.purchased:
case TransactionState.restored:
// Delivering the content
break;
case TransactionState.deferred:
// ...
break;
case TransactionState.refunded:
// ...
break;
}

// You must finish transaction otherwise the purchase being refunded
await inAppPurchase.finishTransaction(transaction);
}
});

获取产品

要获取实际产品,请使用产品标识符数组(在 Google Play 中为产品 ID 调用 SKU)调用 getProducts

import inAppPurchase from "nativescript-iap";

const products = await inAppPurchase.getProducts(["your.product.id.1", "your.product.id.2"]);

购买产品

import inAppPurchase, { PurchaseError } from "nativescript-iap";

try {
await inAppPurchase.purchase(product);
} catch (error) {
if (error instanceof PurchaseError) {
switch (error.code) {
switch (error.code) {
case PurchaseErrorCode.canceled:
// ...
break;
case PurchaseErrorCode.productAlreadyOwned:
// ...
break;
case PurchaseErrorCode.productNotAvailable:
// ...
break;
case PurchaseErrorCode.userNotAuthorized: // On iOS only
// ...
break;
default: //Unknow error
// ...
break;
}
}
}

// Handle the error
}

恢复已购买的产品

import inAppPurchase from "nativescript-iap";
// All restored purchases will be handled by the "purchaseUpdated" hook.
await inAppPurchase.restorePurchases();

(仅限 ANDROID)消耗已购买的产品

import inAppPurchase from "nativescript-iap";

await inAppPurchase.consumePurchase(transaction);

显示价格同意对话框

import inAppPurchase from "nativescript-iap";

const products = await inAppPurchase.getProducts(["product_id_with_updated_price"]);

await inAppPurchase.showPriceConsent(product[0]);

(仅限 iOS)监听被撤销的家庭共享购买。

import inAppPurchase from "nativescript-iap";

inAppPurchase.on("productsRevoked", async (data: ProductsRevokedEventData) => {
data.productIds.foreach((productId) => {
// Notify user
});
});

API

InAppPurchase - 表示用于进行应用内购买的类。

Product - 表示有关产品信息。

ProductType - 枚举 表示产品类型。

PurchaseError - 表示在 purchase 方法中可能抛出的错误类。

PurchaseErrorCode - 枚举 表示 PurchaseError 的错误代码。

PurchaseEventData - 接口 表示 purchaseUpdated 事件的 数据。

SubscriptionPeriod - 枚举 表示订阅周期持续时间。

Transaction - 表示应用内购买交易。

TransactionState - 枚举 表示交易状态。