在IOS React Native中验证收据时获取21002的状态

问题描述 投票:0回答:1

我正在尝试在 IOS 上的 React Native 应用程序中实现订阅,我有几个问题首先我创建了两个沙箱测试用户,但是打开应用程序时,提示在第一次渲染或确认订阅时不会显示为了放置我的电子邮件和沙箱用户的密码。虽然我可以通过反应本机 iap 库从应用程序商店连接获取订阅,但 verifyReceipt 调用仍然始终返回 21002 状态。

我添加了订阅,添加了应用内购买功能并生成了共享密钥。以下是我当前的实现

import {
  PurchaseError,
  requestSubscription,
  useIAP,
  validateReceiptIos,
  withIAPContext,
} from 'react-native-iap';
import {IOS_SHARED_SECRET} from '@env';

const SubscriptionModal = ({showSubscribeModal, onCloseModal}) => {
  const dispatch = useDispatch();

 const {
    connected,
    subscriptions, //returns subscriptions for this app.
    getSubscriptions, //Gets available subsctiptions for this app.
    currentPurchase, //current purchase for the tranasction
    finishTransaction,
    purchaseHistory, //return the purchase history of the user on the device (sandbox user in dev)
    getPurchaseHistory, //gets users purchase history
    getAvailablePurchases,
  } = useIAP();

  useEffect(() => {
    // if (subscriptions) console.log('subscription', subscriptions);
    // if (purchaseHistory) console.log('has purchase history..', purchaseHistory);
    // ... listen if connected, purchaseHistory and subscriptions exist
    if (
      purchase &&
      purchase?.find(
        x => x.productId === (subscriptionSkus[0] || subscriptionSkus[1]),
      )
    ) {
      setAlreadySubscribed(true);
    }
  }, [connected, purchaseHistory, subscriptionSkus, purchase]);

  useEffect(() => {
    (async () => {
      try {
        const data = await RNIap.getPurchaseHistory();
        setPurchase(data);

        // const receiptBody = {
        //   'receipt-data': data[0]?.transactionReceipt,
        //   password: '*******', // app shared secret, can be found in App Store Connect
        // };
        // console.log(receiptBody);
        // const result = await validateReceiptIos(receiptBody, true);
        // const {status} = result;
        // Alert.alert(JSON.stringify(result));
      } catch (error) {
        console.log('error in validating receipt', error);
      }

      // console.log(new Date(data[0]?.transactionDate));
    })();
  }, [connected, getAvailablePurchases, getPurchaseHistory]);

  const handleFreeTrial = async () => {
    await deviceStorage.saveItem('clickedFreeTrial', true);
    onCloseModal();
  };

  const errorLog = ({message, error}) => {
    console.error('An error happened', message, error);
  };
  // product id from appstoreconnect app->subscriptions
  const subscriptionSkus = Platform.select({
    ios: ['Monthly', 'Yearly'],
  });

  const handleGetSubscriptions = async () => {
    try {
      await getSubscriptions({skus: subscriptionSkus});
    } catch (error) {
      errorLog({message: 'handleGetSubscriptions', error});
    }
  };

  useEffect(() => {
    handleGetSubscriptions();
  }, [connected]);

  const handleBuySubscription = async productId => {
    try {
      const result = await requestSubscription({
        sku: productId,
      });
      console.log('result', result);
      dispatch(setShowSubsciptionModal(true));
      // const data = {
      //   user_id: userProfile.id,
      //   subscription: true,
      //   subscription_plan: selectedOption === 'Monthly' ? 30 : 365,
      //   subscription_price:
      //     selectedOption === 'Monthly'
      //       ? subscriptions[0]?.localizedPrice
      //       : subscriptions[1]?.localizedPrice,
      // };
      // const response = await savePayment(data);
      // dispatch(getUserProfileData(userProfile?.id));
    } catch (error) {
      setLoading(false);
      if (error instanceof PurchaseError) {
        console.log('errorsdasd', error);
        errorLog({message: `[${error.code}]: ${error.message}`, error});
      } else {
        console.log('purchased canceled', error);
        setLoading(false);
        // errorLog({message: 'handleBuySubscription', error});
      }
    }
  };

  useEffect(() => {
    const checkCurrentPurchase = async purchase => {
      if (purchase) {
        try {
          const receipt = purchase.transactionReceipt;
          if (receipt) {
            if (Platform.OS === 'ios') {
              const isTestEnvironment = __DEV__;
              //send receipt body to apple server to validete
              const appleReceiptResponse = await validateReceiptIos(
                {
                  'receipt-data': receipt,
                  password: IOS_SHARED_SECRET,
                },
                isTestEnvironment,
              );

              //if receipt is valid
              if (appleReceiptResponse) {
                const {status} = appleReceiptResponse;
                if (status) {
                  // navigation.navigate('Home');
                }
              }
              return;
            }
          }
        } catch (error) {
          console.log('error', error);
        }
      }
    };
    checkCurrentPurchase(currentPurchase);
  }, [currentPurchase, finishTransaction]);

  `
react-native react-native-iap
1个回答
0
投票

你找到答案了吗?请也帮助我

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.