Iaptic React Native SDK.

This is the entry point for the Iaptic SDK, the main methods are:

import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import { IapticRN, IapticProduct, IapticVerifiedPurchase } from 'react-native-iaptic';

const App = () => {
const [products, setProducts] = useState<IapticProduct[]>([]);
const [entitlements, setEntitlements] = useState<string[]>([]);

useEffect(async () => {

// Listen for product and entitlement updates
IapticRN.addEventListener('products.updated', setProducts);
IapticRN.addEventListener('purchase.updated', () => {
setEntitlements(IapticRN.listEntitlements());
});

// Initialize IapticRN with your API key and product definitions
await IapticRN.initialize({
appName: 'com.example.app',
publicKey: 'YOUR_API_KEY',
iosBundleId: 'com.example.app',
products: [
{ id: 'pro_monthly', type: 'paid subscription', entitlements: ['pro'] },
{ id: 'premium_lifetime', type: 'non consumable', entitlements: ['premium'] },
],
});

// Load products and entitlements
setEntitlements(IapticRN.listEntitlements());
setProducts(IapticRN.getProducts());

return () => {
IapticRN.destroy();
};
}, []);

// Handle purchase button press
const handlePurchase = async (product: IapticProduct) => {
try {
await IapticRN.order(product.offers[0]);
Alert.alert('Purchase complete!');
} catch (err) {
Alert.alert('Purchase failed', err.message);
}
};

// Restore purchases
const restorePurchases = async () => {
try {
await IapticRN.restorePurchases(() => {});
Alert.alert('Purchases restored');
} catch (err) {
Alert.alert('Restore failed', err.message);
}
};

return (
<View>
{products.map(product => (
<TouchableOpacity
key={product.id}
onPress={() => handlePurchase(product)}
>
<Text>{product.title}</Text>
<Text>{product.offers[0].pricingPhases[0].price}</Text>
</TouchableOpacity>
))}

<Text>Pro entitlement: {entitlements.includes('pro') ? 'Yes' : 'No'}</Text>
<Text>Premium entitlement: {entitlements.includes('premium') ? 'Yes' : 'No'}</Text>

<TouchableOpacity onPress={restorePurchases}>
<Text>Restore Purchases</Text>
</TouchableOpacity>
</View>
);
};

export default App;

Constructors

Properties

utils: IapticUtils = utils

Utility functions

