Skip to content

Instantly share code, notes, and snippets.

@alea12
Created October 7, 2021 16:37
Show Gist options
  • Save alea12/afeb71edb204517944d94ae503667181 to your computer and use it in GitHub Desktop.
Save alea12/afeb71edb204517944d94ae503667181 to your computer and use it in GitHub Desktop.
import React, {useEffect} from 'react';
import {Alert, Button, View} from 'react-native';
import {finishTransaction, Purchase, PurchaseError, useIAP, useIAPContext} from 'react-native-iap';
const PaymentComponent: React.FC = () => {
const {connected, subscriptions, currentPurchase, currentPurchaseError, requesSubscription, getSubscriptions} =
useIAP();
const {setCurrentPurchaseError} = useIAPContext();
// (1) get subscription plans
useEffect(() => {
if (connected) {
const subscriptionPlanIds = ['premium_500_monthly'];
getSubscriptions(subscriptionPlanIds);
}
}, [getSubscriptions, connected]);
// (2) handle purchase
useEffect(() => {
const checkCurrentPurchase = async (purchase?: Purchase): Promise<void> => {
if (purchase) {
const receipt = purchase.transactionReceipt;
if (receipt) {
const ackResult = await finishTransaction(purchase);
console.log('ackResult', ackResult);
// TODO: Implement receipt verification by backend server
}
}
};
checkCurrentPurchase(currentPurchase);
}, [currentPurchase, finishTransaction]);
// (3) hande purchase error
useEffect(() => {
if (currentPurchaseError) {
const handlePurchaseError = async (currentPurchaseError: PurchaseError) => {
Alert.alert('Purchase Error', `Code: ${currentPurchaseError.code}`);
setCurrentPurchaseError(undefined);
};
handlePurchaseError(currentPurchaseError);
}
}, [currentPurchaseError, setCurrentPurchaseError]);
return (
<View style={{alignItems: 'center', padding: 20}}>
{subscriptions.map(subscription => (
<View key={subscription.productId}>
<Button
title={`purchase ${subscription.title}`}
onPress={() => {
requesSubscription(subscription.productId, false);
}}
/>
</View>
))}
</View>
);
};
export default PaymentComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment