React Native In App Purchase : A Comprehensive Guide to Implementing In-App Purchases with React Native IAP for IOS





In-app purchases have emerged as a vital source of income for mobile apps, allowing developers to monetize their products while ensuring users enjoy a smooth purchasing process. React Native, a widely used framework for creating cross-platform mobile apps, provides strong support for implementing in-app purchases on both iOS and Android platforms. In this detailed blog post, we'll delve into the realm of React Native in-app purchases, addressing the basics, steps for implementation, recommended practices, and helpful tips for seamlessly integrating in-app purchasing features into your mobile apps.




Implementing In-App Purchase in React Native (IOS)

Incorporating in-app purchases into React Native entails a series of tasks, such as configuring essential libraries, managing user authentication, retrieving product details, and managing purchase transactions. Let's examine each of these steps thoroughly.


Setting up the Apple App Store Connect

Go to App Store Connect and log in with your Apple Developer account credentials.

If you haven't already created your app in App Store Connect, you'll need to do so. Click on the "My Apps" tab and then click the "+" button to create a new app. Follow the prompts to enter the necessary details about your app.

Once you've selected your app, you'll see a sidebar menu. Click on "In-App Purchases" under the "Features" section.

Click on the "+" button to add a new in-app purchase.

Choose the "Subscription" option from the list of in-app purchase types.

Configure Your Subscription like Subscription Group, Subscription Duration, Subscription Pricing, Subscription Display Name and Description and Free Trial and Introductory Offers

Enter localized display names, descriptions, and promotional images for each language and territory where your app is available.

If your app is not yet live on the App Store or if you've made changes to your subscription that require review, you'll need to submit it for review. Apple will review your subscription to ensure it complies with App Store guidelines.














Install React Native IAP

Install the React Native IAP library using npm or yarn

npm install react-native-iap --save


Product Listing and Verify Receipt


To implement in-app purchases in your React Native application using the React Native IAP library, you'll need to handle product listing and receipt verification. Below are the steps to achieve this:

Product listing involves fetching the available in-app purchase products from the respective app stores and displaying them in your app for users to browse and purchase. Here's how you can list products using React Native IAP.

Receipt verification ensures that the in-app purchases made by users are valid and not tampered with.


import React, { useState, useEffect, useContext } from "react";
import {
  initConnection,
  getSubscriptions,
  getPurchaseHistory,
  purchaseUpdatedListener,
  validateReceiptIos,
} from "react-native-iap";

const validateReceipt = async (receipt: any) => {
  const result = await validateReceiptIos({
    receiptBody: {
      "receipt-data": receipt,
      password: "k6524310m0f24807b7b04898f56c0aff",
    },
    isTest: false,
  })
    .catch(() => {})
    .then((receipt) => {
      console.log(receipt, "receipt");
    });
};

useEffect(() => {
  // setup({storekitMode:'STOREKIT2_MODE'})
  initConnection()
    .then(async (res) => {
      const subscription = await getSubscriptions({
        skus: ["64f1c1624dfedbe5b290e1e8", "64ffeccf8cc96aaa6cee6df8"],
      });

      const getpur = await getPurchaseHistory()
        .catch(() => {})
        .then((res) => {
          console.log(res, "res");
          if (res) {
            const receipt = res[res.length - 1]?.transactionReceipt;
            if (receipt) {
              validateReceipt(receipt);
            }
          }
        });
      //console.log('getpur',getpur)
    })
    .catch((error) => console.log(error));
}, []);

useEffect(() => {
  const purchaseUpdateSubscription = purchaseUpdatedListener(
    async (purchase) => {
      if (purchase) {
        const receipt = purchase?.transactionReceipt;
        if (receipt) {
          validateReceipt(receipt);
        }
        //await finishTransaction(purchase?.transactionId);
      }
    }
  );

  return () => {
    purchaseUpdateSubscription.remove();
  };
}, []);


Once you have the user's purchase history, you can validate the receipts using server-side validation or third-party services like Apple's App Store Receipts  Developer API.





Request Subscription

To request a subscription purchase in a React Native application using the React Native IAP library, you would typically implement a button or UI element that initiates the purchase process when pressed by the user. Here's a basic example of how you can request a subscription purchase



import {
  initConnection,
  getSubscriptions,
  requestSubscription,
  clearTransactionIOS,
  purchaseUpdatedListener,
} from "react-native-iap";

const submitPayment = async () => {
  await clearTransactionIOS();
  try {
    const result = await requestSubscription({
      sku: "64f1c1624dfedbe5b290e1e8",
      andDangerouslyFinishTransactionAutomaticallyIOS: false,
    });
  } catch (err: any) {
    console.log(err);
  }
};


Test Your Implementation


Run your app on a physical device or simulator and try purchasing the product you've set up in App Store Connect


Remember to handle edge cases, such as user cancelations, refunds, and ensuring that your app behaves correctly in offline scenarios or when the user is unable to complete a purchase. Also, ensure to handle the security aspect of in-app purchases to prevent unauthorized access or tampering.


To sum up, in-app purchases offer app developers a potent means to monetize their mobile apps while enhancing user satisfaction. With careful implementation in React Native and adherence to best practices, developers can craft a favorable and lucrative user experience that fosters revenue generation.

Happy Coding 😀

Previous Post Next Post

Contact Form