Methods

  • Add an event listener for iaptic events

    To remove a listener, call the returned object's remove() method.

    Type Parameters

    Parameters

    • eventType: T

      Type of event to listen for

    • listener: IapticEventListener<T>

      Callback function that will be called when the event occurs

    Returns { remove: () => void }

    // Listen for subscription updates
    IapticRN.addEventListener('subscription.updated', (reason, purchase) => {
    console.log(`Subscription ${purchase.id} ${reason}`);
    });

    // Listen for pending purchase updates
    IapticRN.addEventListener('pendingPurchase.updated', (pendingPurchase) => {
    console.log(`Purchase ${pendingPurchase.productId} is now ${pendingPurchase.status}`);
    });

    // Listen for purchase updates
    IapticRN.addEventListener('purchase.updated', (purchase) => {
    console.log(`Purchase ${purchase.id} ${purchase.status}`);
    });

    // Listen for non-consumable purchases
    IapticRN.addEventListener('nonConsumable.owned', (purchase) => {
    console.log(`Non-consumable purchase ${purchase.id} is now owned`);
    });
    const listener = IapticRN.addEventListener('purchase.updated', (purchase) => {
    console.log(`Purchase ${purchase.id} ${purchase.status}`);
    });
    listener.remove();

    IapticEventType for all possible event types

  • Add a locale for Iaptic provided components and error messages.

    Parameters

    • code: string

      The language code

    • messages: IapticLocale

      The locale messages

    Returns void

    IapticRN.addLocale('fr', {...});
    
  • Check if the user has active access to a specific feature or content.

    Entitlements represent features/content that users unlock through purchases. They are defined in product definitions and automatically tracked when purchases are validated.

    Parameters

    • featureId: string

      The unique identifier for the feature/content (e.g. "premium", "gold_status")

    Returns boolean

    True if the user has active access to the specified feature

    // Check premium access
    if (IapticRN.checkEntitlement('premium')) {
    showPremiumContent();
    } else {
    showUpgradePrompt();
    }

    // Check specific feature access
    const hasCoolFeature = IapticRN.checkEntitlement('cool_feature');
  • Destroy the IapticRN singleton, remove event listeners and cleanup everything.

    Returns void

  • Get the active subscription (if any)

    For apps that sell multiple subscriptions that can be active at the same time, this returns the first one. To check if there is any active subscription:

    • getPurchases to manually parse and find all active subscriptions.
    • isOwned with all your product ids to check if there is any active subscription.

    Returns undefined | IapticVerifiedPurchase

    The active subscription or undefined if there is no active subscription

    IapticVerifiedPurchase for more information on the purchase object

    const activeSubscription = IapticRN.getActiveSubscription();
    if (activeSubscription) {
    console.log(`Active subscription: ${activeSubscription.productId}`);
    if (activeSubscription.renewalIntent === 'Renew') {
    console.log('Will renew on: ' + new Date(activeSubscription.expiryDate).toLocaleDateString());
    }
    else {
    console.log('Will expire on: ' + new Date(activeSubscription.expiryDate).toLocaleDateString());
    }
    }
  • Get a product from the product catalog

    Parameters

    • productId: string

      The product identifier

    Returns undefined | IapticProduct

    The product or undefined if not found

    const product = IapticRN.getProduct('premium_monthly');
    

    IapticProduct for more information on the product object

  • Initialize the IapticRN singleton

    Parameters

    • config: IapticConfig

      The configuration for the IapticRN singleton

    Returns Promise<void>

    IapticRN.initialize({
    appName: 'com.example.app',
    publicKey: '1234567890',
    iosBundleId: 'com.example.app',
    products: [
    { id: 'pro_monthly', type: 'paid subscription', entitlements: ['pro'] },
    { id: 'premium_lifetime', type: 'non consumable', entitlements: ['premium'] },
    { id: 'coins_100', type: 'consumable', tokenType: 'coins', tokenValue: 100 },
    ],
    });
  • Check if a product is owned.

    • For non-consumable products, this checks if the product is owned.
    • For paid subscriptions, this checks if there is an active subscription.
    • For consumables, this always returns false.

    Parameters

    • productId: string

      The product identifier

    Returns boolean

    True if the product is owned

    if (IapticRN.isOwned('premium_subscription')) {
    console.log('User has an active subscription');
    }
  • Get all currently active entitlements for the user.

    This aggregates entitlements from all non-expired purchases, including:

    • Active subscriptions
    • Non-consumable purchases
    • Non-consumed consumables

    Entitlements are defined in product definitions and automatically tracked when purchases are validated.

    Returns string[]

    Array of entitlement IDs the user currently has access to

    // Get all unlocked features
    const unlockedFeatures = IapticRN.listEntitlements();
    // ['basic', 'premium', 'dark_theme']
  • Load products from the Store.

    Parameters

    Returns Promise<IapticProduct[]>

    await IapticRN.loadProducts([
    { id: 'basic_subscription', type: 'paid subscription', entitlements: [ 'basic' ] },
    { id: 'premium_subscription', type: 'paid subscription', entitlements: [ 'basic', 'premium' ] },
    { id: 'premium_lifetime', type: 'non consumable', entitlements: [ 'basic', 'premium' ] },
    { id: 'coins_100', type: 'consumable', tokenType: 'coins', tokenValue: 100 },
    ]);
  • Load and validate active purchases details from the Store and Iaptic using their receipts

    Notice that this is done when initialize the Store already.

    Returns Promise<IapticVerifiedPurchase[]>

    List of verified purchases.

    const purchases = await IapticRN.loadPurchases();
    
  • Opens the platform-specific billing management page.

    Returns Promise<void>

  • Opens the platform-specific subscription management page.

    Returns Promise<void>

  • Order a product with an offer.

    Parameters

    Returns Promise<void>

    const offer = IapticRN.getProduct('premium_monthly')?.offers[0];
    if (offer) {
    try {
    await IapticRN.order(offer);
    console.log('Purchase started successfully');
    } catch (error) {
    console.error('Purchase failed:', error);
    }
    }
  • Present a subscription comparison view with product cards and feature grid

    Returns void

    IapticRN.presentSubscriptionView();
    

    This is a singleton component - Render it once at your root component:

    // In your App.tsx
    export default function App() {
    return (
    <>
    <MainComponent />
    <IapticSubscriptionView />
    </>
    );
    }
  • Remove all event listeners for a specific event type If no event type is specified, removes all listeners for all events

    Parameters

    • OptionaleventType: IapticEventType

      Optional event type to remove listeners for

    Returns void

  • Restore purchases from the Store.

    Parameters

    • progressCallback: (processed: number, total: number) => void

      Callback function that will be called with the progress of the restore operation - An initial call with -1, 0 when the operation starts. - Subsequent calls are with the current progress (processed, total). - The final call will have processed === total, you know the operation is complete.

    Returns Promise<number>

    The number of purchases restored

    // Restore purchases with progress updates
    const numRestored = await IapticRN.restorePurchases((processed, total) => {
    console.log(`Processed ${processed} of ${total} purchases`);
    });
  • Set the application username for the iaptic service.

    This is used to track which user is making the purchase and associate it with the user's account.

    • On iOS, the application username is also added as an appAccountToken in the form of a UUID formatted MD5 (utils.md5UUID).
    • On Android, the application username is added as an obfuscatedAccountIdAndroid in the form of a 64 characters string (utils.md5).

    Don't forget to update the username in the app service if the user changes (login/logout).

    Parameters

    • username: undefined | string

    Returns Promise<void>

    IapticRN.setApplicationUsername('user_123');
    
    IapticRN.setApplicationUsername(undefined);
    
  • Set the current locale for Iaptic provided components and error messages.

    It's automatically set to the device's language, but you can override it.

    Parameters

    • code: string

      The language code

    • fallbackCode: string = 'en'

    Returns void

    IapticRN.setLocale('fr');
    
  • Add product definitions to the product catalog.

    Entitlements define what features/content a product unlocks. They can be shared across multiple products (e.g. a subscription and lifetime purchase both granting "premium" access).

    Parameters

    Returns void

    IapticRN.setProductDefinitions([
    {
    id: 'premium_monthly',
    type: 'paid subscription',
    entitlements: ['premium'] // Unlocks premium features
    },
    {
    id: 'dark_theme',
    type: 'non consumable',
    entitlements: ['dark_theme'] // Unlocks visual feature
    }
    ]);
    IapticRN.setProductDefinitions([
    { id: 'coins_100', type: 'consumable', tokenType: 'coins', tokenValue: 100 },
    { id: 'coins_500', type: 'consumable', tokenType: 'coins', tokenValue: 500 },
    ]);
    // Define a subscription and consumable product
    IapticRN.setProductDefinitions([
    {
    id: 'premium_monthly',
    type: 'paid subscription',
    entitlements: ['premium'],
    },
    {
    id: 'coins_1000',
    type: 'consumable',
    tokenType: 'coins',
    tokenValue: 1000,
    }