Implementing In-App Subscriptions in React Native with react-native-iap: A Step-by-Step Guide

Implementing In-App Subscriptions in React Native with react-native-iap: A Step-by-Step Guide

Written by Olgaa on Jul 28th, 2023 Views Report Post

Monetizing mobile applications through in-app purchases has become a popular revenue model for developers. With React Native, developers can easily integrate in-app purchases, including subscriptions, into their cross-platform mobile applications. In this blog post, we will walk through a step-by-step example of implementing in-app subscriptions using the react-native-iap library in a React Native application. By the end of this tutorial, you will have a clear understanding of how to set up and manage in-app subscriptions in your React Native app.

Understanding In-App Subscriptions

In-app subscriptions allow developers to offer recurring payment options to users, granting them access to premium content, features, or services for a specific duration. Common use cases for in-app subscriptions include access to ad-free content, premium features, or exclusive content on a subscription basis.

To implement in-app subscriptions in a React Native app, we'll use the react-native-iap library, which provides a simple and easy-to-use interface for handling in-app purchases and subscriptions across both Android and iOS platforms.

Prerequisites

Before we begin, make sure you have the following set up in your development environment:

  1. Node.js and npm installed.
  2. React Native development environment set up.
  3. A valid developer account on the Apple App Store and/or Google Play Console.

Setting Up a New React Native Project

If you don't have an existing React Native project, follow these steps to create a new one:

npx react-native init SubscriptionExample
cd SubscriptionExample

Installing react-native-iap Now, install the react-native-iap library in your project:

npm install react-native-iap

Linking the Library For React Native versions below 0.60, manually link the library:

react-native link react-native-iap

For React Native versions 0.60 and above, the library will be auto-linked.

Configuring In-App Purchases

To enable in-app purchases in your React Native app, you need to set up the necessary configurations on the Apple App Store and/or Google Play Console.

  1. Setting Up on Apple App Store (iOS)
  2. Log in to your Apple Developer Account and navigate to App Store Connect.
  3. Create a new app or select an existing one.
  4. In the Features section, click on "In-App Purchases" and add a new subscription product.
  5. Configure the pricing, duration, and other details for the subscription product.
  6. Setting Up on Google Play Console (Android)
  7. Log in to your Google Play Console and select your app.
  8. In the Monetization section, click on "Subscriptions" and create a new subscription product.
  9. Configure the pricing, duration, and other details for the subscription product.

Implementing In-App Subscriptions in React Native

Now that we have set up the necessary configurations on the app stores, let's implement in-app subscriptions in our React Native app using react-native-iap.

Step 1: Importing the Library

In the entry point of your application (e.g., App.js), import the react-native-iap library:

// App.js
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { initIAP, fetchProducts } from 'react-native-iap';

Step 2: Initializing the Library

In the same file, initialize the react-native-iap library using the initIAP() function. This function sets up the necessary listeners and configurations for in-app purchases:

// App.js
const App = () => {
  useEffect(() => {
    initIAP();
  }, []);

  // Rest of the component code

  return (
    <View>
      <Text>Implementing In-App Subscriptions</Text>
      {/* Add subscription components here */}
    </View>
  );
};

Step 3: Fetching Subscription Products

To display available subscription options to the user, we need to fetch the subscription products from the app stores. We'll use the fetchProducts() function to do this:

// App.js
const App = () => {
  useEffect(() => {
    initIAP();
    fetchSubscriptionProducts();
  }, []);

  const fetchSubscriptionProducts = async () => {
    try {
      const productIds = ['subscription_monthly', 'subscription_yearly'];
      const products = await fetchProducts(productIds);
      console.log('Fetched Products:', products);
    } catch (error) {
      console.error('Error fetching products:', error.message);
    }
  };

  // Rest of the component code

  return (
    <View>
      <Text>Implementing In-App Subscriptions</Text>
      {/* Add subscription components here */}
    </View>
  );
};

In this react-native-iap subscription example, we've fetched two subscription products with IDs 'subscription_monthly' and 'subscription_yearly'. These IDs should match the product IDs you set up on the app stores.

Step 4: Displaying Subscription Options

Now that we have fetched the subscription products, we can display them to the user:

// App.js
import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { initIAP, fetchProducts, purchaseSubscription } from 'react-native-iap';

