Implementing In-app Purchase In React Native

In the previous article, What is In-App Purchase and Configuration of In-App Purchase in React Native? We saw a detailed explanation of In-App Purchase, type of In-App Purchase, working of In-App Purchase, the Prerequisites before implementing In-App purchase, configuration in both android and ios. This article will look into the implementation of In-App Purchase in React Native and how to test it.

Library Used: react-native-iap

Installation:

npm install --save react-native-iap

For iOS:

Cd ios && pod install

Code:

Import the library,

import * as RNIap from 'react-native-iap';

Define your products for android and ios separately,

const itemSubs = Platform.select({

   ios: ['your_product_id'],

   android: ['your_product_id'],

 });

Get Connection Status,

useEffect(() => {

   initilizeIAPConnection();

 }, []);

 const initilizeIAPConnection = async () => {

   await RNIap.initConnection()

     .then(async (connection) => {

       console.log('IAP result', connection);

       getItems();

     })

     .catch((err) => {

       console.warn(`IAP ERROR ${err.code}`, err.message);

     });

     await RNIap.flushFailedPurchasesCachedAsPendingAndroid()

       .then(async(consumed) => {

       console.log('consumed all items?', consumed);

     }).catch((err) => {

       console.warn(`flushFailedPurchasesCachedAsPendingAndroid ERROR ${err.code}`, err.message);

     });

 };

If the connection equals to true then get the products,

const getItems = async () => {

   try {

     console.log("itemSubs ",itemSubs);

     const Products = await RNIap.getSubscriptions(itemSubs);

     console.log(' IAP Su', Products);

     if (Products.length !== 0){

       if (Platform.OS === 'android'){

       //Your logic here to save the products in states etc

       } else if (Platform.OS === 'ios'){

       // your logic here to save the products in states etc

       // Make sure to check the response differently for android and ios as it is different for both

       }

     }

   } catch (err) {

     console.warn("IAP error",err.code, err.message, err);

     setError(err.message);

   }

 };

Before you request any purchase, you should set purchaseUpdatedListener to get the updates as soon as the application is launched.

let purchaseUpdateSubscription = null;

let purchaseErrorSubscription = null;

 

useEffect(() => {

   purchaseUpdateSubscription = RNIap.purchaseUpdatedListener(

     async (purchase) => {

       console.log("purchase", purchase);

       const receipt = purchase.transactionReceipt;

       if (receipt) {

         try {

           if (Platform.OS === 'ios') {

             RNIap.finishTransactionIOS(purchase.transactionId);

           } else if (Platform.OS === 'android'){

             await RNIap.consumeAllItemsAndroid(purchase.purchaseToken);

             await RNIap.acknowledgePurchaseAndroid(purchase.purchaseToken);

           }

             await RNIap.finishTransaction(purchase, true);

         } catch (ackErr) {

           console.log('ackErr INAPP>>>>', ackErr);

         }

       }

     },

   );

   purchaseErrorSubscription = RNIap.purchaseErrorListener(

     (error) => {

       console.log('purchaseErrorListener INAPP>>>>', error);

     },

   );

   return (() => {

     if (purchaseUpdateSubscription) {

       purchaseUpdateSubscription.remove();

       purchaseUpdateSubscription = null;

     }
 if (purchaseErrorSubscription) {

       purchaseErrorSubscription.remove();

       purchaseErrorSubscription = null;

     }

   });

 }, []);

And finally you can call requestSubcription() or requestPurchase() on click of buy button

<TouchableOpacity

   onPress={() => {

    requestSubscription(monthlyPlanId);

    }}>

   <LinearGradient

    style={styles.subscriptionContinueButton}

    colors={['#3983F7', '#4DAAEE']}

    star t={{ x: 0.0, y: 0.5 }}

    end={{ x: 1.0, y: 0.5 }}

    location={[0.0, 1.0]}>

    {buyIsLoading === true ?

      <ActivityIndicator size={'small'} color={colors.white} /> :

      <Text style={styles.subscriptionContinueButtonText}>{'Buy'}</Text> }

   </LinearGradient>

 </TouchableOpacity>

 

const requestSubscription = async (sku) => {

   setBuyIsLoading(true);

   console.log("IAP req", sku);

   try {

     await RNIap.requestSubscription(sku)

     .then(async (result) => {

       console.log('IAP req sub', result);

       if (Platform.OS === 'android'){

           setPurchaseToken(result.purchaseToken);

           setPackageName(result.packageNameAndroid);

           setProductId(result.productId);

// can do your API call here to save the purchase details of particular user

       } else if (Platform.OS === 'ios'){

          console.log(result.transactionReceipt)

           setProductId(result.productId);

           setReceipt(result.transactionReceipt);

// can do your API call here to save the purchase details of particular user

       }

       setBuyIsLoading(false);

      })

     .catch((err) => {

       setBuyIsLoading(false);

       console.warn(`IAP req ERROR %%%%% ${err.code}`, err.message, isModalVisible);

       setError(err.message);

     });

   } catch (err) {

     setBuyIsLoading(false);

     console.warn(`err ${error.code}`, error.message);

     setError(err.message);

   }

 };

Testing:

For iOS, you can create a sandbox tester for that: Go to “User & Roles Section” in iTunes, select the “Sandbox Tester” tab and add a new user as a tester with some basic details. With that user’s credentials, he can purchase any product on iOS without paying any real money and test in-app purchase functionality in the iOS app.

For Android, open the google play store console, go to the “Settings” section and then the “Email list,” and add the user’s email you want to add as a tester. You can test in-app purchase functionality in the Android app using these tester accounts credentials.
Make sure testers have accepted the invitation. In the testing mode, you will get default-test cards.

coma

Conclusion

In this article, we saw in detail the implementation of In-App Purchase in React Native and how to test it. If you have any queries, just leave your comments below.

Sayali

Tech Expert
Sayali is a React Native Developer with around 2.5 years of experience in developing mobile applications. She is familiar with writing blogs for the last 3 years. She is self-motivated, a fast learner, and result-oriented. She loves to write blogs on technical issues faced by developers in day-to-day work and help them through her blogs.

Upcoming Webinar On "How To Achieve Project Success With Your Outsourced Team!"

Register Now

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google