modules
react-native-iap / Exports
react-native-iap
Table of contents
References
- AmazonModule
- AmazonModuleProps
- AndroidModule
- AndroidModuleProps
- BuyItemByType
- BuyProduct
- IosModuleProps
- acknowledgePurchaseAndroid
- buyPromotedProductIOS
- clearProductsIOS
- clearTransactionIOS
- deepLinkToSubscriptionsAmazon
- deepLinkToSubscriptionsAndroid
- deepLinkToSubscriptionsIos
- getInstallSourceAndroid
- getPendingPurchasesIOS
- getPromotedProductIOS
- getReceiptIOS
- isFeatureSupported
- presentCodeRedemptionSheetIOS
- validateReceiptAmazon
- validateReceiptAndroid
- validateReceiptIos
- verifyLicense
Namespaces
Enumerations
- ErrorCode
- InstallSourceAndroid
- ProductType
- PurchaseStateAndroid
- ReplacementModesAndroid
- SubscriptionPlatform
- TransactionReason
Classes
Interfaces
- Discount
- NativeModuleProps
- PricingPhaseAndroid
- ProductAndroid
- ProductCommon
- ProductIOS
- ProductPurchase
- PurchaseResult
- RequestPurchaseAndroid
- RequestPurchaseBaseAndroid
- RequestPurchaseIOS
- RequestSubscriptionAndroid
- SubscriptionAmazon
- SubscriptionAndroid
- SubscriptionIOS
- SubscriptionOffer
- SubscriptionOfferAndroid
- SubscriptionPurchase
Type Aliases
- Product
- Purchase
- RequestPurchase
- RequestPurchaseAmazon
- RequestSubscription
- RequestSubscriptionAmazon
- RequestSubscriptionIOS
- STOREKIT_OPTIONS
- Sku
- Subscription
- SubscriptionIosPeriod
Variables
Functions
- deepLinkToSubscriptions
- endConnection
- finishTransaction
- flushFailedPurchasesCachedAsPendingAndroid
- getAvailablePurchases
- getProducts
- getPurchaseHistory
- getSubscriptions
- initConnection
- isIosStorekit2
- promotedProductListener
- purchaseErrorListener
- purchaseUpdatedListener
- requestPurchase
- requestSubscription
- setup
- transactionListener
- useIAP
- useIAPContext
- withIAPContext
References
AmazonModule
Re-exports AmazonModule
AmazonModuleProps
Re-exports AmazonModuleProps
AndroidModule
Re-exports AndroidModule
AndroidModuleProps
Re-exports AndroidModuleProps
BuyItemByType
Re-exports BuyItemByType
BuyProduct
Re-exports BuyProduct
IosModuleProps
Re-exports IosModuleProps
acknowledgePurchaseAndroid
Re-exports acknowledgePurchaseAndroid
buyPromotedProductIOS
Re-exports buyPromotedProductIOS
clearProductsIOS
Re-exports clearProductsIOS
clearTransactionIOS
Re-exports clearTransactionIOS
deepLinkToSubscriptionsAmazon
Re-exports deepLinkToSubscriptionsAmazon
deepLinkToSubscriptionsAndroid
Re-exports deepLinkToSubscriptionsAndroid
deepLinkToSubscriptionsIos
Re-exports deepLinkToSubscriptionsIos
getInstallSourceAndroid
Re-exports getInstallSourceAndroid
getPendingPurchasesIOS
Re-exports getPendingPurchasesIOS
getPromotedProductIOS
Re-exports getPromotedProductIOS
getReceiptIOS
Re-exports getReceiptIOS
isFeatureSupported
Re-exports isFeatureSupported
presentCodeRedemptionSheetIOS
Re-exports presentCodeRedemptionSheetIOS
validateReceiptAmazon
Re-exports validateReceiptAmazon
validateReceiptAndroid
Re-exports validateReceiptAndroid
validateReceiptIos
Re-exports validateReceiptIos
verifyLicense
Re-exports verifyLicense
Type Aliases
Product
Ƭ Product: ProductAndroid
& ProductIOS
Defined in
Purchase
Ƭ Purchase: ProductPurchase
| SubscriptionPurchase
Defined in
RequestPurchase
Ƭ RequestPurchase: RequestPurchaseAndroid
| RequestPurchaseAmazon
| RequestPurchaseIOS
Defined in
RequestPurchaseAmazon
Ƭ RequestPurchaseAmazon: RequestPurchaseIOS
As of 2022-10-12, we only use the sku
field for Amazon purchases
Defined in
RequestSubscription
Ƭ RequestSubscription: RequestSubscriptionAndroid
| RequestSubscriptionAmazon
| RequestSubscriptionIOS
Defined in
RequestSubscriptionAmazon
Ƭ RequestSubscriptionAmazon: RequestSubscriptionIOS
As of 2022-10-12, we only use the sku
field for Amazon subscriptions
Defined in
RequestSubscriptionIOS
Ƭ RequestSubscriptionIOS: RequestPurchaseIOS
Defined in
STOREKIT_OPTIONS
Ƭ STOREKIT_OPTIONS: "STOREKIT1_MODE"
| "STOREKIT_HYBRID_MODE"
| "STOREKIT2_MODE"
STOREKIT1_MODE: Will not enable Storekit 2 even if the device supports it. Thigs will work as before, minimum changes required in the migration guide (default) HYBRID_MODE: Will enable Storekit 2 for iOS devices > 15.0 but will fallback to Sk1 on older devices There are some edge cases that you need to handle in this case (described in migration guide). This mode is for developers that are migrating to Storekit 2 but want to keep supporting older versions. STOREKIT2_MODE: Will only enable Storekit 2. This disables Storekit 1. This is for apps that have already targeted a min version of 15 for their app.
Defined in
Sku
Ƭ Sku: string
Defined in
Subscription
Ƭ Subscription: SubscriptionAndroid
| SubscriptionAmazon
| SubscriptionIOS
Defined in
SubscriptionIosPeriod
Ƭ SubscriptionIosPeriod: "DAY"
| "WEEK"
| "MONTH"
| "YEAR"
| ""
Defined in
Variables
PROMOTED_PRODUCT
• Const
PROMOTED_PRODUCT: "iap-promoted-product"
Defined in
Functions
deepLinkToSubscriptions
▸ deepLinkToSubscriptions(«destructured»
): Promise
\<void
>
Deeplinks to native interface that allows users to manage their subscriptions
Parameters
Name | Type |
---|---|
«destructured» | Object |
› isAmazonDevice? | boolean |
› sku? | string |
Returns
Promise
\<void
>
Defined in
endConnection
▸ endConnection(): Promise
\<boolean
>
Disconnects from native SDK Usage
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {endConnection} from 'react-native-iap';
const App = () => {
useEffect(() => {
return () => {
void endConnection();
};
}, []);
return <View />;
};
Returns
Promise
\<boolean
>
Defined in
finishTransaction
▸ finishTransaction(«destructured»
): Promise
\<boolean
| PurchaseResult
>
Finish Transaction (both platforms)
Abstracts Finish Transaction
iOS: Tells StoreKit that you have delivered the purchase to the user and StoreKit can now let go of the transaction.
Call this after you have persisted the purchased state to your server or local data in your app.
react-native-iap
will continue to deliver the purchase updated events with the successful purchase until you finish the transaction. Even after the app has relaunched.
Android: it will consume purchase for consumables and acknowledge purchase for non-consumables.
import React from 'react';
import {Button} from 'react-native';
import {finishTransaction} from 'react-native-iap';
const App = () => {
const handlePurchase = async () => {
// ... handle the purchase request
const result = finishTransaction({purchase});
};
return <Button title="Buy product" onPress={handlePurchase} />;
};
Parameters
Name | Type |
---|---|
«destructured» | Object |
› developerPayloadAndroid? | string |
› isConsumable? | boolean |
› purchase | Purchase |
Returns
Promise
\<boolean
| PurchaseResult
>
Android: PurchaseResult, iOS: true
Defined in
flushFailedPurchasesCachedAsPendingAndroid
▸ flushFailedPurchasesCachedAsPendingAndroid(): Promise
\<boolean
>
Consume all 'ghost' purchases (that is, pending payment that already failed but is still marked as pending in Play Store cache). Android only.
Returns
Promise
\<boolean
>
Defined in
getAvailablePurchases
▸ getAvailablePurchases(:boolean?
): Promise
\<Purchase
[]>
Get all purchases made by the user (either non-consumable, or haven't been consumed yet)
Usage
import React, {useCallback} from 'react';
import {View} from 'react-native';
import {getAvailablePurchases} from 'react-native-iap';
const App = () => {
const availablePurchases = useCallback(
async () => await getAvailablePurchases(),
[],
);
return <View />;
};
Restoring purchases
You can use getAvailablePurchases()
to do what's commonly understood as "restoring" purchases.
For debugging you may want to consume all items, you have then to iterate over the purchases returned by getAvailablePurchases()
.
Beware that if you consume an item without having recorded the purchase in your database the user may have paid for something without getting it delivered and you will have no way to recover the receipt to validate and restore their purchase.
import React from 'react';
import {Button} from 'react-native';
import {getAvailablePurchases,finishTransaction} from 'react-native-iap';
const App = () => {
handleRestore = async () => {
try {
const purchases = await getAvailablePurchases();
const newState = {premium: false, ads: true};
let titles = [];
await Promise.all(purchases.map(async purchase => {
switch (purchase.productId) {
case 'com.example.premium':
newState.premium = true;
titles.push('Premium Version');
break;
case 'com.example.no_ads':
newState.ads = false;
titles.push('No Ads');
break;
case 'com.example.coins100':
await finishTransaction({purchase});
CoinStore.addCoins(100);
}
}));
Alert.alert(
'Restore Successful',
`You successfully restored the following purchases: ${titles.join(', ')}`,
);
} catch (error) {
console.warn(error);
Alert.alert(error.message);
}
};
return (
<Button title="Restore purchases" onPress={handleRestore} />
)
};
Parameters
Name | Type | Description |
---|---|---|
:boolean | Object | When true , every element will also be pushed to the purchaseUpdated listener. Note that this is only for backaward compatiblity. It won't publish to transactionUpdated (Storekit2) Defaults to false |
:boolean.alsoPublishToEventListener? | boolean | - |
:boolean.automaticallyFinishRestoredTransactions? | boolean | - |
:boolean.onlyIncludeActiveItems? | boolean | - |
Returns
Promise
\<Purchase
[]>
See
https://developer.apple.com/documentation/storekit/transaction/3851204-currententitlements for details
Defined in
getProducts
▸ getProducts(«destructured»
): Promise
\<Product
[]>
Get a list of products (consumable and non-consumable items, but not subscriptions)
Usage
import React, {useState} from 'react';
import {Platform} from 'react-native';
import {getProducts, Product} from 'react-native-iap';
const skus = Platform.select({
ios: ['com.example.consumableIos'],
android: ['com.example.consumableAndroid'],
});
const App = () => {
const [products, setProducts] = useState<Product[]>([]);
const handleProducts = async () => {
const items = await getProducts({skus});
setProducts(items);
};
useEffect(() => {
void handleProducts();
}, []);
return (
<>
{products.map((product) => (
<Text key={product.productId}>{product.productId}</Text>
))}
</>
);
};
Just a few things to keep in mind:
- You can get your products in
componentDidMount
,useEffect
or another appropriate area of your app. - Since a user may start your app with a bad or no internet connection, preparing/getting the items more than once may be a good idea.
- If the user has no IAPs available when the app starts first, you may want to check again when the user enters your IAP store.
Parameters
Name | Type |
---|---|
«destructured» | Object |
› skus | string [] |
Returns
Promise
\<Product
[]>
Defined in
getPurchaseHistory
▸ getPurchaseHistory(«destructured»?
): Promise
\<Purchase
[]>
Gets an inventory of purchases made by the user regardless of consumption status
Usage
import React, {useCallback} from 'react';
import {View} from 'react-native';
import {getPurchaseHistory} from 'react-native-iap';
const App = () => {
const history = useCallback(
async () =>
await getPurchaseHistory([
'com.example.product1',
'com.example.product2',
]),
[],
);
return <View />;
};
Parameters
Name | Type |
---|---|
«destructured» | Object |
› alsoPublishToEventListener? | boolean |
› automaticallyFinishRestoredTransactions? | boolean |
› onlyIncludeActiveItems? | boolean |
Returns
Promise
\<Purchase
[]>
See
https://developer.apple.com/documentation/storekit/transaction/3851204-currententitlements for details
Defined in
getSubscriptions
▸ getSubscriptions(«destructured»
): Promise
\<Subscription
[]>
Get a list of subscriptions
Usage
import React, {useCallback} from 'react';
import {View} from 'react-native';
import {getSubscriptions} from 'react-native-iap';
const App = () => {
const subscriptions = useCallback(
async () =>
await getSubscriptions({skus:['com.example.product1', 'com.example.product2']}),
[],
);
return <View />;
};
Parameters
Name | Type |
---|---|
«destructured» | Object |
› skus | string [] |
Returns
Promise
\<Subscription
[]>
Defined in
initConnection
▸ initConnection(): Promise
\<boolean
>
Init module for purchase flow. Required on Android. In ios it will check whether user canMakePayment.
Usage
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {initConnection} from 'react-native-iap';
const App = () => {
useEffect(() => {
void initConnection();
}, []);
return <View />;
};
Returns
Promise
\<boolean
>
Defined in
isIosStorekit2
▸ isIosStorekit2(): boolean
Returns
boolean
Defined in
promotedProductListener
▸ promotedProductListener(listener
): null
| EmitterSubscription
Add IAP promoted subscription event Add IAP promoted subscription event.
Signature
promotedProductListener((productId?: string) => {});
Usage
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {promotedProductListener} from 'react-native-iap';
const App = () => {
useEffect(() => {
const subscription = promotedProductListener((productId) => {
console.log(productId);
});
return () => {
subscription.remove();
};
}, []);
return <View />;
};
Parameters
Name | Type |
---|---|
listener | () => void |
Returns
null
| EmitterSubscription
Platform
iOS
Defined in
purchaseErrorListener
▸ purchaseErrorListener(listener
): EmitterSubscription
Add IAP purchase error event
Register a callback that gets called when there has been an error with a purchase. Returns a React Native EmitterSubscription
on which you can call .remove()
to stop receiving updates.
Signature
purchaseErrorListener((error: PurchaseError) => {});
Usage
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {purchaseErrorListener} from 'react-native-iap';
const App = () => {
useEffect(() => {
const subscription = purchaseErrorListener((error: PurchaseError) => {
console.log(error);
});
return () => {
subscription.remove();
};
}, []);
return <View />;
};
Parameters
Name | Type |
---|---|
listener | (error : PurchaseError ) => void |
Returns
EmitterSubscription
Defined in
purchaseUpdatedListener
▸ purchaseUpdatedListener(listener
, errorCallback?
): EmitterSubscription
Add IAP purchase event
Register a callback that gets called when the store has any updates to purchases that have not yet been finished, consumed or acknowledged. Returns a React Native EmitterSubscription
on which you can call .remove()
to stop receiving updates. Register you listener as soon as possible and react to updates at all times.
Signature
purchaseUpdatedListener((purchase: Purchase) => {});
Usage
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {purchaseUpdatedListener} from 'react-native-iap';
const App = () => {
useEffect(() => {
const subscription = purchaseUpdatedListener((purchase: Purchase) => {
console.log(purchase);
});
return () => {
subscription.remove();
};
}, []);
return <View />;
};
Parameters
Name | Type |
---|---|
listener | (event : Purchase ) => void |
errorCallback? | (error : unknown ) => void |
Returns
EmitterSubscription
Defined in
requestPurchase
▸ requestPurchase(request
): Promise
\<void
| ProductPurchase
| ProductPurchase
[]>
Request a purchase for product. This will be received in PurchaseUpdatedListener
.
Request a purchase for a product (consumables or non-consumables).
The response will be received through the PurchaseUpdatedListener
.
andDangerouslyFinishTransactionAutomatically
defaults to false. We recommend
always keeping at false, and verifying the transaction receipts on the server-side.
Signature
requestPurchase(
The product's sku/ID
sku,
* You should set this to false and call finishTransaction manually when you have delivered the purchased goods to the user.
* @default false
andDangerouslyFinishTransactionAutomaticallyIOS = false,
/** Specifies an optional obfuscated string that is uniquely associated with the user's account in your app.
obfuscatedAccountIdAndroid,
Specifies an optional obfuscated string that is uniquely associated with the user's profile in your app.
obfuscatedProfileIdAndroid,
The purchaser's user ID
applicationUsername,
): Promise<ProductPurchase>;
Usage
import React, { useState, useEffect } from 'react';
import {Button} from 'react-native';
import {requestPurchase, Product, Sku, getProducts} from 'react-native-iap';
const App = () => {
const [products, setProducts] = useState<Product[]>([]);
useEffect(() => {
const fetchProducts = async () => {
const productList = await getProducts({skus:['com.example.product']});
setProducts(productList);
}
fetchProducts();
}, []);
const handlePurchase = async (sku: Sku) => {
await requestPurchase({sku});
};
return (
<>
{products.map((product) => (
<Button
key={product.productId}
title="Buy product"
onPress={() => handlePurchase(product.productId)}
/>
))}
</>
);
};
Parameters
Name | Type |
---|---|
request | RequestPurchase |
Returns
Promise
\<void
| ProductPurchase
| ProductPurchase
[]>
Defined in
requestSubscription
▸ requestSubscription(request
): Promise
\<null
| void
| SubscriptionPurchase
| SubscriptionPurchase
[]>
Request a purchase for product. This will be received in PurchaseUpdatedListener
.
Request a purchase for a subscription.
The response will be received through the PurchaseUpdatedListener
.
andDangerouslyFinishTransactionAutomatically
defaults to false. We recommend
always keeping at false, and verifying the transaction receipts on the server-side.
Signature
requestSubscription(
The product's sku/ID
sku,
* You should set this to false and call finishTransaction manually when you have delivered the purchased goods to the user.
* @default false
andDangerouslyFinishTransactionAutomaticallyIOS = false,
purchaseToken that the user is upgrading or downgrading from (Android).
purchaseTokenAndroid,
UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY, IMMEDIATE_WITH_TIME_PRORATION, IMMEDIATE_AND_CHARGE_PRORATED_PRICE, IMMEDIATE_WITHOUT_PRORATION, DEFERRED
prorationModeAndroid = -1,
/** Specifies an optional obfuscated string that is uniquely associated with the user's account in your app.
obfuscatedAccountIdAndroid,
Specifies an optional obfuscated string that is uniquely associated with the user's profile in your app.
obfuscatedProfileIdAndroid,
The purchaser's user ID
applicationUsername,
): Promise<SubscriptionPurchase>
Usage
import React, {useCallback} from 'react';
import {Button} from 'react-native';
import {
requestSubscription,
Product,
Sku,
getSubscriptions,
} from 'react-native-iap';
const App = () => {
const subscriptions = useCallback(
async () => getSubscriptions(['com.example.subscription']),
[],
);
const handlePurchase = async (sku: Sku) => {
await requestSubscription({sku});
};
return (
<>
{subscriptions.map((subscription) => (
<Button
key={subscription.productId}
title="Buy subscription"
onPress={() => handlePurchase(subscription.productId)}
/>
))}
</>
);
};
Parameters
Name | Type |
---|---|
request | RequestSubscription |
Returns
Promise
\<null
| void
| SubscriptionPurchase
| SubscriptionPurchase
[]>
Defined in
setup
▸ setup(«destructured»?
): void
Parameters
Name | Type |
---|---|
«destructured» | Object |
› storekitMode? | STOREKIT_OPTIONS |
Returns
void
Defined in
transactionListener
▸ transactionListener(listener
): null
| EmitterSubscription
Updated transactions for iOS Sk2
Register a callback that gets called when the store has any updates to transactions related to purchases that have not yet been finished, consumed or acknowledged.
Returns a React Native EmitterSubscription
on which you can call .remove()
to stop receiving updates. Register you listener as soon as possible and react to updates at all times.
*Warning** This is only available for iOS 15 and higher and Storekit 2 is activated
Signature
purchaseUpdatedListener((transactionOrError: TransactionOrError) => {});
Usage
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {purchaseUpdatedListener} from 'react-native-iap';
const App = () => {
useEffect(() => {
const subscription = purchaseUpdatedListener((transactionOrError: TransactionOrError) => {
if(transactionOrError.transaction){
console.log("There's an update to a transaction", transactionOrError.transaction);
}else{
console.log("There's been an error with a received transaction")
}
});
return () => {
subscription.remove();
};
}, []);
return <View />;
};
Parameters
Name | Type |
---|---|
listener | (event : TransactionEvent ) => void |
Returns
null
| EmitterSubscription
Platform
iOS (Sk2)
Defined in
useIAP
▸ useIAP(): IAP_STATUS
Returns
IAP_STATUS
Defined in
useIAPContext
▸ useIAPContext(): IAPContextType
Returns
IAPContextType
Defined in
withIAPContext
▸ withIAPContext\<T
>(Component
): (props
: T
) => Element
Type parameters
Name |
---|
T |
Parameters
Name | Type |
---|---|
Component | ComponentType \<T > |
Returns
fn
▸ (props
): Element
Parameters
Name | Type |
---|---|
props | T |
Returns
Element