const App = () => {
  const [subscriptionProducts, setSubscriptionProducts] = useState([]);

  useEffect(() => {
    initIAP();
    fetchSubscriptionProducts();
  }, []);

  const fetchSubscriptionProducts = async () => {
    try {
      const productIds = ['subscription_monthly', 'subscription_yearly'];
      const products = await fetchProducts(productIds);
      setSubscriptionProducts(products);
    } catch (error) {
      console.error('Error fetching products:', error.message);
    }
  };

  const handleSubscriptionPurchase = async (productId) => {
    try {
      await purchaseSubscription(productId);
      console.log('Subscription purchased successfully!');
    } catch (error) {
      console.error('Error purchasing subscription:', error.message);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.heading}>Implementing In-App Subscriptions</Text>
      {subscriptionProducts.map((product) => (
        <TouchableOpacity
          key={product.productId}
          onPress={() => handleSubscriptionPurchase(product.productId)}
          style={styles.subscriptionOption}
        >
          <Text style={styles.subscriptionTitle}>{product.title}</Text>
          <Text style={styles.subscriptionDescription}>{product.description}</Text>
          <Text style={styles.subscriptionPrice}>{product.localizedPrice}</Text>
        </TouchableOpacity>
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  heading: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  subscriptionOption: {
    width: '100%',
    padding: 16,
    marginBottom: 16,
    borderRadius: 8,
    backgroundColor: '#f0f0f0',
  },
  subscriptionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  subscriptionDescription: {
    fontSize: 14,
    color: '#888',
    marginBottom: 8,
  },
  subscriptionPrice: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#007bff',
  },
});

export default App;

In this continuation, we have added the UI components to display the subscription options to the user. Each subscription option is rendered as a TouchableOpacity with the product title, description, and localized price. When the user taps on a subscription option, the handleSubscriptionPurchase function is called with the respective product ID, which initiates the purchase process.

Step 5: Handling Purchase Events

We also need to handle the events related to the purchase process, such as successful or failed purchases, and update the UI accordingly.

// App.js
import { initIAP, fetchProducts, purchaseSubscription } from 'react-native-iap';

// ... other code ...

const App = () => {
  // ... other code ...

  useEffect(() => {
    initIAP();
    fetchSubscriptionProducts();

    const purchaseUpdateSubscription = purchaseUpdatedListener(async (purchase) => {
      const receipt = purchase.transactionReceipt;
      if (receipt) {
        // Purchase was successful, handle the receipt or verify it on the server.
        console.log('Purchase successful! Receipt:', receipt);
      }
    });

    const purchaseErrorSubscription = purchaseErrorListener((error) => {
      console.error('Purchase error:', error.message);
    });

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

  // ... other code ...

  return (
    // ... other code ...
  );
};

In this example, we have added event listeners for purchase updates and purchase errors. The purchaseUpdatedListener listens for successful purchases, and the purchaseErrorListener listens for any errors that occur during the purchase process. When a purchase is successful, the receipt is extracted from the purchase object, and you can handle the receipt or verify it on the server, depending on your requirements.

Step 6: Testing the In-App Subscriptions

Now that we have implemented the in-app subscription functionality, it's time to test it on actual devices. Before testing, make sure you are using a test user account for in-app purchases on both iOS and Android devices.

Run your React Native app on a physical device (emulators do not support in-app purchases). Tap on any subscription option, and you should see the standard in-app purchase flow specific to the respective platform. After successfully making a purchase, the purchaseUpdatedListener will be triggered, and you should see the console log with the receipt information.

Conclusion

Congratulations! You have successfully implemented in-app subscriptions in your React Native app using the react-native-iap library. Users can now subscribe to premium content or services through your app, providing a new revenue stream for your mobile application.

In this tutorial, we covered the steps to set up the react-native-iap library, configure in-app purchases on the app stores, fetch subscription products, and handle the purchase events. With this knowledge, you can create a wide range of subscription-based features in your React Native applications, from ad-free experiences to premium access to exclusive content.

Remember to handle purchase receipts securely and consider implementing server-side verification to prevent unauthorized access to premium content.

As you continue to develop your React Native app, keep in mind that in-app purchases and subscriptions play a crucial role in driving app revenue and user engagement. With the power of react-native-iap, you can offer a seamless and intuitive subscription experience to your users, encouraging them to unlock the full potential of your application.

Comments (0)