Security News
Research
Supply Chain Attack on Rspack npm Packages Injects Cryptojacking Malware
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
react-native-iap
Advanced tools
We are willing to share same in-app-purchase experience for both android and ios platform and will continuously merge methods which are standing alone.
Android iap is implemented with iap version 3 which is currently recent.
react-native-iap
module versions that are not described in change logs
may not run as expected so please refer to version mentioned in Changelogs
below.
0.3.0-alpha
has released. All the methods are renamed and current methods are merged into each single method. See Methods
section below to see what's been changed.
Breaking changes have made from 0.2.17
. refreshAllItems
has changed name to fetchHistory
. See the changelogs below.
Breaking changes have made from 0.2.16
in android. Package name has been fixed to com.dooboolab.RNIap.RNIapPackage
. Read the changelogs below. There was linking issue with wrong package name.
Breaking changes have made from 0.2.12
. Please read the changelogs below. The summary of change is that it now returns receipt in different format.
Changes from react-native-iap@0.1.*
to react-native-iap@0.2.*
is that you have prepare()
method deprecated which you should call before using RNIap
methods. Now you have to call prepareAndroid()
instead just to know that it is just android dependent method.
Also to import module, previously in react-native-iap@0.1.*
you had to import RNIap from 'react-native-iap'
but now you have to do like import * as RNIap from 'react-native-iap'
.
For new method, refreshAllItems has been implemented for both ios and android. This feature will support senario for non-consumable products.
Also there are some other methods that is not supported in ios and implemented in android. You can see more in Changelogs below.
Lastly, this module also supports types for typescript users from 0.2.5
.
prepare
, getProducts
, getSubscriptions
, getPurchaseHistory
, getAvailablePurchases
, buySubscription
, buyProduct
, consumeProduct
. Please compare these methods with your previous methods used in 0.2.*
if you want to upgrade to 0.3.0
.refreshAllItems
has changed name to fetchHistory
since android and ios had different functionality and fixed to fetching history of purchases.com.reactlibrary.RNIapPackage
to com.dooboolab.RNIap.RNIapPackage
;.buySubscribeItem
callback.homepage
now is mandatory attribute in cocoapods from pull request.buyItem
cancel callback.Func | Param | Return | Description |
---|---|---|---|
prepare | Promise<void> | Prepare IAP module. Must be called on Android before any other purchase flow methods. No-op on iOS. | |
getProducts | string[] Product IDs/skus | Promise<Product[]> | Get a list of products (consumable and non-consumable items, but not subscriptions). Note: On iOS versions earlier than 11.2 this method will return subscriptions if they are included in your list of SKUs. This is because we cannot differentiate between IAP products and subscriptions prior to 11.2. |
getSubscriptions | string[] Subscription IDs/skus | Promise<Subscription[]> | Get a list of subscriptions. Note: On iOS versions earlier than 11.2 this method has the same output as getProducts . This is because we cannot differentiate between IAP products and subscriptions prior to 11.2. |
getPurchaseHistory | Promise<Purchase[]> | Gets an invetory of purchases made by the user regardless of consumption status (where possible) | |
getAvailablePurchases | Promise<Purchase[]> | Get all purchases made by the user (either non-consumable, or haven't been consumed yet) | |
buySubscription | string Subscription ID/sku | Promise<Purchase> | Create (buy) a subscription to a sku |
buyProduct | string Product ID/sku | Promise<Purchase> | Buy a product |
consumeProduct | string Purchase token | Promise<void> | Consume a product (on Android.) No-op on iOS. |
https://www.npmjs.com/package/react-native-iap
https://github.com/dooboolab/react-native-iap
$ npm install react-native-iap --save
$ react-native link react-native-iap
Libraries
➜ Add Files to [your project's name]
node_modules
➜ react-native-iap
and add RNIap.xcodeproj
libRNIap.a
to your project's Build Phases
➜ Link Binary With Libraries
Cmd+R
)<android/app/src/main/java/[...]/MainActivity.java
import com.reactlibrary.RNIapPackage;
to the imports at the top of the filenew RNIapPackage()
to the list returned by the getPackages()
methodandroid/settings.gradle
:
include ':react-native-iap'
project(':react-native-iap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-iap/android')
android/app/build.gradle
:
compile project(':react-native-iap')
You can look in the RNIapExample folder to try the example. Below is basic implementation which is also provided in RNIapExample project.
First thing you should do is to define your items for iOS and android separately like defined below.
import * as RNIap from 'react-native-iap';
const itemSkus = Platform.select({
ios: [
'com.example.coins100'
],
android: [
'com.example.coins100'
]
});
Next, call the prepare function (ios it's not needed, but android it is. No need to check platform though since nothing will happen in ios:
async function() {
try {
await RNIap.prepare();
// Ready to call RNIap.getProducts(), etc.
} catch(err) {
console.warn(err); // standardized err.code and err.message available
}
}
Once you called prepare(), call getProducts(). Both are async funcs. You can do it in componentDidMount(), or other area as appropriate for you app. Since a user may first start your app with a bad internet connection, then later have an internet connection, making preparing/getting items more than once may be a good idea. Like if the user has no IAPs available when the app first starts, you may want to check again when the user enters the your IAP store.
async componentDidMount() {
try {
await RNIap.prepare();
const products = await RNIap.getProducts(itemSkus);
this.setState({ items });
} catch(err) {
console.warn(err); // standardized err.code and err.message available
}
}
iOS | Android | Comment | |
---|---|---|---|
price | ✓ | ✓ | Will return localizedPrice on Android (default) or a string price (eg. 1.99 ) (iOS) |
productId | ✓ | ✓ | Returns a string needed to purchase the item later |
currency | ✓ | ✓ | Returns the currency code |
localizedPrice | ✓ | ✓ | Use localizedPrice if you want to display the price to the user so you don't need to worry about currency symbols. |
title | ✓ | ✓ | Returns the title Android and localizedTitle on iOS |
description | ✓ | ✓ | Returns the description of the product |
type | ✓ | ✓ | Returns SKU type (subscription or in-app product). iOS < 11.2 will always return null |
Once you have called getProducts(), and you have a valid response, you can call buyProduct().
// Will return a purchase object with a receipt which can be used to validate on your server.
const purchase = await RNIap.buyProduct('com.example.coins100');
In RNIapExample, upon receiving receiving a purchase receipt, main page will navigate to Second.js.
this.setState({ progressTitle: 'Please wait...' });
RNIap.buyProduct('com.example.coins100').then(purchase => {
this.setState({
receipt: purchase.transactionReceipt, // save the receipt if you need it, whether locally, or to your server.
progressTitle: 'Purchase Successful!',
coins: this.state.coins + 100
});
}).catch(err => {
// resetting UI
console.warn(err); // standardized err.code and err.message available
this.setState({ progressTitle: 'Buy 100 Coins for only $0.99' });
alert(err.message);
})
Subscribable products can be purchased just like consumable products. Users can cancel subscriptions by using the iOS System Settings.
You can use getAvailablePurchases()
to do what's commonly understood as "restoring" purchases. Once an item is consumed, it will no longer be available in getAvailablePurchases()
and will only be available via getPurchaseHistory()
. However, this method has some caviats on Android -- namely that purchase history only exists for the single most recent purchase of each SKU -- so your best bet is to track consumption in your app yourself. By default all items that are purchased will not be consumed unless they are automatically consumed by the store (for example, if you create a consumable item for iOS.) This means that you must manage consumption yourself. Purchases can be consumed by calling consumePurchase()
. If you want to consume all items, you have to iterate over the purchases returned by getAvailablePurchases()
.
getPurchases = async() => {
try {
const purchases = await RNIap.getAvailablePurchases();
let restoredTitles = '';
let coins = CoinStore.getCount();
purchases.forEach(purchase => {
if (purchase.productId == 'com.example.premium') {
this.setState({ premium: true });
restoredTitles += 'Premium Version';
} else if (purchase.productId == 'com.example.no_ads') {
this.setState({ ads: false });
restoredTitles += restoredTitles.length > 0 ? 'No Ads' : ', No Ads';
} else if (purchase.productId == 'com.example.coins100') {
CoinStore.addCoins(100);
await RNIap.consumePurchase(purchase.transactionReceipt);
}
})
Alert.alert('Restore Successful', 'You successfully restored the following purchases: ' + restoredTitles);
} catch(err) {
console.warn(err); // standardized err.code and err.message available
Alert.alert(err.message);
}
}
Returned purchases is an array of each purchase transaction with the following keys:
{
transactionDate,
transactionId,
productId,
transactionReceipt,
purchaseToken, // available on Android (same as transactionReceipt)
autoRenewing, // available on Android
originalTransactionDate, // available on iOS
originalTransactionIdentifier // available on iOS
}
You need to test with one sandbox account, because the account holds previous purchase history.
Nothing at the moment.
Thanks.
by JJMoon and dooboolab.
FAQs
React Native In App Purchase Module.
The npm package react-native-iap receives a total of 45,335 weekly downloads. As such, react-native-iap popularity was classified as popular.
We found that react-native-iap demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.
Security News
Sonar’s acquisition of Tidelift highlights a growing industry shift toward sustainable open source funding, addressing maintainer burnout and critical software dependencies.