Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on emulator while purchase #2705

Open
puneetkansal04 opened this issue Mar 17, 2024 · 0 comments
Open

Error on emulator while purchase #2705

puneetkansal04 opened this issue Mar 17, 2024 · 0 comments

Comments

@puneetkansal04
Copy link

puneetkansal04 commented Mar 17, 2024

Purchase error The sku was not found. Please fetch products first by calling getItems

import React, { useEffect, useState } from 'react';
import { Alert, FlatList, Text, TouchableOpacity, View } from 'react-native';
import usePurchaseFetching from '../hooks/usePurchaseFetching';
import {
finishTransaction,
getProducts,
purchaseErrorListener,
purchaseUpdatedListener,
requestPurchase,
} from 'react-native-iap';
import { useNavigation } from '@react-navigation/native';
import { constants } from '../utils/constants';

function HomeScreen() {
const [premiumUser, setPremiumUser] = useState(false);
const navigation = useNavigation();
// Call the custom hook
const loading = usePurchaseFetching(setPremiumUser);

const [products, setProducts] = useState([]);
const [isLoading, setLoading] = useState(true);

const notifySuccessfulPurchase = () => {
  Alert.alert('Success', 'Purchase successful', [
    {
      text: 'Home',
      onPress: () => navigation.navigate('Home'),
    },
  ]);
};

const handlePurchase = async (productId) => {
  // setPurchaseLoading(true)
  console.log('productId',productId)
  try {
    await requestPurchase({ skus: [productId] });
  } catch (error) {
    Alert.alert('Error occurred while making purchase')
  }
  finally {
    setLoading(false);
  }
}

useEffect(() => {
  const purchaseUpdateSubscription = purchaseUpdatedListener(
    async purchase => {
      const receipt = purchase.transactionReceipt;
      if (receipt) {
        try {
          await finishTransaction({ purchase, isConsumable: false });
        } catch (error) {
          console.error(
            'An error occurred while completing transaction',
            error,
          );
        }
        notifySuccessfulPurchase();
      }
    },
  );
  const purchaseErrorSubscription = purchaseErrorListener(error =>
    console.error('Purchase error', error.message),
  );
  const fetchProducts = async () => {
    try {
      const result = await getProducts({ skus: constants.productSkus });
      setProducts(result);
      setLoading(false);
    } catch (error) {
      Alert.alert('Error fetching products');
    }
  };
  fetchProducts();
  return () => {
    purchaseUpdateSubscription.remove();
    purchaseErrorSubscription.remove();
  };
}, []);

const renderItem = ({ item }) => {
  return (
    <TouchableOpacity
      onPress={() => { 
                          handlePurchase(constants.productSkus[0])
       }}
      style={{
        flex: 1,
        height: 100,
        backgroundColor: 'blue',
        margin: 10,
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      <Text style={{ color: 'white' }}>{item}</Text>
    </TouchableOpacity>
  );
};

return (
  <View style={{ flex: 1 }}>
    <FlatList
      contentContainerStyle={{ flexGrow: 1 }}
      numColumns={2}
      data={[1, 2, 3, 4]}
      renderItem={renderItem}
      keyExtractor={item => item.toString()}
    />
  </View>
);
}

export default HomeScreen;

import {useFocusEffect} from '@react-navigation/native';
import {useCallback, useState} from 'react';
import {constants} from '../utils/constants';
import {getAvailablePurchases} from 'react-native-iap';

const usePurchaseFetching = setPremiumUser => {
  const [loading, setLoading] = useState(true);

  useFocusEffect(
    useCallback(() => {
      setLoading(true);
      const fetchPurchases = async () => {
        try {
          const result = await getAvailablePurchases();
          const hasPurchased = result.find(
            product => product.productId === constants.productSkus[0],
          );
          console.log('hasPurchased',result)
          setLoading(false);
          setPremiumUser(hasPurchased);
        } catch (error) {
          console.error('Error occurred while fetching purchases', error);
        }
      };

      fetchPurchases();
    }, [setPremiumUser]),
  );

  return loading;
};

export default usePurchaseFetching;

addeed billing permission as well but still getting this error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant