Skip to content

Latest commit

 

History

History
3710 lines (1866 loc) · 62.2 KB

api.md

File metadata and controls

3710 lines (1866 loc) · 62.2 KB

react-native-iaptic

Iaptic React Native SDK

Provides in-app purchase functionality with integrated receipt validation through the Iaptic service.

The API entry point is IapticRN.

Example

import { IapticSubscriptionView } from 'react-native-iaptic';
const app = (props) => {
  useEffect(() => {
    // Initialize the SDK with your configuration at startup
    IapticRN.initialize({
      appName: 'com.example.app',
      publicKey: 'YOUR_API_KEY',
      iosBundleId: 'com.yourcompany.app',
      products: [{
        id: 'premium_subscription',
        type: 'paid subscription',
        entitlements: ['basic', 'premium']
      }, {
        id: 'basic_subscription',
        type: 'paid subscription',
        entitlements: ['basic']
      }],
    });
  }, []);
  return (
    <View>
      // In your root node, add the modal component
      <IapticSubscriptionView entitlementLabels={{
        premium: 'Premium Features',
        basic: 'Basic Features',
      }} />

      // Anyway in your app, open the Subscription UI
      <TouchableOpacity onPress={() => IapticRN.presentSubscriptionView()}>
        <Text>Subscribe</Text>
      </TouchableOpacity>
    </View>
  );
};

// 2. Check access without a backend server
if (IapticRN.checkEntitlement('premium')) {
  // Unlock premium features
}

With a backend server, you will get webhook calls from iaptic server and store your user's subscription status (unlocking features server-side, safer).

Enumerations

IapticCancelationReason

Reason why a subscription has been canceled

Enumeration Members

CUSTOMER

CUSTOMER: "Customer"

Subscription canceled by the user for an unspecified reason.

CUSTOMER_COST

CUSTOMER_COST: "Customer.Cost"

Customer canceled for cost-related reasons.

CUSTOMER_FOUND_BETTER_APP

CUSTOMER_FOUND_BETTER_APP: "Customer.FoundBetterApp"

Customer claimed to have found a better app.

CUSTOMER_NOT_USEFUL_ENOUGH

CUSTOMER_NOT_USEFUL_ENOUGH: "Customer.NotUsefulEnough"

Customer did not feel he is using this service enough.

CUSTOMER_OTHER_REASON

CUSTOMER_OTHER_REASON: "Customer.OtherReason"

Subscription canceled for another reason; for example, if the customer made the purchase accidentally.

CUSTOMER_PRICE_INCREASE

CUSTOMER_PRICE_INCREASE: "Customer.PriceIncrease"

Customer did not agree to a recent price increase. See also priceConsentStatus.

CUSTOMER_TECHNICAL_ISSUES

CUSTOMER_TECHNICAL_ISSUES: "Customer.TechnicalIssues"

Customer canceled their transaction due to an actual or perceived issue within your app.

DEVELOPER

DEVELOPER: "Developer"

Subscription canceled by the developer.

NOT_CANCELED

NOT_CANCELED: ""

Not canceled

SYSTEM

SYSTEM: "System"

Subscription canceled by the system for an unspecified reason.

SYSTEM_BILLING_ERROR

SYSTEM_BILLING_ERROR: "System.BillingError"

Billing error; for example customer's payment information is no longer valid.

SYSTEM_DELETED

SYSTEM_DELETED: "System.Deleted"

Transaction is gone; It has been deleted.

SYSTEM_PRODUCT_UNAVAILABLE

SYSTEM_PRODUCT_UNAVAILABLE: "System.ProductUnavailable"

Product not available for purchase at the time of renewal.

SYSTEM_REPLACED

SYSTEM_REPLACED: "System.Replaced"

Subscription upgraded or downgraded to a new subscription.

UNKNOWN

UNKNOWN: "Unknown"

Subscription canceled for unknown reasons.


IapticErrorCode

Error codes

Enumeration Members

BAD_RESPONSE

BAD_RESPONSE: 6777018

Error: Bad response from the server

CLIENT_INVALID

CLIENT_INVALID: 6777005

Error: Client is not allowed to issue the request

CLOUD_SERVICE_NETWORK_CONNECTION_FAILED

CLOUD_SERVICE_NETWORK_CONNECTION_FAILED: 6777025

Error: The device could not connect to the network.

CLOUD_SERVICE_PERMISSION_DENIED

CLOUD_SERVICE_PERMISSION_DENIED: 6777024

Error: The user has not allowed access to Cloud service information

CLOUD_SERVICE_REVOKED

CLOUD_SERVICE_REVOKED: 6777026

Error: The user has revoked permission to use this cloud service.

COMMUNICATION

COMMUNICATION: 6777014

Error: Failed to communicate with the server

DOWNLOAD

DOWNLOAD: 6777021

Error: Failed to download the content

FINISH

FINISH: 6777013

Error: Cannot finalize a transaction or acknowledge a purchase

INVALID_OFFER_IDENTIFIER

INVALID_OFFER_IDENTIFIER: 6777029

Error: The offer identifier is invalid.

INVALID_OFFER_PRICE

INVALID_OFFER_PRICE: 6777030

Error: The price you specified in App Store Connect is no longer valid.

INVALID_PRODUCT_ID

INVALID_PRODUCT_ID: 6777012

Error: The product identifier is invalid

INVALID_SIGNATURE

INVALID_SIGNATURE: 6777031

Error: The signature in a payment discount is not valid.

LOAD

LOAD: 6777002

Error: Failed to load in-app products metadata

LOAD_RECEIPTS

LOAD_RECEIPTS: 6777004

Error: Failed to load the purchase receipt

MISSING_OFFER_PARAMS

MISSING_OFFER_PARAMS: 6777032

Error: Parameters are missing in a payment discount.

MISSING_TOKEN

MISSING_TOKEN: 6777016

Error: Purchase information is missing token

PAYMENT_CANCELLED

PAYMENT_CANCELLED: 6777006

Error: Purchase flow has been cancelled by user

PAYMENT_EXPIRED

PAYMENT_EXPIRED: 6777020

Error: Payment has expired

PAYMENT_INVALID

PAYMENT_INVALID: 6777007

Error: Something is suspicious about a purchase

PAYMENT_NOT_ALLOWED

PAYMENT_NOT_ALLOWED: 6777008

Error: The user is not allowed to make a payment

PRIVACY_ACKNOWLEDGEMENT_REQUIRED

PRIVACY_ACKNOWLEDGEMENT_REQUIRED: 6777027

Error: The user has not yet acknowledged Apple's privacy policy

PRODUCT_NOT_AVAILABLE

PRODUCT_NOT_AVAILABLE: 6777023

Error: The requested product is not available in the store.

PURCHASE

PURCHASE: 6777003

Error: Failed to make a purchase

REFRESH

REFRESH: 6777019

Error: Failed to refresh the store

REFRESH_RECEIPTS

REFRESH_RECEIPTS: 6777011

Error: Failed to refresh the purchase receipt

SETUP

SETUP: 6777001

Error: Failed to intialize the in-app purchase library

SUBSCRIPTION_UPDATE_NOT_AVAILABLE

SUBSCRIPTION_UPDATE_NOT_AVAILABLE: 6777022

Error: Failed to update a subscription

SUBSCRIPTIONS_NOT_AVAILABLE

SUBSCRIPTIONS_NOT_AVAILABLE: 6777015

Error: Subscriptions are not available

UNAUTHORIZED_REQUEST_DATA

UNAUTHORIZED_REQUEST_DATA: 6777028

Error: The app is attempting to use a property for which it does not have the required entitlement.

UNKNOWN

UNKNOWN: 6777010

Error: Unknown error

VALIDATOR_SUBSCRIPTION_EXPIRED

VALIDATOR_SUBSCRIPTION_EXPIRED: 6778003

Server code used when a subscription expired.

Deprecated

Validator should now return the transaction in the collection as expired.

VERIFICATION_FAILED

VERIFICATION_FAILED: 6777017

Error: Verification of store data failed


IapticPriceConsentStatus

Whether or not the user was notified or agreed to a price change

Enumeration Members

AGREED

AGREED: "Agreed"

NOTIFIED

NOTIFIED: "Notified"


IapticPurchasePlatform

Purchase platforms supported by the plugin

Enumeration Members

APPLE_APPSTORE

APPLE_APPSTORE: "ios-appstore"

Apple AppStore

BRAINTREE

BRAINTREE: "braintree"

Braintree

GOOGLE_PLAY

GOOGLE_PLAY: "android-playstore"

Google Play

TEST

TEST: "test"

Test platform

WINDOWS_STORE

WINDOWS_STORE: "windows-store-transaction"

Windows Store


IapticSeverity

Error severity

  • INFO: The error is not critical and can be ignored, not worth reporting to the user, can be logged to your server or ignored.
  • WARNING: The error is important and can be reported to the user as a toast message.
  • ERROR: The error is critical and should be reported to the user as a pop-up alert.

Enumeration Members

ERROR

ERROR: 2

INFO

INFO: 0

WARNING

WARNING: 1


IapticVerbosity

Enumeration Members

DEBUG

DEBUG: 3

ERROR

ERROR: 0

INFO

INFO: 2

WARN

WARN: 1

Classes

IapticError

Represents an error in the Iaptic purchase flow

Example

try {
  await iaptic.order(productOffer);
} catch (error) {
  if (error instanceof IapticError) {
    trackAnalyticsEvent(error.code);
    if (error.severity === IapticErrorSeverity.INFO) {
      console.log('Info:', error.localizedMessage);
      return;
    }
    Alert.alert(error.localizedTitle, error.localizedMessage);
  } else {
    Alert.alert('Unknown error', error.message);
  }
}

Extends

  • Error

Properties

cause?

optional cause: unknown

Inherited from

Error.cause

code

readonly code: IapticErrorCode

debugMessage

readonly debugMessage: string

localizedMessage

readonly localizedMessage: string

localizedTitle

readonly localizedTitle: string

message

message: string

Inherited from

Error.message

name

name: string

Inherited from

Error.name

severity

readonly severity: IapticSeverity

stack?

optional stack: string

Inherited from

Error.stack

status

readonly status: undefined | number

prepareStackTrace()?

static optional prepareStackTrace: (err, stackTraces) => any

Optional override for formatting stack traces

Parameters
err

Error

stackTraces

CallSite[]

Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from

Error.prepareStackTrace

stackTraceLimit

static stackTraceLimit: number

Inherited from

Error.stackTraceLimit

Methods

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters
targetObject

object

constructorOpt?

Function

Returns

void

Inherited from

Error.captureStackTrace


IapticRN

Iaptic React Native SDK.

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

Example

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

new IapticRN()

new IapticRN(): IapticRN

Returns

IapticRN

Properties

utils

readonly static utils: IapticUtils

Utility functions

Methods

addEventListener()

static addEventListener<T>(eventType, listener): object

Add an event listener for iaptic events

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

Type Parameters

T extends IapticEventType

Parameters
eventType

T

Type of event to listen for

listener

IapticEventListener<T>

Callback function that will be called when the event occurs

Returns

object

remove()

remove: () => void

Returns

void

Examples
// 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();
See

