react-native-iap

repository·main·Indexed 25 days ago

https://github.com/hyochan/react-native-iap

A high-performance React Native In-App Purchases module for iOS and Android that conforms to the Open IAP specification. Version 14.7.20 utilizes Nitro Modules to provide a unified API for purchases and subscriptions with minimal native bridge overhead. It supports React Native 0.64+, Expo SDK 45+ (via Dev Client), iOS 15+ (StoreKit 2), and Android API level 21+ (Google Play Billing v8.0.0+).

Tokens
101.5K
Snippets
274
Records
424
Agent score
83%

What's inside react-native-iap

  1. Compare subscription validation capabilities across iOS and Android

    main

    React Native IAP provides different API surfaces depending on the platform to handle subscription validation.

    • getAvailablePurchases: Fetches active entitlement records. On iOS, it wraps StoreKit 2 Transaction.currentEntitlements. On Android, it merges inapp and subs queries from Google Play Billing.
    • getActiveSubscriptions: A specialized version of getAvailablePurchases that filters for subscriptions and adds convenience fields like expirationDateIOS or willExpireSoon (Android).
    • subscriptionStatusIOS: Provides fine-grained phase data (e.g., inTrialPeriod, inGracePeriod) on iOS via StoreKit 2. Not available on Android; Android users must pair getAvailablePurchases with the Play Developer API for phase data.
    • Receipt Validation: Use getReceiptDataIOS or validateReceipt (iOS) for App Store receipts/JWS. For Android, validateReceipt forwards to the OpenIAP Google Play validator using purchaseToken and packageName.
  2. Understand the OpenIAP specification

    main
    React Native IAP conforms to the OpenIAP specification, which is a vendor-neutral interoperability standard for in-app purchases. Instead of using framework-specific implementations, OpenIAP uses a single GraphQL schema as a source of truth to define common types, error codes, and purchase flows. This ensures consistent and verifiable behavior across different platforms (iOS, Android, Flutter, etc.).
  3. Use direct listeners for purchase updates

    main

    If you prefer not to use the useIAP hook, you can use direct listeners. You must initialize the connection with initConnection() first. Ensure you remove the listeners in the cleanup function of your effect to prevent memory leaks.

    useEffect(() => {
      initConnection().then(() => {
        const purchaseUpdate = purchaseUpdatedListener((purchase) => {
          handlePurchaseUpdate(purchase);
        });
    
        const purchaseError = purchaseErrorListener((error) => {
          console.log('purchaseErrorListener', error);
        });
    
        return () => {
          purchaseUpdate.remove();
          purchaseError.remove();
        };
      });
    }, []);
  4. Configure react-native-iap for Horizon OS (Meta Quest)

    main

    To use react-native-iap on Meta Quest devices running Horizon OS, you must configure the library to use Meta's Platform SDK instead of Google Play Billing. This requires enabling Horizon mode in Gradle and providing your Horizon App ID in the Android manifest.

    Prerequisites

    • Meta Quest Developer account
    • App created in Meta Quest Developer Hub
    • Quest device or Quest Link for testing

    1. Enable Horizon Mode

    Add the following line to your android/gradle.properties file:

    2. Add Horizon App ID

    Add the following <meta-data> tag inside the <application> block of your android/app/src/main/AndroidManifest.xml. Replace YOUR_HORIZON_APP_ID with the ID from the Meta Quest Developer Hub.

    3. Clean and Rebuild

    After making these changes, you must clean the build to ensure the correct artifacts are used:

    Note on Code Integration

    Code integration is identical to standard Android integration. You can use the useIAP hook and standard API methods without modification; react-native-iap handles the platform differences automatically.

    # android/gradle.properties
    horizonEnabled=true
    <!-- android/app/src/main/AndroidManifest.xml -->
    <application>
      <!-- Meta Horizon App ID (required for Horizon OS) -->
      <meta-data
        android:name="com.meta.horizon.platform.ovr.OCULUS_APP_ID"
        android:value="YOUR_HORIZON_APP_ID" />
    </application>
    cd android
    ./gradlew clean
    cd ..
    npx react-native run-android
  5. Set up the Expo example app

    main

    The example-expo project is an independent project used to test react-native-iap. It uses bun for package management and a custom postinstall script to link the library's source code and native modules.

    Recommended Automated Setup: From the root directory of the main project, run:

    yarn setup:expo

    This command installs root and example dependencies, runs the postinstall script (linking and building), and generates native iOS/Android code.

    Manual Setup: If you need to set it up manually, navigate to the example-expo directory and run:

    bun install

    To manually trigger the linking and building process, run the postinstall script:

    ./scripts/postinstall.sh
  6. Implement Android Alternative Billing

    main

    Android supports two modes: alternative-only (exclusive use of your payment system) and user-choice (users choose between Google Play and your system).

    Follow this three-step flow:

    1. Check availability using checkAlternativeBillingAvailabilityAndroid().
    2. Show the selection dialog using showAlternativeBillingDialogAndroid().
    3. Create a reporting token using createAlternativeBillingTokenAndroid(productId) to ensure Google Play compliance (must be reported within 24 hours).

    Use userChoiceBillingListenerAndroid to listen for user selection events.

    import {
      initConnection,
      checkAlternativeBillingAvailabilityAndroid,
      showAlternativeBillingDialogAndroid,
      createAlternativeBillingTokenAndroid,
      userChoiceBillingListenerAndroid,
    } from 'react-native-iap';
    
    // Initialize with alternative billing mode
    await initConnection({
      alternativeBillingModeAndroid: 'alternative-only', // or 'user-choice'
    });
    
    // 3-step alternative billing flow
    const isAvailable = await checkAlternativeBillingAvailabilityAndroid();
    const userAccepted = await showAlternativeBillingDialogAndroid();
    const token = await createAlternativeBillingTokenAndroid(productId);
    
    // User choice billing event listener
    const subscription = userChoiceBillingListenerAndroid((details) => {
      console.log('User selected alternative billing');
      // Report to backend for Google Play compliance
    });
  7. Install React Native IAP 14.4.12 with Alternative Billing Support

    main

    To use the new alternative billing features, install version 14.4.12 or higher.

    For standard React Native CLI projects:

    npm install react-native-iap@14.4.12
    # or
    yarn add react-native-iap@14.4.12
    # or
    bun add react-native-iap@14.4.12
    
    cd ios && pod install

    For Expo projects: After installing, you must run prebuild to apply the Expo Config Plugin changes:

    npx expo prebuild --clean
    npm install react-native-iap@14.4.12