Implementing In-app Purchase In React Native

In the previous article, React Native In-App Purchase In Android And IOS. 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.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?