React Native Google Play In-App Purchases
Integrating the react-native-iap library to sell products and subscriptions on Google Play.
To sell products and subscriptions on Google Play from our Android apps, let's integrate the react-native-iap library into the app. You can use the code below to add it.
import * as RNIap from 'react-native-iap';To get rid of the most common error, "PROMISE_BUY_ITEM The sku was not found. Please fetch products first by calling getItems", you can adapt the code below to your app. Before the code, let's look at why this error happens: there is a mismatch between the library's old files and its updated ones. If you stay on the old version you can use it without problems, but once the maintainers drop support you'll need the current version again, so it's worth fixing the issue on the latest version. Let's get to the integration.
Import the library
import * as RNIap from 'react-native-iap';Add the following code to the componentDidMount method of your screen
async componentDidMount() { try { const products: Product[] = await RNIap.getProducts(itemSkus); const getsub: Subscription[] = await RNIap.getSubscriptions(itemSkus); this.setState({ getsub }); } catch(err) { console.warn(err); // standardized err.code and err.message available } }Depending on your case, you can remove the async and await keywords.
Set up the state as in the code below; what happens in componentDidMount is stored in these state fields.
state= { products:[], getsub:[], count:0, listprice:0, selectedItem:'none' }Now let's create a method that handles the purchase. I named mine requestPurchase; create a method and copy the code below into it.
requestPurchase = async (sku: string) => { try { await RNIap.requestPurchase(sku, false) .then((purchase)=>{ console.log(purchase.purchaseToken) RNIap.finishTransaction(purchase, true); this.setState({ count:this.state.count+1 }); }) }); } catch (err) { console.warn(err.code, err.message); } }Everything is ready now. All that's left is to trigger the code with a button or something similar. Let's test the app with android.test.purchased, the test SKU Google Play provides for Android.
this.requestPurchase("android.test.purchased")If you follow all these steps, you can use the library without problems. I hope this helped. Happy coding!
Comments 0
No comments yet. Be the first.
Leave a comment