React-Native-IAP to Implement In App Purchase in React Native Apps

Learn via video courses
Topics Covered

Overview

In app purchases(IAP) lets users purchase products or product features within an app, like subscriptions, premium content, etc. It can make your app more profitable and engaging.

To add IAP to a React Native app, we need a package that supports both Android and iOS. We will use the react-native-iap package for React Native IAP, which supports different payment providers and methods. It also connects to the app stores and checks the receipts.

We will also use Firebase as our backend service to store user data and handle authentication, and Stripe as our payment gateway to process the payments and verify the receipts.

Prerequisites

Before we start coding our app, we need to have some prerequisites ready:

  1. A Firebase account and project. You can sign up for a free account at https://firebase.google.com/.
  2. A Stripe account and project. We will use Stripe to process the payments and verify the receipts in our app. You can sign up for a free account at https://stripe.com/.
  3. A Google Play Developer account and console. You can sign up for a developer account at https://play.google.com/apps/publish/.
  4. An Apple Developer account and an App Store Connect account. You can sign up for a developer account at https://developer.apple.com/ and an App Store Connect account at https://appstoreconnect.apple.com/.
  5. A code editor of your choice.
  6. Node.js and npm are installed on your machine. You can download them together at https://nodejs.org/en/download/.
  7. React Native CLI installed on your machine. You can install it by running npm install -g react-native-cli in your terminal.
  8. Android Studio installed on your machine. You can download it at https://developer.android.com/studio.
  9. Xcode installed on your machine (if you are using a Mac).
  10. A physical or virtual device to run and test your app.

Important Installations

Install the Following Package:

Visit React Native IAP for details regarding manual installations for Android and iOS.

After that, we need to install Firebase packages using npm:

Visit ReactNative - Firebase for a detailed guide to link your App with a Firebase account and use Authentication to sign in users with email&password/PhoneOTP/Google etc.

Finally, we need to install the Stripe package using npm:

Refer to ReactNative - Stripe for the Manual installation guide.

Now that we have installed all the important dependencies for our project, we can start coding our app!

Setting Up the Server

Before we code our app logic, we need to set up our server logic first.

We will use Firebase Cloud Functions as our serverless backend service to handle some tasks related to IAP functionality.

We will use Firebase Cloud Functions to do the following tasks:

  • Create Stripe customers when users sign up with Firebase Authentication.
  • Update Stripe customers when users change their email or password with Firebase Authentication.
  • Delete Stripe customers when users delete their accounts with Firebase Authentication.
  • Verify Stripe receipts when users purchase subscriptions with react-native-iap.
  • Update Firebase Firestore when users purchase or cancel subscriptions with react-native-iap.
  • Send push notifications when users purchase or cancel subscriptions with react-native-iap.

To set up our Firebase Cloud Functions, we need to do the following steps:

  • Install Firebase CLI on our machines. Firebase CLI is a command-line tool that allows us to interact with Firebase services. We can install it by running npm install -g firebase-tools in our terminal.
  • Initialize Firebase Cloud Functions in our project folder. We can do this by running Firebase init functions in our terminal. This command will create a new folder called functions with all the necessary files and folders for our Cloud Functions. It will also ask us some questions to configure our Cloud Functions, such as which Firebase project to use, which language to use (JavaScript or TypeScript), etc.

We can choose the default options for most of the questions, except for the following ones:

  • Do you want to use ESLint to catch probable bugs and enforce style? (y/N) -> y.
  • Do you want to install dependencies with npm now? (Y/n) -> Y
  • Install the Stripe Node.js library in our functions folder. We can do this by running npm install stripe --save in our terminal. This command will install the Stripe Node.js library in our node_modules folder and update our package.json file accordingly.
  • Enable billing for our Firebase project. We need to enable billing for our Firebase project to use Firebase Cloud Functions and Stripe. We can do this by following the instructions at https://firebase.google.com/docs/functions/manage-functions#set_up_billing.
  • Enable Google Cloud Pub/Sub API for our Firebase project. We need to enable Google Cloud Pub/Sub API for our Firebase project to use push notifications with react-native-iap. We can do this by following the instructions at https://firebase.google.com/docs/functions/manage-functions#enable_apis.

Now that we have set up our Firebase Cloud Functions, we can start coding our functions.

