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

Even though I added iOS items, the products appear blank. #2808

Open
zelalsu opened this issue Jul 25, 2024 · 1 comment
Open

Even though I added iOS items, the products appear blank. #2808

zelalsu opened this issue Jul 25, 2024 · 1 comment

Comments

@zelalsu
Copy link

zelalsu commented Jul 25, 2024

import React, {useState, useEffect} from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
ImageBackground,
Platform,
} from 'react-native';
import {useDispatch} from 'react-redux';
import {SwiperFlatList} from 'react-native-swiper-flatlist';
import {
requestSubscription,
getSubscriptions,
initConnection,
endConnection,
purchaseUpdatedListener,
purchaseErrorListener,
finishTransaction,
} from 'react-native-iap';
import OptionCard from '../Components/Options/OptionCard';
import COLORS from '../constants/colors';
import {setPackages} from '../store/slices/package';
import {useGetByPackageQuery} from '../store/api/package';
import startApplePayTransaction from '../utils/paymentHelper';
import saveToDatabaseAndNavigate from '../utils/saveDataBaseAndNavigate';
import {ITUNES_SHARED_SECRET} from '@env';

const itemSkus = Platform.select({
android: ['global_package', 'national_package'],
ios: ['global_package_ios', 'national_package_ios'],
});

const PackageChosenScreen = ({navigation}) => {
const [selectedValue, setSelectedValue] = useState(null);
const [subscriptions, setSubscriptions] = useState([]);
const dispatch = useDispatch();
const {data: responsePackage} = useGetByPackageQuery();

useEffect(() => {
async function initIAP() {
try {
console.log('Initializing IAP connection...');
await initConnection();
console.log('IAP connection initialized');

    const products = await getSubscriptions({skus: itemSkus});
    console.log('Fetched products:', products);
    if (responsePackage) {
      const playConsolePackages = responsePackage?.data || [];

      const combinedPackages = playConsolePackages.map(playPackage => {
        const iapProduct = products.find(
          product => product.productId === playPackage.productId_PlayStore,
        );
        return iapProduct ? {...playPackage, ...iapProduct} : playPackage;
      });

      setSubscriptions(combinedPackages);
      dispatch(setPackages(combinedPackages));
      console.log('Combined packages:', combinedPackages);
    } else {
      console.log('No responsePackage data available');
    }
  } catch (error) {
    console.error('Error initializing IAP: ', error);
  }
}

const purchaseUpdateSubscription = purchaseUpdatedListener(
  async purchase => {
    const receipt = purchase.transactionReceipt;
    if (receipt) {
      try {
        if (Platform.OS === 'ios') {
          const isTestEnvironment = __DEV__;

          const appleReceiptResponse = await validateReceiptIos(
            {
              'receipt-data': receipt,
              password: ITUNES_SHARED_SECRET,
            },
            isTestEnvironment,
          );

          if (appleReceiptResponse && appleReceiptResponse.status === 0) {
            await finishTransaction({purchase, isConsumable: false});
          }
        } else {
          await finishTransaction({purchase, isConsumable: false});
        }
      } catch (error) {
        console.error(
          'An error occurred while completing transaction',
          error,
        );
      }
    }
  },
);

const purchaseErrorSubscription = purchaseErrorListener(error =>
  console.error('Purchase error', error.message),
);

initIAP();
return () => {
  endConnection();
  purchaseUpdateSubscription.remove();
  purchaseErrorSubscription.remove();
};

}, [responsePackage, ITUNES_SHARED_SECRET]);

async function saveOptionToDB(value) {
try {
if (value.productId === 'free_package') {
console.log('Ücretsiz paket seçildi. Firebase kaydediliyor...');
await saveToDatabaseAndNavigate(dispatch, navigation, value);
return;
}

  if (Platform.OS === 'ios') {
    console.log('Apple Pay ile ödeme işlemi başlatılıyor...');
    await startApplePayTransaction(dispatch, navigation, value);
  } else {
    const offerToken = value.subscriptionOfferDetails[0]?.offerToken;
    const sku = value.productId;
    const subscriptionOffers = [{sku, offerToken}];

    if (!offerToken || !sku) {
      console.log(
        'Geçersiz offerToken veya sku değeri. offerToken:',
        offerToken,
        'sku:',
        sku,
      );
      return;
    }

    console.log('Satın alma işlemi başlatılıyor...');
    const purchase = await requestSubscription({subscriptionOffers});
    console.log('Satın alma işlemi başarılı:', purchase);

    await saveToDatabaseAndNavigate(dispatch, navigation, value);
  }
} catch (error) {
  console.error('Hata oluştu:', error);
}

}

function renderData({item}) {
return (
<OptionCard
navigation={navigation}
selectedValue={selectedValue}
name={item.title}
item={item}
id={item.productId}
onPress={() => {
setSelectedValue(item);
saveOptionToDB(item);
}}
/>
);
}

return (

<ImageBackground
source={require('../Assests/Login.jpg')}
style={styles.containerStyle}>


{selectedValue ? (

Paket {selectedValue.title.toUpperCase()} seçildi

) : (

Henüz bir paket seçilmedi

)}

<View style={{flex: 1}}>
<SwiperFlatList
showPagination
paginationStyleItem={{
width: 20,
height: 6,
borderRadius: 5,
}}
data={subscriptions}
renderItem={renderData}
paginationActiveColor={COLORS.SECOND_ORANGE}
paginationDefaultColor="gray"
/>




);
};

const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#fff',
},
containerStyle: {
flex: 1,
justifyContent: 'center',
},
container: {
flex: 1,
},
chosenPackageStyle: {
color: COLORS.PRIMARY_GRAY,
fontSize: 25,
alignSelf: 'center',
fontWeight: 'bold',
},
chosenStyle: {
marginTop: 20,
},
});

export default PackageChosenScreen;

@Jeyoung-Park
Copy link

did you add information about subscription items in app store connect?

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

2 participants