Apple’s StoreKit2 framework, announced at WWDC 2021, simplifies the development and testing of react native in app purchases on iOS.
One of StoreKit2’s key features is its integration with Xcode. We can now see the status of react native in app purchases directly in Xcode, making debugging issues more accessible and ensuring that everything works as expected.
To test our app’s behavior under different conditions, we can also simulate various purchase scenarios, such as successful purchases, canceled purchases, and refunds.
We will also learn how to develop a full-fledged react native IAP implementation for custom business logic, such as mapping user IDs to Apple/Google subscriptions or enabling parent-child subscription logic where a privileged user can purchase a subscription for other users.
To satisfy these custom product specifications, we must implement App Store Server Notifications and Google Pub/Sub along with our backend server to handle in-app lifecycle events.
Our proposed architecture handles only the initial transaction on the Mobile side. We will validate the first purchase via Apple on iOS and Google on Android, then send a request to our server to store our premium users’ information and unique transaction IDs.
Our server will receive and process all further lifecycle events, such as subscription renewal, cancellation, expiry, and grace periods, based on their transaction ID.
We will update our own record by matching the unique transaction ID found in each App Store Server Notification or Google Pub/Sub event with our user subscription records.
Finally, we must relay any IAP-related updates back to the front end. For this, we can pick from one of multiple approaches, depending on the requirements:
NOTE: This is a React Native-only tutorial. Our architecture also requires a server implementation for handling IAP lifecycle events using App Store Server Notifications and Google Pub/Sub Events.
If your app has login and user authentication or any custom business logic, then it is necessary to implement a backend along with your front end to handle the management of Apple/Google accounts and link them to your usernames in the app.
To set in-app purchases using StoreKit2, you need to follow these steps:
To setup in-app purchases using Google Billing, you need to follow these steps:
NOTE: It’s a good idea to have matching SKUs (product IDs) for both iOS & Android.
NOTE: Creating subscriptions here doesn’t mean we are creating in-app subscriptions. It just means that we are subscribing to a topic and will receive messages(in-app events) published by Google on that topic.
The react native iap package allows us to incorporate react native in app purchases into our iOS and Android apps and handle store transactions within them.
Regrettably, the documentation provided is quite limited, and bugs plague the implementation of StoreKit2. This guide seeks to consolidate our experiences with implementing react-native-app and present them digestibly, sparing you from going through all the meticulous research independently.
To implement in-app purchases in your React Native in app purchases app using react-native-app, you need to follow these steps:
cd ios
pod install
withIAPContext,
initConnection,
endConnection,
setup,
useIAP,
} from ‘react-native-iap’;
// … root App Component
export default withIAPContext(App);
useEffect(() => {
// … other init
// IAP init
setup({ storekitMode: ‘STOREKIT2_MODE’ });
initConnection();
return () => {
// … other deinit
/// IAP cleanup
void endConnection();
};
}, []);
This will initialize the connection with Play Store Console & App Store Connect using StoreKit2 and set up the necessary configuration for your in-app purchases.
// … in component
const { getProducts, getSubscriptions } = useIAP();
const PRODUCT_IDS = [‘com.yourapp.product1’, ‘com.yourapp.product2’];
const APP_SKUS = [
‘product1’,
‘product2’,
];
// can get objects using either product IDs or SKU names
const products = await getProducts(PRODUCT_IDS);
const subscriptions = await getSubscriptions({ skus: APP_SKUS });
This will initiate the react native in app purchases process and trigger the onPurchase event if the purchase is successful.
RNIap.finishTransaction(transactionId);
This will finish the transaction and the purchase process.
NOTE: After calling this function, you tell Apple/Google that you have fulfilled the transaction. In most use cases, you will want to contact your backend server and confirm the user has been granted the premium features before calling finishTransaction.
useEffect(() => {
// … listen to currentPurchase to check if the purchase went through
if (purchase) {
try {
const receipt = purchase.transaction receipt;
if (receipt) {
// validate the receipt from the backend
const validationResponse = iapService.validate(receipt)
if (validationResponse) {
// update local user state with newly purchased subscription
// note: It is important to check user recvd from backend because
// any signed in apple ID can send receipts to this listener,
// so we may receive updates for another user
if (validationResponse.id === user.id) {
dispatch(updateUser(validationResponse));
}
// after confirming transaction & updating our app to show
// user’s new subscription status, we can finishTransaction
// note: isConsumable = true for one-time purchases,
// false for subscriptions
await finishTransaction({ purchase, isConsumable: false });
}
}
} catch (error) {
console.log(‘[IAP] error parsing purchase object: ‘, error);
}
}
}, [currentPurchase]);
useEffect(() => {
// … listen to currentPurchaseError, to check if any error happened
if (currentPurchaseError) {
const errorCodes = [
‘E_USER_CANCELLED’,
‘E_ITEM_UNAVAILABLE’,
‘UNKNOWN_ERROR’,
];
// handle accordingly. you might want to ignore the 3 error codes
// listed above
}
}, [currentPurchaseError]);
Thanks to StoreKit2 and Google Billing, Implementing React Native in app purchases has never been easier. By following the guidelines outlined in this guide, developers can enhance their apps with premium features and monetize their offerings effectively.
So why wait? Explore React Native in app purchases and take your React Native apps to new heights of success!
USA408 365 4638
1301 Shoreway Road, Suite 160,
Belmont, CA 94002
Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.
Tel:
+1 408 365 4638
Support:
+1 (408) 512 1812
COMMENTS ()
Tweet