We will use the following code template for each function:

We will replace the functionName, triggerType, onTriggerEvent, eventData, context, and function logic with the appropriate values for each function.

We will also add some comments to explain the function logic. Here is the code for each function:

Create Stripe Customers When Users Sign Up with Firebase Authentication:

Update Stripe Customers When Users Change Their Email or Password with Firebase Authentication:

Delete Stripe Customers When Users Delete Their Accounts with Firebase Authentication:

Verify Stripe Receipts When Users Purchase Subscriptions with React Native IAP:

Update Firebase Firestore When Users Purchase or Cancel Subscriptions with React Native IAP:

Send Push Notifications When Users Purchase or Cancel Subscriptions with React Native IAP:

In-App Purchases for Android

Subscription

To set up and implement subscription products for Android users, we need to take the following steps:

  1. Create subscription products on Google Play Console.
  2. Connect our app with Google Play Billing Library.
  3. Connect our app with react-native-iap.

Create subscription products in Google Play Console:

To create subscription products in Google Play Console, we need to do the following steps:

  • Sign in to Google Play Console with our Google Play Developer account at https://play.google.com/apps/publish/.
  • Create a new app or select an existing app from the dashboard.
  • Go to Monetize > In-app products > Subscriptions from the left menu.
  • Click on the Create subscription button at the top right corner.
  • Enter a unique product ID for each subscription product. The product ID should follow the format of com.example.appname.period, where com.example.appname is our app’s package name and the period is either monthly or yearly. For example, com.example.RNInAppPurchase.monthly and com.example.RNInAppPurchase.yearly.
  • Enter a title and a description for each subscription product. The title and description should be clear and concise, and explain what the user will get by subscribing to the product. For example, “Monthly Plan” and “Access all content for one month” or “Yearly Plan” and “Access all content for one year”.
  • Enter a price for each subscription product.
  • Choose a billing period for each subscription product. For example, monthly for a monthly plan and yearly for a yearly plan.
  • Choose a free trial period for each subscription product (optional).
  • Choose an introductory price for each subscription product (optional).
  • Choose a grace period for each subscription product (optional).
  • Choose an account hold option for each subscription product (optional). The account hold option allows us to pause users’ access to our product until they fix their payment issues. We can choose either on or off as our account hold option.
  • Choose a restore option for each subscription product (optional). The restore option allows us to resume users’ access to our product after they fix their payment issues.
  • Click on the Save draft button at the bottom right corner.
  • Repeat these steps for each subscription product that we want to create.

After we have created all our subscription products, we need to activate them by clicking on the Activate button at the top right corner. We also need to upload and publish our app on Google Play by following the instructions at https://support.google.com/googleplay/android-developer/answer/113469?hl=en.

Connect our app with Google Play Billing Library:

To connect our app with Google Play Billing Library, we need to do the following steps:

  • Add Google Play Billing Library dependency in our app/build.gradle file. We need to add the following line under the dependencies section:

  • Add Google Play Billing permission in our AndroidManifest.xml file. We need to add the following line under the manifest tag:

Connect our app with react-native-iap:

To connect our app with React Native IAP, we need to do the following steps:

  • Import the react-native-iap module in our App.tsx file. We need to add the following line at the top of our App.tsx file:

  • Initialize the react-native-iap module in our App.tsx file. We need to add the following code snippet inside the useEffect hook in our App.tsx file:

    We can now do something with the products array, such as storing it in a state variable or displaying it in a UI component.

  • Purchase a subscription product with react-native-iap module:

    We need to add the following code snippet inside a button onPress handler or a similar event handler in our App.tsx file:

    We can then call the above function inside a button onPress handler or a similar event handler with the desired product ID as an argument.

    For example:

    This code snippet will render a button that will call the purchaseSubscription function with the monthly plan product ID when pressed.

  • Listen to purchase updates and errors with the react-native-iap module. We need to add the following code snippet inside the useEffect hook in our App.tsx file:

    This way, we can listen to and handle any purchase updates and errors in our app.

Notifications

To set up and implement push notifications for Android users, we need to take the following steps:

  • Create a Firebase Cloud Messaging project and service account.
  • Connect our app with Firebase Cloud Messaging SDK.
  • Connect our app with react-native-push-notification.

To create a Firebase Cloud Messaging project and service account, we need to do the following steps:

  1. Sign in to Firebase Console with our Firebase account at https://console.firebase.google.com/.
  2. Create a new project or select an existing project from the dashboard.
  3. Go to Project settings > Cloud Messaging from the left menu.
  4. Copy the Server key and the Sender ID from the General tab. We will need them later for configuring our app and our server.
  5. Click on the Generate Key button under the Service Accounts tab. This will generate a new service account key file and download it to our machine. We will need this file later for authenticating our server with FCM.

To connect our app with Firebase Cloud Messaging SDK, we need to do the following steps:

  • Add Firebase Cloud Messaging dependency in our app/build.gradle file. We need to add the following line under the dependencies section:

  • Add Google Services plugin in our app/build.gradle file. We need to add the following lines at the bottom of our app/build.gradle file:

  • Add Google Services classpath in our Android/build.gradle file. We need to add the following line under the dependencies section:

  • Add the google-services.json file in our Android/app folder. We need to download the google-services.json file from Firebase Console by following the instructions at https://firebase.google.com/docs/android/setup#register-app.

    We need to make sure that the package name in the google-services.json file matches the one in our AndroidManifest.xml file.

  • Import the @react-native-firebase/messaging module in our App.tsx file. We need to add the following line at the top of our App.tsx file:

    We can use this variable to access all the methods and properties of the @react-native-firebase/messaging module.

  • Request permission for push notifications in our App.tsx file. We need to add the following code snippet inside the useEffect hook in our App.tsx file:

  • Get a device token for push notifications in our App.tsx file. We need to add the following code snippet inside the useEffect hook in our App.tsx file:

  • Handle incoming messages and notifications in our App.tsx file. We need to add the following code snippet inside the useEffect hook in our App.tsx file:

License Testers

To set up and implement license testers for Android users, we need to take the following steps:

  • Add license testers in Google Play Console.
  • Enable license testing in our app.

Add license testers in Google Play Console:

  1. Sign in to Google Play Console with our Google Play Developer account at https://play.google.com/apps/publish/.
  2. Select our app from the dashboard.
  3. Go to Development Tools> License testing from the left menu.
  4. Enter the email addresses of the users who we want to add as license testers in the License testers box. We can enter multiple email addresses separated by commas or new lines. For example, tester1@example.com, tester2@example.com.
  5. Click on the Save Changes button in the bottom right corner.

After we have added our license testers, they will be able to test our app and its in-app products without being charged.

We need to make sure that our license testers use the same email addresses that we have added in the Google Play Console when they sign in to Google Play on their devices.

We also need to make sure that our app is uploaded and published on Google Play before we can test it with our license testers.

Enable license testing in our app:

  • Add a debug flag in our App.tsx file. We need to add the following line at the top of our App.tsx file:

    We need to make sure that we set this flag to true when we want to test our app with license testers and set it to false when we want to release our app to the public.

  • Pass the debug flag to the react-native-iap module in our App.tsx file. We need to add the following code snippet inside the useEffect hook in our App.tsx file:

In-App Purchases for iOS

Subscription

To set up and implement subscription products for iOS users, we need to do the following steps:

  • Create subscription products in App Store Connect.
  • Connect our app with the StoreKit framework.
  • Connect our app with react-native-iap.

To create subscription products in App Store Connect, we need to do the following steps:

  1. Sign in to App Store Connect with our Apple Developer account at https://appstoreconnect.apple.com/.
  2. Create a new app or select an existing app from the dashboard.
  3. Go to In-App Purchases > Manage from the left menu.
  4. Click on the Create button in the top right corner.
  5. Choose Auto-Renewable Subscription as the type of in-app purchase and click on the Create button.
  6. Enter a reference name and a product ID for each subscription product.Product ID should look like com.example.RNInAppPurchase.monthly or com.example.RNInAppPurchase.yearly.
  7. Click on the Create button at the bottom right corner.
  8. Enter a display name and a description for each subscription product. The display name and description should be clear and concise, and explain what the user will get by subscribing to the product. For example, “Monthly Plan” and “Access all content for one month” or “Yearly Plan” and “Access all content for one year”.
  9. Choose a subscription group for each subscription product. A subscription group is a collection of subscription products that are related or offer similar features or content. We can create a new subscription group or choose an existing one from the dropdown menu.
  10. Choose a subscription duration for each subscription product. The subscription duration should match the product ID and the description of the product. We can choose either one month or one year as our subscription duration. For example, one month for a monthly plan and one year for a yearly plan.
  11. Choose a pricing and availability option for each subscription product. The pricing and availability option allows us to set the price and availability date for each subscription product. We can choose either Set Price or Use Existing Price Tier as our pricing option.
  12. Choose an introductory offer for each subscription product (optional).
  13. Choose an in-app purchase display order for each subscription product (optional).
  14. Click on the Save button in the top right corner.
  15. Repeat these steps for each subscription product that we want to create.

