Greetings community members,
I am currently navigating the intricacies of in-app purchases in my React Native application. Specifically, I am in the process of integrating auto-renewable subscriptions using the 'react-native-iap' package. Below is the complete code snippet I have implemented. While I have successfully fetched the subscriptions, I encounter an issue during the subscription process. After triggering the sandbox UI, a subscribe button appears. However, upon selecting it, a sign-in prompt is presented. Despite providing the correct credentials, the intended action does not occur.
I would greatly appreciate any insights or guidance on resolving this matter. Thank you in advance for your assistance.
import { View, Text, Button, StyleSheet, Alert, Platform } from 'react-native'; // Import Platform
import {
useIAP,
validateReceiptIos,
finishTransaction,
} from 'react-native-iap';
import axios from 'axios';
import { ITUNES_SHARED_SECRET } from "@env";
const SubscriptionScreen = ({ navigation }) => {
const {
requestSubscription,
getSubscriptions,
currentPurchase,
purchaseHistory,
} = useIAP();
const [subscriptionStatus, setSubscriptionStatus] = useState(false);
const [loading, setLoading] = useState(false);
useEffect(() => {
handleGetSubscriptions();
}, []);
useEffect(() => {
if (purchaseHistory && purchaseHistory.length > 0) {
const isSubscribed = purchaseHistory.some((purchase) =>
subscriptionSkus.includes(purchase.productId)
);
if (isSubscribed) {
setSubscriptionStatus(true);
}
}
}, [purchaseHistory]);
const subscriptionSkus = Platform.select({
ios: ['sub1', 'sub2', 'sub3'],
});
const handleGetSubscriptions = async () => {
try {
await getSubscriptions({ skus: subscriptionSkus });
} catch (error) {
console.error('Error getting subscriptions:', error);
}
};
const handleBuySubscription = async (productId) => {
try {
setLoading(true);
// Request subscription
const purchase = await requestSubscription({
sku: productId,
...(Platform.OS === 'ios' && { andDangerouslyFinishTransactionAutomaticallyIOS: false }), // Handle differently for iOS
});
// Finish the transaction
await finishTransaction({
purchase,
isConsumable: false,
});
// Check if the purchase was successful
if (purchase.transactionState === 'Purchased') {
// Validate the receipt
const receipt = purchase.transactionReceipt;
await handleValidateReceipt(receipt);
// Navigate to the desired screen
navigation.navigate('IndexPage');
} else {
// Handle other transaction states if needed
console.warn('Transaction state:', purchase.transactionState);
}
} catch (err) {
console.error(err.code, err.message);
} finally {
setLoading(false);
}
};
const handleValidateReceipt = async (receipt) => {
try {
const isTestEnvironment = false;
const response = await validateReceiptIos(
{
'receipt-data': receipt,
password: ITUNES_SHARED_SECRET,
},
isTestEnvironment
);
if (response && response.status === 0) {
// Receipt is valid, you may want to save the purchase on your server
const serverValidationResult = await validateReceiptOnServer(receipt);
if (serverValidationResult.valid) {
setSubscriptionStatus(true);
Alert.alert('Subscription Purchased', 'Thank you for subscribing!');
} else {
console.warn('Server validation failed');
}
} else {
console.warn('Receipt validation failed');
}
} catch (error) {
console.error('Error during receipt validation:', error);
}
};
const validateReceiptOnServer = async (receipt) => {
try {
// Replace with your server endpoint for receipt validation
const response = await axios.post('', { receipt });
return response.data;
} catch (error) {
console.error('Error validating receipt on server:', error);
return { valid: false };
}
};
useEffect(() => {
const checkCurrentPurchase = async () => {
if (currentPurchase) {
const receipt = currentPurchase.transactionReceipt;
if (receipt) {
await handleValidateReceipt(receipt);
try {
await finishTransaction({
purchase: currentPurchase,
isConsumable: false,
});
} catch (err) {
console.warn(err.code, err.message);
}
}
}
};
checkCurrentPurchase();
}, [currentPurchase, finishTransaction]);
return (
<View style={styles.container}>
<Text>{subscriptionStatus ? 'Subscribed' : 'Not Subscribed'}</Text>
{subscriptionSkus.map((sku) => (
<Button
key={sku}
title={`Purchase ${sku}`}
onPress={() => handleBuySubscription(sku)}
/>
))}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default SubscriptionScreen;```