IapticEventType for all possible event types

addLocale()

static addLocale(code, messages): void

Add a locale for Iaptic provided components and error messages.

Parameters
code

string

The language code

messages

IapticLocale

The locale messages

Returns

void

Example
IapticRN.addLocale('fr', {...});
checkEntitlement()

static checkEntitlement(featureId): boolean

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

See

setProductDefinitions

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

// Check specific feature access
const hasCoolFeature = IapticRN.checkEntitlement('cool_feature');
consume()

static consume(purchase): Promise<void>

Consume a purchase. Only for consumable products.

Parameters
purchase

IapticVerifiedPurchase

The purchase to consume

Returns

Promise<void>

Example
IapticRN.consume(purchase);
See

IapticTokensManager for a convenient way to handle your consumable products.

destroy()

static destroy(): void

Destroy the IapticRN singleton, remove event listeners and cleanup everything.

Returns

void

getActiveSubscription()

static getActiveSubscription(): undefined | IapticVerifiedPurchase

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

See

IapticVerifiedPurchase for more information on the purchase object

Example
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());
  }
}
getPendingPurchases()

static getPendingPurchases(): IapticPendingPurchase[]

Get all pending purchases.

Returns

IapticPendingPurchase[]

List of pending purchases

getProduct()

static getProduct(productId): undefined | IapticProduct

Get a product from the product catalog

Parameters
productId

string

The product identifier

Returns

undefined | IapticProduct

The product or undefined if not found

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

IapticProduct for more information on the product object

getProducts()

static getProducts(): IapticProduct[]

Get all products from the product catalog

Returns

IapticProduct[]

List of products

Example
const products = IapticRN.getProducts();
See

IapticProduct for more information on the product object

getPurchases()

static getPurchases(): IapticVerifiedPurchase[]

Get all verified purchases.

Returns

IapticVerifiedPurchase[]

List of purchases, most recent first

Example
const purchases = IapticRN.getPurchases();
See

IapticVerifiedPurchase for more information on the purchase object

initialize()

static initialize(config): Promise<void>

Initialize the IapticRN singleton

Parameters
config

IapticConfig

The configuration for the IapticRN singleton

Returns

Promise<void>

Example
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 },
  ],
});
isOwned()

static isOwned(productId): boolean

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

Example
if (IapticRN.isOwned('premium_subscription')) {
  console.log('User has an active subscription');
}
listEntitlements()

static listEntitlements(): string[]

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

See

setProductDefinitions

Example
// Get all unlocked features
const unlockedFeatures = IapticRN.listEntitlements();
// ['basic', 'premium', 'dark_theme']
loadProducts()

static loadProducts(definitions?): Promise<IapticProduct[]>

Load products from the Store.

Parameters
definitions?

IapticProductDefinition[]

The products to load

Returns

Promise<IapticProduct[]>

Example
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 },
]);
loadPurchases()

static loadPurchases(): Promise<IapticVerifiedPurchase[]>

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.

Example
const purchases = await IapticRN.loadPurchases();
manageBilling()

static manageBilling(): Promise<void>

Opens the platform-specific billing management page.

Returns

Promise<void>

manageSubscriptions()

static manageSubscriptions(): Promise<void>

Opens the platform-specific subscription management page.

Returns

Promise<void>

order()

static order(offer): Promise<void>

Order a product with an offer.

Parameters
offer

IapticOffer

The offer to order

Returns

Promise<void>

Example
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);
  }
}
presentSubscriptionView()

static presentSubscriptionView(): void

Present a subscription comparison view with product cards and feature grid

Returns

void

Example
IapticRN.presentSubscriptionView();
Remarks

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

// In your App.tsx
export default function App() {
  return (
    <>
      <MainComponent />
      <IapticSubscriptionView />
    </>
  );
}
removeAllEventListeners()

static removeAllEventListeners(eventType?): void

Remove all event listeners for a specific event type If no event type is specified, removes all listeners for all events

Parameters
eventType?

IapticEventType

Optional event type to remove listeners for

Returns

void

restorePurchases()

static restorePurchases(progressCallback): Promise<number>

Restore purchases from the Store.

Parameters
progressCallback

(processed, total) => 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

Example
// Restore purchases with progress updates
const numRestored = await IapticRN.restorePurchases((processed, total) => {
  console.log(`Processed ${processed} of ${total} purchases`);
});
setApplicationUsername()

static setApplicationUsername(username): Promise<void>

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>

Examples
IapticRN.setApplicationUsername('user_123');
IapticRN.setApplicationUsername(undefined);
setLocale()

static setLocale(code, fallbackCode): void

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

Example
IapticRN.setLocale('fr');
setProductDefinitions()

static setProductDefinitions(productDefinitions): void

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
productDefinitions

IapticProductDefinition[]

Returns

void

Examples
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,
  }
]);

##### setVerbosity()

> `static` **setVerbosity**(`verbosity`): `void`


Set the verbosity level for the iaptic service.

###### Parameters

###### verbosity

