Day 9: Implementing In-App Purchases in React Native


In this tutorial, you’ll learn how to set up in-app purchases using react-native-iap, a popular package that simplifies implementing purchases on both iOS and Android. By the end of today’s lesson, you’ll have configured your app to allow users to buy products and subscriptions.


What You Will Learn Today:

  1. Installing and setting up react-native-iap
  2. Configuring in-app purchases in Google Play Console and App Store Connect
  3. Implementing purchase logic and handling purchases
  4. Testing in-app purchases on Android and iOS

Step 1: Setting Up In-App Purchases

To get started, install the react-native-iap package, which handles in-app purchases for both Android and iOS.

  1. Install react-native-iap:
npm install react-native-iap
  1. For iOS, navigate to the ios directory and install the required CocoaPods:
cd ios
pod install
cd ..

Explanation:

  • react-native-iap: A React Native library that provides a unified API for handling in-app purchases on iOS and Android.

Step 2: Configuring In-App Purchases on Google Play Console and App Store Connect

To use in-app purchases, you must set up products in the Google Play Console and App Store Connect. Here’s a quick overview of the configuration for each platform:

See also  Day 7: Securing User Authentication and Authorization with Role-Based Access Control (RBAC)

1. Google Play Console

  1. Go to the Google Play Console and select your app.
  2. Navigate to Monetize > Products > In-app products and click Create Product.
  3. Fill in the product ID, name, and description, then set a price.
  4. Save the product. Note the product ID (e.g., premium_upgrade) as you’ll need it in your code.

2. App Store Connect

  1. Go to App Store Connect and select your app.
  2. Go to In-App Purchases and click the + button to add a new purchase.
  3. Choose the type of in-app purchase (e.g., non-consumable, consumable, or subscription).
  4. Enter the Reference Name and Product ID (e.g., premium_upgrade), then save.
  5. Ensure your in-app purchase is added to your app’s App Store version before testing.

Step 3: Initializing In-App Purchases

Once your products are set up, you can initialize in-app purchases and fetch available products in your app.

  1. Create a new file called PurchaseService.js:
touch PurchaseService.js
  1. Open PurchaseService.js and add the following code to initialize and fetch products:
import React, { useEffect, useState } from 'react';
import { Alert } from 'react-native';
import * as RNIap from 'react-native-iap';

const productIds = ['premium_upgrade']; // Add your product IDs here

export default function useIAP() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // Initialize IAP connection
    const initIAP = async () => {
      try {
        await RNIap.initConnection();
        const items = await RNIap.getProducts(productIds);
        setProducts(items);
      } catch (error) {
        console.warn('Error initializing IAP:', error);
      }
    };

    initIAP();

    return () => {
      RNIap.endConnection(); // End connection on unmount
    };
  }, []);

  return { products };
}

Explanation:

  • productIds: List of product IDs configured in the Google Play Console and App Store Connect.
  • RNIap.initConnection(): Initializes the connection to the in-app purchase service.
  • RNIap.getProducts(): Fetches the products available for purchase based on the product IDs.
See also  Day 4: Handling User Input and Forms

Step 4: Implementing Purchase Logic

Now let’s add the purchase logic to allow users to buy a product.

  1. Create a new file called PurchaseScreen.js:
touch PurchaseScreen.js
  1. Open PurchaseScreen.js and set up a screen to display available products and handle purchases:
import React from 'react';
import { View, Text, Button, FlatList, Alert } from 'react-native';
import * as RNIap from 'react-native-iap';
import useIAP from './PurchaseService';

export default function PurchaseScreen() {
  const { products } = useIAP();

  const handlePurchase = async (productId) => {
    try {
      const purchase = await RNIap.requestPurchase(productId);
      console.log('Purchase successful:', purchase);
      Alert.alert('Success', 'Purchase successful!');
      // Handle post-purchase logic here (e.g., unlocking features)
    } catch (error) {
      console.warn('Purchase failed:', error);
      Alert.alert('Purchase failed', error.message);
    }
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Available Purchases</Text>
      <FlatList
        data={products}
        keyExtractor={(item) => item.productId}
        renderItem={({ item }) => (
          <View style={{ marginVertical: 10 }}>
            <Text style={{ fontSize: 16 }}>{item.title}</Text>
            <Text>{item.description}</Text>
            <Text>{item.localizedPrice}</Text>
            <Button title="Buy" onPress={() => handlePurchase(item.productId)} />
          </View>
        )}
      />
    </View>
  );
}

Explanation:

  • handlePurchase: Initiates the purchase process when the user presses the “Buy” button. If the purchase succeeds, you can implement post-purchase logic (e.g., granting access to premium features).
  • FlatList: Displays each available product, including its title, description, and price, with a “Buy” button.

Step 5: Handling Purchase Completion and Errors

To manage purchases and handle any errors, we’ll add some checks and event listeners.

  1. Update PurchaseService.js to handle purchase updates:
import { useEffect } from 'react';
import * as RNIap from 'react-native-iap';

export default function useIAP() {
  // Other initialization and state here...

  useEffect(() => {
    const purchaseUpdateSubscription = RNIap.purchaseUpdatedListener((purchase) => {
      if (purchase.transactionReceipt) {
        console.log('Purchase receipt:', purchase.transactionReceipt);
        // Verify the receipt with your server here (optional)
        RNIap.finishTransaction(purchase); // Acknowledge the purchase
      }
    });

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

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

Explanation:

  • RNIap.purchaseUpdatedListener: Listens for successful purchase updates. finishTransaction acknowledges the purchase, required for consumable items.
  • RNIap.purchaseErrorListener: Captures and logs any errors that occur during the purchase process.
See also  PHP and Bitcoin: Exploring Integration Possibilities

Step 6: Testing In-App Purchases

Testing IAP functionality is essential to ensure it works correctly on both platforms. Here’s how to test in-app purchases:

1. Testing on Android

  1. Upload an internal testing or alpha version of your app on the Google Play Console.
  2. Add tester accounts (emails) in the Play Console under Settings > License Testing.
  3. Install the internal testing version on your test device and test the purchase flow.

2. Testing on iOS

  1. Create an App Store Connect Sandbox Account under Users and Access > Sandbox Testers.
  2. Install the app on an iOS device using TestFlight.
  3. Sign in to the iOS device with the sandbox account and test the purchase.

Step 7: Recap and Summary

In today’s tutorial, you learned how to implement in-app purchases in a React Native app using react-native-iap. Here’s a quick summary of what you’ve done:

  • Set up in-app purchases in the Google Play Console and App Store Connect.
  • Initialized react-native-iap to connect with Google Play and Apple’s App Store.
  • Created purchase logic and implemented UI elements to display available products.
  • Set up purchase listeners to handle successful purchases and errors.
  • Tested in-app purchases on both Android and iOS.

With in-app purchases integrated, you can now monetize your app by offering premium content or features.


Next Up: Day 10 – Integrating Analytics with Firebase in React Native

In Day 10, we’ll explore integrating analytics with Firebase to track user interactions, engagement, and conversions, which is essential for understanding your app’s usage.

Stay tuned for more advanced features tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.