DEV Community

Arpit
Arpit

Posted on

Setup Cordova-plugin-purchase v13 in ionic

To begin, install Cordova-plugin-purchase v13 by using:

npm i cordova-plugin-purchase

Import the library:

import "cordova-plugin-purchase";

Then, access the class methods as follows:

const { store, ProductType, Platform } = CdvPurchase;

Alternatively, you can use:

CdvPurchase.Store;

Next, set the verbosity level for console logging:

store.verbosity = LogLevel.DEBUG; // Use LogLevel constants

Here are the available verbosity levels:

LogLevel.QUIET (0) to disable all logging (default)
LogLevel.ERROR (1) to display only error messages
LogLevel.WARNING (2) to show warnings and errors
LogLevel.INFO (3) to show informational messages
LogLevel.DEBUG (4) to enable internal debugging messages
Initialize the validator value using:

store.validator = yourValidatorMethodOrApiRoute;

Register your products:

store.register([
{
id: 'subscription1',
type: ProductType.PAID_SUBSCRIPTION,
platform: Platform.APPLE_APPSTORE,
},
{
id: 'subscription2',
type: ProductType.PAID_SUBSCRIPTION,
platform: Platform.GOOGLE_PLAY,
},
{
id: 'consumable1',
type: ProductType.CONSUMABLE,
platform: Platform.BRAINTREE,
},
]);

Set up an error callback function:

store.error(console.warn);

// OR

store.error(() => {
// Your error-handling code
});

Initialize the in-app purchase plugin:

store.initialize(); // Pass platforms if needed

Refresh product prices and purchase statuses:

store.update();

Replay user transactions (Apple AppStore requirement):

store.restorePurchases();

To display the subscription popup, use:

store.get("Your_subscription_id")?.getOffer()?.order();

If store.get("Your_subscription_id") is consistently undefined, use:

store.ready(() => {
store.when().productUpdated((product) => {
setCanBuy(true);
setStoreProductValue(store.get("Your_subscription_id"));
});
});

Here, upon store readiness, the productUpdated event callback is triggered when product details are successfully fetched or updated. The product details are stored in a state, and the subscription model is triggered using

StoreProductValue.getOffer().order()

Once the user initiates a transaction, the validator runs. You can handle the events using:

store.when().approved(async (transaction) => {
// Your code
transaction.verify();
}).verified((receipt) => {
if (Object.values(Subscription_Plans).includes(receipt?.id)) {
receipt.finish();
}
// Your code
});

Feel free to adapt these instructions to ensure smooth operation within your app.tsx file. This setup will enable the subscription model to run effectively.

Top comments (0)