[`IapticVerbosity`](#iapticverbosity)

###### Returns

`void`

###### Example

```typescript
IapticRN.setVerbosity(IapticLoggerVerbosityLevel.DEBUG);

IapticTokensManager

Simple token balance manager that uses localStorage to store transactions.

To do this, this class the list of all transactions and their corresponding amounts.

When a transaction is added, it is added to the list. When a transaction is removed, it is removed from the list.

The balance is the sum of all the amounts in the list.

See

  • IapticProductDefinition.tokenType
  • IapticProductDefinition.tokenValue

Example

const tokensManager = new IapticTokensManager(iaptic);
// ... tokensManager is now tracking consumable purchases that have a tokenType defined.
const balance = tokensManager.getBalance('coin');

Constructors

new IapticTokensManager()

new IapticTokensManager(consumePurchases): IapticTokensManager

Parameters
consumePurchases

boolean = true

Returns

IapticTokensManager

Methods

addTransaction()

addTransaction(transactionId, type, amount): Promise<void>

Add a transaction to the map and persist it

Parameters
transactionId

string

Unique identifier for the transaction

type

string

Type of token (e.g., 'gems', 'coins', 'credits')

amount

number

Number of tokens earned (positive) or spent (negative)

Returns

Promise<void>

getAllBalances()

getAllBalances(): Map<string, number>

Get all balances as a map of token type to amount

Returns

Map<string, number>

getBalance()

getBalance(tokenType): number

Get balance for a specific token type

Parameters
tokenType

string

Returns

number

getTransactions()

getTransactions(tokenType?): IapticTokenTransaction[]

Get transaction history for a specific token type

Parameters
tokenType?

string

Returns

IapticTokenTransaction[]

hasTransaction()

hasTransaction(transactionId): boolean

Helper method to check if we've already processed a transaction This can be used before processing a purchase to avoid double-counting

Parameters
transactionId

string

Returns

boolean

removeTransaction()

removeTransaction(transactionId): Promise<void>

Remove a transaction and update storage

Parameters
transactionId

string

Returns

Promise<void>


IapticUtils

Utility methods for users of the iaptic library.

Constructors

new IapticUtils()

new IapticUtils(): IapticUtils

Returns

IapticUtils

Methods

cheapestOffer()

cheapestOffer(product): IapticOffer

Parameters
product

IapticProduct

Returns

IapticOffer

fixedRecurrenceMode()

fixedRecurrenceMode(pricingPhase): undefined | IapticRecurrenceMode

FINITE_RECURRING with billingCycles=1 is like NON_RECURRING FINITE_RECURRING with billingCycles=0 is like INFINITE_RECURRING

Parameters
pricingPhase

IapticPricingPhase

Returns

undefined | IapticRecurrenceMode

formatBillingCycle()

formatBillingCycle(pricingPhase): string

Generate a localized version of the billing cycle in a pricing phase.

For supported languages, check IapticSupportedLocales.

Example outputs:

  • "3x 1 month": for FINITE_RECURRING, 3 cycles, period "P1M"
  • "for 1 year": for NON_RECURRING, period "P1Y"
  • "every week": for `INFINITE_RECURRING, period "P1W"
Parameters
pricingPhase

IapticPricingPhase

Returns

string

Example
IapticRN.utils.formatBillingCycle(offer.pricingPhases[0])
formatCurrency()

formatCurrency(amountMicros, currency): string

Format a currency amount from micros with proper localization

Parameters
amountMicros

number

Amount in micros (1/1,000,000 of currency unit)

currency

string

ISO 4217 currency code (e.g., 'USD', 'EUR')

Returns

string

Formatted currency string

Example
Utils.formatCurrency(1990000, 'USD') // Returns "$1.99"
Utils.formatCurrency(1000000, 'EUR') // Returns "€1"
formatDuration()

formatDuration(iso, count, includeCount?): string

Parameters
iso

`P${number}D` | `P${number}W` | `P${number}M` | `P${number}Y`

count

number

includeCount?

boolean

Returns

string

md5()

md5(account): string

Returns the MD5 hash-value of the passed string.

Parameters
account

string

Returns

string

md5UUID()

md5UUID(account): string

Generate a UUID v3-like string from an account string.

The username is first hashed with MD5, then formatted as a UUID v3-like string by adding dashes between the different parts of the hash.

This is used to generate a appAccountToken for Apple App Store purchases.

Parameters
account

string

The account string

Returns

string

The UUID v3-like string

monthlyPriceMicros()

monthlyPriceMicros(offer): number

Parameters
offer

IapticOffer

Returns

number

Interfaces

IapticConfig

Configuration for Iaptic React Native SDK

Extends

  • IapticStoreConfig

Properties

applicationUsername?

optional applicationUsername: string

appName

appName: string

Inherited from

IapticStoreConfig.appName

baseUrl?

optional baseUrl: string

The base URL of the iaptic validator

Inherited from

IapticStoreConfig.baseUrl

iosBundleId?

optional iosBundleId: string

Inherited from

IapticStoreConfig.iosBundleId

products?

optional products: IapticProductDefinition[]

publicKey

publicKey: string

Inherited from

IapticStoreConfig.publicKey

showAlerts?

optional showAlerts: boolean

Disable alert by setting this to false.

By default, IapticRN will display relevant alerts to the user when something goes wrong.

Default is true.

Inherited from

IapticStoreConfig.showAlerts

verbosity?

optional verbosity: IapticVerbosity


IapticEventMap

Event argument types mapped to their event names

Properties

consumable.purchased

purchased: [IapticVerifiedPurchase]

consumable.refunded

refunded: [IapticVerifiedPurchase]

error

error: [IapticError]

nonConsumable.owned

owned: [IapticVerifiedPurchase]

nonConsumable.unowned

unowned: [IapticVerifiedPurchase]

nonConsumable.updated

updated: [IapticVerifiedPurchase]

pendingPurchase.updated

updated: [IapticPendingPurchase]

products.updated

updated: [IapticProduct[]]

purchase.updated

updated: [IapticVerifiedPurchase]

subscription.cancelled

cancelled: [IapticVerifiedPurchase]

subscription.changed

changed: [IapticVerifiedPurchase]

subscription.expired

expired: [IapticVerifiedPurchase]

subscription.renewed

renewed: [IapticVerifiedPurchase]

subscription.updated

updated: [IapticSubscriptionReason, IapticVerifiedPurchase]


IapticLocale

List of keys a locale must provide.

Example

const myLocale: IapticLocale = {
  ProgrammingError: 'No pa bon',
  ...
};

IapticRN.addLocale('xx_yy', myLocale);

Properties

ActiveSubscription_ManageBilling

ActiveSubscription_ManageBilling: string

Manage Billing

ActiveSubscription_ManageSubscriptions

ActiveSubscription_ManageSubscriptions: string

Manage Subscriptions

ActiveSubscription_Status_Active

ActiveSubscription_Status_Active: string

Active

ActiveSubscription_Status_Expired

ActiveSubscription_Status_Expired: string

Expired

ActiveSubscription_Tag_Retry

ActiveSubscription_Tag_Retry: string

Payment Retry

ActiveSubscription_Tag_Trial

ActiveSubscription_Tag_Trial: string

Trial Period

ActiveSubscription_WillCancel

ActiveSubscription_WillCancel: string

Will be cancelled on {0} at {1}

ActiveSubscription_WillRenew

ActiveSubscription_WillRenew: string

Auto-renewing on {0} at {1}

BillingCycle_Finite

BillingCycle_Finite: string

{cycles}x {duration}

BillingCycle_Infinite

BillingCycle_Infinite: string

every {duration}

BillingCycle_NonRecurring

BillingCycle_NonRecurring: string

for {duration}

DateFormatter_Date

DateFormatter_Date: string

"Date"

DateFormatter_Time

DateFormatter_Time: string

"Time"

Duration_D_plural

Duration_D_plural: string

days

Duration_D_singular

Duration_D_singular: string

day

Duration_M_plural

Duration_M_plural: string

months

Duration_M_singular

Duration_M_singular: string

month

Duration_W_plural

Duration_W_plural: string

weeks

Duration_W_singular

Duration_W_singular: string

week

Duration_Y_plural

Duration_Y_plural: string

years

Duration_Y_singular

Duration_Y_singular: string

year

EntitlementGrid_Checkmark

EntitlementGrid_Checkmark: string

"✓"

Error

Error: string

Error

IapticError_6777001

IapticError_6777001: string

Failed to initialize the in-app purchase library

IapticError_6777002

IapticError_6777002: string

Failed to load in-app products metadata

IapticError_6777003

IapticError_6777003: string

Failed to make a purchase

IapticError_6777004

IapticError_6777004: string

Failed to load the purchase receipt

IapticError_6777005

IapticError_6777005: string

Client is not allowed to issue the request

IapticError_6777006

IapticError_6777006: string

Purchase flow has been cancelled by user

IapticError_6777007

IapticError_6777007: string

Something is suspicious about a purchase

IapticError_6777008

IapticError_6777008: string

The user is not allowed to make a payment

IapticError_6777010

IapticError_6777010: string

Unknown error

IapticError_6777011

IapticError_6777011: string

Failed to refresh the purchase receipt

IapticError_6777012

IapticError_6777012: string

The product identifier is invalid

IapticError_6777013

IapticError_6777013: string

Cannot finalize a transaction or acknowledge a purchase

IapticError_6777014

IapticError_6777014: string

Failed to communicate with the server

IapticError_6777015

IapticError_6777015: string

Subscriptions are not available

IapticError_6777016

IapticError_6777016: string

Purchase information is missing token

IapticError_6777017

IapticError_6777017: string

Verification of store data failed

IapticError_6777018

IapticError_6777018: string

Bad response from the server

IapticError_6777019

IapticError_6777019: string

Failed to refresh the store

IapticError_6777020

IapticError_6777020: string

Payment has expired

IapticError_6777021

IapticError_6777021: string

Failed to download the content

IapticError_6777022

IapticError_6777022: string

Failed to update a subscription

IapticError_6777023

IapticError_6777023: string

The requested product is not available in the store

IapticError_6777024

IapticError_6777024: string

The user has not allowed access to Cloud service information

IapticError_6777025

IapticError_6777025: string

The device could not connect to the network

IapticError_6777026

IapticError_6777026: string

The user has revoked permission to use this cloud service

IapticError_6777027

IapticError_6777027: string

The user has not yet acknowledged Apple's privacy policy

IapticError_6777028

IapticError_6777028: string

The app is attempting to use a property without required entitlement

IapticError_6777029

IapticError_6777029: string

The offer identifier is invalid

IapticError_6777030

IapticError_6777030: string

The price specified in App Store Connect is no longer valid

IapticError_6777031

IapticError_6777031: string

The signature in a payment discount is not valid

IapticError_6777032

IapticError_6777032: string

Parameters are missing in a payment discount

IapticError_6778003

IapticError_6778003: string

Subscription has expired

IapticError_StoreAlreadyInitialized

IapticError_StoreAlreadyInitialized: string

IapticRN.store is already initialized, call IapticRN.destroy() first

IapticError_StoreNotInitialized

IapticError_StoreNotInitialized: string

IapticRN.store is not initialized, call IapticRN.initialize() first

IapticError_UnsupportedPlatform

IapticError_UnsupportedPlatform: string

Unsupported platform

IapticRN_initialized_called

IapticRN_initialized_called: string

IapticRN.initialize() can only be called once

ProductPrice_StartingAt

ProductPrice_StartingAt: string

"starting at {0} per month" - {0} will be replaced with price component

ProgrammingError

ProgrammingError: string

Programming Error

PurchaseError_E_ALREADY_OWNED

PurchaseError_E_ALREADY_OWNED: string

This item has already been purchased.

PurchaseError_E_BILLING_RESPONSE_JSON_PARSE_ERROR

PurchaseError_E_BILLING_RESPONSE_JSON_PARSE_ERROR: string

Failed to parse the billing response.

PurchaseError_E_DEFERRED_PAYMENT

PurchaseError_E_DEFERRED_PAYMENT: string

The payment has been deferred.

PurchaseError_E_DEVELOPER_ERROR

PurchaseError_E_DEVELOPER_ERROR: string

An error occurred in the application.

PurchaseError_E_IAP_NOT_AVAILABLE

PurchaseError_E_IAP_NOT_AVAILABLE: string

In-app purchases are not available.

PurchaseError_E_INTERRUPTED

PurchaseError_E_INTERRUPTED: string

The operation was interrupted.

PurchaseError_E_ITEM_UNAVAILABLE

PurchaseError_E_ITEM_UNAVAILABLE: string

The requested product is not available.

PurchaseError_E_NETWORK_ERROR

PurchaseError_E_NETWORK_ERROR: string

A network error occurred.

PurchaseError_E_NOT_ENDED

PurchaseError_E_NOT_ENDED: string

The transaction has not been ended.

PurchaseError_E_NOT_PREPARED

PurchaseError_E_NOT_PREPARED: string

The purchase cannot be completed because it has not been prepared.

PurchaseError_E_RECEIPT_FAILED

PurchaseError_E_RECEIPT_FAILED: string

Failed to validate receipt.

PurchaseError_E_RECEIPT_FINISHED_FAILED

PurchaseError_E_RECEIPT_FINISHED_FAILED: string

Failed to finish the transaction.

PurchaseError_E_REMOTE_ERROR

PurchaseError_E_REMOTE_ERROR: string

A remote error occurred.

PurchaseError_E_SERVICE_ERROR

PurchaseError_E_SERVICE_ERROR: string

The service returned an error.

PurchaseError_E_UNKNOWN

PurchaseError_E_UNKNOWN: string

An unknown error occurred.

PurchaseError_E_USER_CANCELLED

PurchaseError_E_USER_CANCELLED: string

The user cancelled the purchase.

PurchaseError_E_USER_ERROR

PurchaseError_E_USER_ERROR: string

An error occurred in the application.

PurchaseError_title

PurchaseError_title: string

Purchase Error #{0}

SubscriptionView_Back

SubscriptionView_Back: string

"Back"

SubscriptionView_BillingOptions

SubscriptionView_BillingOptions: string

"Billing Options"

SubscriptionView_Cancel

SubscriptionView_Cancel: string

Cancel

SubscriptionView_ChangePlan

SubscriptionView_ChangePlan: string

"Change Plan"

SubscriptionView_Close

SubscriptionView_Close: string

"Close"

SubscriptionView_Continue

SubscriptionView_Continue: string

"Continue"

SubscriptionView_CurrentPlan

SubscriptionView_CurrentPlan: string

"Current Plan"

SubscriptionView_CurrentSubscription

SubscriptionView_CurrentSubscription: string

"Your Subscription"

SubscriptionView_Includes

SubscriptionView_Includes: string

"Includes:"

SubscriptionView_PleaseWait

SubscriptionView_PleaseWait: string

Please wait...

SubscriptionView_Processing

SubscriptionView_Processing: string

"Processing..."

SubscriptionView_ProcessingStatus_cancelled

SubscriptionView_ProcessingStatus_cancelled: string

"Cancelled"

SubscriptionView_ProcessingStatus_completed

SubscriptionView_ProcessingStatus_completed: string

Completed

SubscriptionView_ProcessingStatus_finishing

SubscriptionView_ProcessingStatus_finishing: string

Finalizing purchase...

SubscriptionView_ProcessingStatus_processing

SubscriptionView_ProcessingStatus_processing: string

Processing...

SubscriptionView_ProcessingStatus_purchasing

SubscriptionView_ProcessingStatus_purchasing: string

Purchasing...

SubscriptionView_ProcessingStatus_validating

SubscriptionView_ProcessingStatus_validating: string

Validating receipt...

SubscriptionView_ProcessingTitle

SubscriptionView_ProcessingTitle: string

Purchasing...

SubscriptionView_RestoreProgress

SubscriptionView_RestoreProgress: string

"Processed {0} of {1} purchases"

SubscriptionView_RestorePurchase

SubscriptionView_RestorePurchase: string

"Restore Purchases"

SubscriptionView_RestoringTitle

SubscriptionView_RestoringTitle: string

"Restoring..."

SubscriptionView_TermsLink

SubscriptionView_TermsLink: string

"Terms and Conditions"

SubscriptionView_TermsPrefix

SubscriptionView_TermsPrefix: string

"By subscribing, you agree to our"

SubscriptionView_Title

SubscriptionView_Title: string

"Choose Your Plan"

SubscriptionView_UpdatePlan

SubscriptionView_UpdatePlan: string

"Update Plan"

UnknownError

UnknownError: string

An unknown error occurred.

UnknownError_title

UnknownError_title: string

Unknown Error

ValidationError

ValidationError: string

Receipt Validation Error

ValidationError_MissingTransactionId

ValidationError_MissingTransactionId: string

Transaction ID is missing


IapticOffer

Pricing offer for an In-App Product

Properties

id

id: string

Offer identifier

offerToken?

optional offerToken: string

Offer token (if any)

offerType

offerType: "Default" | "Introductory" | "Subscription"

Type of offer

platform

platform: IapticPurchasePlatform

Platform of the product

pricingPhases

pricingPhases: IapticPricingPhase[]

Pricing phases for this offer

productGroup?

optional productGroup: null | string

Subscription group (if any)

productId

productId: string

Product identifier

productType?

optional productType: IapticProductType

Type of product (subscription, consumable, etc.)


IapticPendingPurchase

Keep the state of a potential purchase in progress

Properties

offerId?

optional offerId: string

Identifier of the offer that is being purchased

productId

productId: string

Product identifier

status

status: IapticPendingPurchaseState

Status of the purchase


IapticPricingPhase

Description of a phase for the pricing of a purchase.

See

IapticOffer.pricingPhases

Properties

billingCycles?

optional billingCycles: number

Number of recurrence cycles (if recurrenceMode is FINITE_RECURRING)

billingPeriod?

optional billingPeriod: string

ISO 8601 duration of the period (https://en.wikipedia.org/wiki/ISO_8601#Durations)

currency?

optional currency: string

Currency code

paymentMode?

optional paymentMode: IapticPaymentMode

Payment mode for the pricing phase ("PayAsYouGo", "UpFront", or "FreeTrial")

price

price: string

priceMicros

priceMicros: number

Price in micro-units (divide by 1000000 to get numeric price)

recurrenceMode?

optional recurrenceMode: IapticRecurrenceMode

Type of recurring payment


IapticProduct

Product metadata from the store

Properties

countryCode?

optional countryCode: string

Country code of the product

description?

optional description: string

Description of the product provided by the store

entitlements?

optional entitlements: string[]

Entitlements this product will give to the user, can be used for subscription and non-consumable products.

Use iapticRN.checkEntitlement("my-entitlement") to check if the user owns any product that provides this entitlement.

id

id: string

Product identifier on the store (unique per platform)

offers

offers: IapticOffer[]

List of offers available for this product

platform

platform: IapticPurchasePlatform

Platform of the product

title?

optional title: string

Title of the product provided by the store

tokenType?

optional tokenType: string

Type of token this product will give to the user for consumable products.

For example: "coin", "gem", "silver", etc.

tokenValue?

optional tokenValue: number

Amount of tokens this product will give to the user for consumable products.

Example
{ id: 'coins_100', type: 'consumable', tokenType: 'coin', tokenValue: 100 },
type

type: IapticProductType

Type of product (subscription, consumable, etc.)


IapticProductDefinition

Interface defining an in-app purchase product

Properties

entitlements?

optional entitlements: string[]

Entitlements this product will give to the user, can be used for subscription and non-consumable products.

Use iapticRN.checkEntitlement("my-entitlement") to check if the user owns any product that provides this entitlement.

id

id: string

Unique identifier of the product

tokenType?

optional tokenType: string

Type of token this product will give to the user for consumable products.

For example: "coin", "gem", "silver", etc.

tokenValue?

optional tokenValue: number

Amount of tokens this product will give to the user for consumable products.

Example
{ id: 'coins_100', type: 'consumable', tokenType: 'coin', tokenValue: 100 },
type

type: IapticProductType

Type of the product (subscription, consumable, or non-consumable)


IapticSubscriptionViewProps

Props for IapticSubscriptionView Component

Example

// Basic usage example:
<IapticSubscriptionView
  entitlementLabels={{ premium: 'Premium Features' }}
  styles={{ productCard: { backgroundColor: '#FFF' }}}
/>

Properties

entitlementLabels?

optional entitlementLabels: Record<string, { detail: string; label: string; }>

Localized descriptions for each entitlement/feature

Default
{}
Example
{ 
   *   premium: { label: 'Premium Features', detail: 'Unlimited Downloads' },
   *   adFree: { label: 'Ad-Free', detail: 'Remove All Ads While Watching Videos' }
   * }
See
  • IapticRN.listEntitlements
  • IapticProductDefinition.entitlements
onPurchaseComplete()?

optional onPurchaseComplete: () => void

Callback when a purchase is complete (show a thank you message or whatever)

Returns

void

Example
onPurchaseComplete={() => console.log('Purchase complete')}
showRestorePurchase?

optional showRestorePurchase: boolean

Show restore purchases button when there's no active subscription

Default
true
sortProducts?

optional sortProducts: boolean

Sort products by number of entitlements (most first)

Default
true
Example
sortProducts={false} // Disable automatic sorting
styles?

optional styles: Partial<IapticSubscriptionViewStyles>

Custom styles for component elements (merges with defaults)

Example
styles={{
  modalContainer: { backgroundColor: 'rgba(0,0,0,0.8)' },
  ctaButton: { backgroundColor: '#FF3B30' }
}}
termsUrl?

optional termsUrl: string

URL to Terms & Conditions (optional)

Example
termsUrl="https://example.com/terms"
theme?

optional theme: Partial<IapticTheme>

Theme configuration for colors

Example
theme={{ primaryColor: '#FF3B30', backgroundColor: '#F5F5F5' }}
visible?

optional visible: boolean

Controls visibility of the modal

Default
false

IapticTheme

Theme configuration for Iaptic components

Example

{
 *   primaryColor: '#007AFF',
 *   secondaryColor: '#4CAF50',
 *   backgroundColor: '#FFFFFF',
 *   textColor: '#1A1A1A',
 *   secondaryTextColor: '#666666',
 *   borderColor: '#EEEEEE',
 *   successColor: '#4CAF50',
 *   warningColor: '#FF9800',
 *   errorColor: '#FF3B30'
 * }

Properties

backgroundColor

backgroundColor: string

Background color for modals/cards

borderColor

borderColor: string

Border and divider colors

errorColor?

optional errorColor: string

Error states color

primaryColor

primaryColor: string

Primary brand color for buttons, highlights

secondaryColor

secondaryColor: string

Secondary color for current plan badges, success states

secondaryTextColor

secondaryTextColor: string

Secondary/subdued text color

successColor?

optional successColor: string

Success states color

textColor

textColor: string

Primary text color

warningColor?

optional warningColor: string

Warning states color


IapticTokenTransaction

A transaction that has occurred.

Properties

amount

amount: number

Number of tokens earned (positive) or spent (negative) for this transaction

timestamp

timestamp: number

When the transaction occurred

transactionId

transactionId: string

Unique identifier from the store

type

type: string

Type of token (e.g., 'gem', 'coin', 'credit')


IapticVerifiedPurchase

Purchase verified by the receipt validator.

Properties

cancelationReason?

optional cancelationReason: IapticCancelationReason

The reason a subscription or purchase was cancelled.

discountId?

optional discountId: string

Identifier of the discount currently applied to a purchase.

Correspond to the product's offerId. When undefined it means there is only one offer for the given product.

expiryDate?

optional expiryDate: number

Date of expiry for a subscription.

id

id: string

Product identifier

Deprecated

Use productId instead

isAcknowledged?

optional isAcknowledged: boolean

True when a purchase has been acknowledged

isBillingRetryPeriod?

optional isBillingRetryPeriod: boolean

True when a subscription a subscription is in the grace period after a failed attempt to collect payment

isExpired?

optional isExpired: boolean

True when a subscription is expired.

isIntroPeriod?

optional isIntroPeriod: boolean

True when a subscription is in introductory pricing period

isTrialPeriod?

optional isTrialPeriod: boolean

True when a subscription is in trial period

lastRenewalDate?

optional lastRenewalDate: number

Last time a subscription was renewed.

platform?

optional platform: IapticPurchasePlatform

Platform this purchase was made on

priceConsentStatus?

optional priceConsentStatus: IapticPriceConsentStatus

Whether or not the user agreed or has been notified of a price change.

productId

productId: string

Product identifier

purchaseDate?

optional purchaseDate: number

Date of first purchase (timestamp).

purchaseId?

optional purchaseId: string

Purchase identifier (optional)

renewalIntent?

optional renewalIntent: "Renew" | "Lapse"

Whether or not the user intends to let the subscription auto-renew.

Possible values:

  • "Renew" - The user intends to renew the subscription.
  • "Lapse" - The user intends to let the subscription expire without renewing.
renewalIntentChangeDate?

optional renewalIntentChangeDate: number

Date the renewal intent was updated by the user.

transactionId?

optional transactionId: string

Identifier of the last transaction (optional)

Type Aliases

IapticEventListener()<T>

IapticEventListener<T>: (...args) => void

Type-safe event listener function

Type Parameters

T extends IapticEventType

Parameters

args

...IapticEventMap[T]

Returns

void


IapticEventType

IapticEventType: "products.updated" | "purchase.updated" | "subscription.updated" | "subscription.renewed" | "subscription.cancelled" | "subscription.expired" | "subscription.changed" | "pendingPurchase.updated" | "nonConsumable.updated" | "nonConsumable.owned" | "nonConsumable.unowned" | "consumable.purchased" | "consumable.refunded" | "error"

All possible event types that can be listened to.

  • products.updated - When any product metadata is updated (title, price, description, etc.)
  • purchase.updated - When any purchase is updated (subscription, consumable, non-consumable)
  • subscription.updated - When a subscription is updated (renewed, cancelled, expired, changed)
  • subscription.renewed - When a subscription is renewed
  • subscription.cancelled - When a subscription is cancelled
  • subscription.expired - When a subscription is expired
  • subscription.changed - When a subscription is changed
  • pendingPurchase.updated - When a pending purchase status changes
  • nonConsumable.updated - When a non-consumable status changes (owned, unowned)
  • nonConsumable.owned - When a non-consumable purchase is owned
  • nonConsumable.unowned - When a non-consumable purchase is no longer owned
  • consumable.purchased - When a consumable purchase is purchased
  • consumable.refunded - When a consumable purchase is refunded
  • error - When an error occurs in the background

IapticPaymentMode

IapticPaymentMode: "PayAsYouGo" | "UpFront" | "FreeTrial"

Mode of payment


IapticPendingPurchaseState

IapticPendingPurchaseState: "purchasing" | "processing" | "validating" | "finishing" | "completed" | "cancelled"

Status of a purchase being processed.


IapticProductType

IapticProductType: "application" | "paid subscription" | "non renewing subscription" | "consumable" | "non consumable"

Product types supported by the iaptic validator


IapticRecurrenceMode

IapticRecurrenceMode: "NON_RECURRING" | "FINITE_RECURRING" | "INFINITE_RECURRING"

Type of recurring payment

  • FINITE_RECURRING: Payment recurs for a fixed number of billing period set in paymentPhase.cycles.
  • INFINITE_RECURRING: Payment recurs for infinite billing periods unless cancelled.
  • NON_RECURRING: A one time charge that does not repeat.

IapticSubscriptionReason

IapticSubscriptionReason: "renewed" | "cancelled" | "expired" | "changed"

Reason why a subscription status changed


IapticSupportedLocales

IapticSupportedLocales: "en" | "en_uk" | "en_au" | "es" | "fr" | "de" | "ja" | "zh" | "pt"

List of supported languages.

Functions

IapticSubscriptionView()

IapticSubscriptionView(props): null | Element

Subscription modal UI component

Parameters

props

IapticSubscriptionViewProps

Propertis

Returns

null | Element

Remarks

React Component

Example

<IapticSubscriptionView
  entitlementLabels={{
    premium: { label: 'Premium Features', detail: 'Unlimited Downloads' },
    adFree: { label: 'Ad-Free', detail: 'Remove All Ads While Watching Videos' }
  }},
  termsUrl="https://example.com/terms"
/>