install the ionic plugin: @ionic-native/in-app-purchase-2
by npm install @ionic-native/in-app-purchase-2
Once installed, import it into the react component that is going to use it:
import { InAppPurchase2 as Store } from "@ionic-native/in-app-purchase-2";
You will need to register items in the App Store/Google play console that you want to display in the app. From there, copy the id of the subscriptions you want to add into your app and register them like so:
const registerItems = () => {
Store.register({
id: "Subscription ID",
type: Store.PAID_SUBSCRIPTION,
});
Store.refresh();
};
Once you have registered your subscriptions, we can now move on to handling a purchase. We can do that below:
const handlePurchase = async (id) => {
Store.order("Subscription ID").then(
(p) => {
// Processing purchase
},
(e) => {
// Purchase error
}
);
};
We then need to listen in and check if the donation was a success or if it was a failure. These events should most likely be run during the component mount or in useEffect. We can handling the events by:
const handleEvents = () => {
Store.when("product").cancelled(() => {
// The user cancelled the purchase
});
Store.when("product").error(() => {
// An error occured
});
Store.when("product").initiated(() => {
// The user clicked on the purchase button and the purchase is now process
});
Store.when("product").approved((product) => {
// The purchase was a success
product.verify();
}).verified((product) => {
// Purchase verified
product.finish();
});
};
Now that you have been able to get a subscription, we always want to check if the user is subscribed. And we can do so by checking it like this:
Store.when("subscription").updated((product) => {
if (product.owned) {
// User is subscribed, do something
} else {
// User is not subscribed, do something
}
});
That is the basic example. There is a lot more you can do, so check out the docs: In App Purchase 2 - Ionic Documentation