After we have created all our subscription products, we need to submit them for review by clicking on the Submit for Review button at the top right corner. We also need to upload and publish our app on Apple App Store by following the instructions at https://developer.apple.com/app-store/submissions/.

To connect our app with a StoreKit framework, we need to take the following steps:

  • Add a StoreKit framework dependency to our Podfile file. We need to add the following line under the target section:

    This line will add the StoreKit framework as a dependency for our app. We need to make sure that this line is inside the target ‘RNInAppPurchase’ do section.

    We also need to install pods after adding this line by running pod installs in our terminal.

  • Add StoreKit capability in Xcode. We need to open Xcode and select our project from the left panel.

    1. We need to go to the Signing & Capabilities tab from the top panel.
    2. We need to click on + Capability button at the top left corner.
    3. We need to select In-App Purchase from the list of capabilities.

    This will add StoreKit capability to our project.

To connect our app with React Native IAP, we need to do the same steps as we did for Android users

  1. Import the react-native-iap module in our App.tsx file.
  2. Initialize the react-native-iap module in our App.tsx file.
  3. Purchase a subscription product with the react-native-iap module in our App.tsx file.
  4. Listen to purchase updates and errors with the react-native-iap module in our App.tsx file.

The only difference is that we don’t need to pass any debug flag to the react-native-iap module for iOS users.

Instead, we can use sandbox testers to test our app and its in-app products without being charged.

Notifications

To set up and implement push notifications for iOS users, we need to do the following steps:

  • Create an Apple Push Notification service (APN) key and certificate.
  • Connect our app with Firebase Cloud Messaging SDK.
  • Connect our app with react-native-push-notification.

To create an APN key and certificate, we need to do the following steps:

  1. Sign in to the Apple Developer Portal with our Apple Developer account at https://developer.apple.com/.
  2. Go to Certificates, Identifiers & Profiles from the left menu.
  3. Go to Keys from the left menu.
  4. Click on the + button at the top right corner.
  5. Enter a name for our key and check the box for Apple Push Notifications service (APNs).
  6. Click on the Continue button at the bottom right corner.
  7. Click on the Register button at the bottom right corner.
  8. Click on the Download button at the bottom right corner. This will download a .p8 file containing our key to our machine. We will need this file later for configuring our server with FCM.
  9. Click on the Done button at the bottom right corner.
  10. Go to Identifiers from the left menu.
  11. Select our app ID from the list of identifiers or create a new one if we don’t have one already.
  12. Check the box for Push Notifications under the Capabilities section.
  13. Click on the Edit button under the Push Notifications section.
  14. Click on the Create Certificate button under the Production SSL Certificate section.
  15. Follow the instructions to create a certificate signing request (CSR) file on our machine and upload it to the Apple Developer Portal.
  16. Click on the Continue button at the bottom right corner.
  17. Click on the Download button at the bottom right corner. This will download a .cer file containing our certificate to our machine. We will need this file later for configuring our app with Xcode.
  18. Click on the Done button at the bottom right corner.

After we have created our APNs key and certificate, we need to upload them to Firebase Console by following the instructions at https://firebase.google.com/docs/cloud-messaging/ios/certs.

To connect our app with Firebase Cloud Messaging SDK, we need to do the same steps as we did for Android users:

  1. Add Firebase Cloud Messaging dependency in our Podfile file.
  2. Add a Google Services plugin to our app/build.gradle file.
  3. Add Google Services classpath in our Android/build.gradle file.
  4. Add the google-services.json file in our Android/app folder.
  5. Import the @react-native-firebase/messaging module in our App.tsx file.
  6. Request permission for push notifications in our App.tsx file.
  7. Get a device token for push notifications in our App.tsx file.
  8. Handle incoming messages and notifications in our App.tsx file.

The only difference is that we don’t need to add Google Play Billing permission in our AndroidManifest.xml file for iOS users.

Instead, we need to add a Push Notifications capability in Xcode.

We can follow the instructions at https://rnfirebase.io/messaging/usage/ios-setup for more details on how to connect our app with Firebase Cloud Messaging SDK for iOS users.

To connect our app with react-native-push-notification, we need to do the same steps as we did for Android users:

Import the react-native-push-notification module in our App.tsx file.

We don’t need to pass any debug flag to the react-native-iap module for iOS users.

Instead, we can use sandbox testers to test our app and its in-app products without being charged.

Sandbox Testers

To set up and implement sandbox testers for iOS users, we need to do the following steps:

  • Add sandbox testers in App Store Connect.
  • Enable sandbox testing in our app.

To add sandbox testers in App Store Connect, we need to do the following steps:

  1. Sign in to App Store Connect with our Apple Developer account at https://appstoreconnect.apple.com/.
  2. Go to Users and Access from the left menu.
  3. Go to Sandbox Testers from the left menu.
  4. Click on + button at the top right corner.
  5. Enter the email address, password, first name, last name, and date of birth for each sandbox tester. The email address should be valid but not associated with any existing Apple ID. The password should meet the Apple ID password requirements. The first name, last name, and date of birth can be any value. For example, tester1@example.com, Password123!, John, Doe, 01/01/2000.
  6. Click on the Save button at the bottom right corner.
  7. Repeat these steps for each sandbox tester that we want to create.

After we have added our sandbox testers, they will be able to test our app and its in-app products without being charged.

We need to make sure that our sandbox testers use the same email addresses and passwords that we have added in App Store Connect when they sign in to App Store on their devices. We also need to make sure that our app is uploaded and published on the Apple App Store before we can test it with our sandbox testers.

Enable sandbox testing in our app:

To enable sandbox testing in our app, we don’t need to do any extra steps.

  1. We just need to sign out of any existing Apple ID on our devices and sign in with one of our sandbox tester accounts.
  2. We also need to make sure that we set the debug flag to false when we want to test our app with sandbox testers.
  3. When we launch our app and try to purchase a subscription product, we will see a dialog box that says “Environment: Sandbox”.
  4. We can then enter the password of our sandbox tester account and proceed with the purchase.

We can then test and verify our app logic and UI for our subscription products using different scenarios.

Conclusion

In this article, we have learned how to set up and implement IAP in React Native for both Android and iOS users using the react-native-iap library.

We have covered the following topics:

  • Subscription
  • Notifications
  • License testers (Android)
  • Sandbox testers (iOS)
  • We have also learned how to use different services and frameworks such as Google Play Console, Google Play Billing Library, Firebase Cloud Messaging, App Store Connect, StoreKit framework, and Apple Push Notification service.

We hope that this article has been helpful and informative for you.

If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

FAQs

Q. How does the verification of Stripe receipts work?

A. The verification of Stripe receipts is done using the "verifyStripeReceipt" function. It receives the user ID and receipt data in the request body, checks if the user exists and has a Stripe customer ID, and then verifies the receipt with Stripe by creating a payment intent and confirming it with the customer ID and other relevant details.

Q. What functions are needed in the Firebase Cloud Functions setup?

A. The Firebase Cloud Functions setup requires functions to create Stripe customers when users sign up with Firebase Authentication, update Stripe customers when users change their email or password, delete Stripe customers when users delete their accounts, and verify Stripe receipts when users purchase subscriptions with react-native-iap.

Q. What are the prerequisites for implementing in-app purchases using react-native-iap?

A. The prerequisites for implementing in-app purchase using react-native-iap include having a Firebase account and project, a Stripe account and project, a Google Play Developer account and console, an Apple Developer account and App Store Connect account, a code editor, a terminal or command prompt, Node.js and npm installed, React Native CLI installed, Android Studio installed (for Android development), Xcode installed (for iOS development), and a physical or virtual device for testing.