React Native IAP 設定記錄

React Native Aug 29, 2022

最近在翻新過去寫的React Native應用程式,因為舊有代碼難以維謢(用了expo、寫太爛、所用的NPM Package已棄用等等),需要整個App重新編寫過,當中需要用到In App Purchase功能來收款,在React Native中,比較受觀迎的有expo-in-app-purchases和react-native-iap,由於上次亦是用了react-native-iap,能夠重用舊有的代碼,加上這次要脫離expo,所以仍然是採用react-native-iap。

不過上次使用的react-native-iap版本5.x,現在已經更新到10.0.1,documentation都有點改動,套用原來的代碼就會有點問題,所以記錄一下React Native IAP的設定記錄:

  1. npm i react-native-iap 先安裝React Native IAP
    按照docs設定IAP: https://react-native-iap.dooboolab.com/docs/installing
  2. 在載入應用時初始化時加入
const itemSkus = Platform.select({
    ios: ['product_name'],
    android: ['product_name'],
});

await initConnection();
await getProducts({skus: itemSkus});

按照docs,itemSkus是直接pass到getProducts()裏面,但實際是要pass一個object,當中的skus才是要passitemSkus,否則會無法取得相應的產品
3. 在初始化時(getProducts後)設定付款listener(只有Android完成付款後才會觸發listener裏面的動作),iOS可以在await requestPurchase()後設定付款後的動作
參考docs: https://react-native-iap.dooboolab.com/docs/usage_instructions/purchase

await flushFailedPurchasesCachedAsPendingAndroid();
purchaseUpdateSubscription = purchaseUpdatedListener(
    async purchase => {
        const receipt = purchase?.transactionReceipt;
        if (receipt) {
            await finishTransaction({purchase}, false);
            await iapHook.getAvailablePurchases();
            // ... show success message
        }
    },
);
purchaseErrorSubscription = purchaseErrorListener(error => {
    if (error.responseCode === 7) {
      // ... show already purchased error message
    }
// ... show error messages
});

按照docs,purchase是直接pass到finishTransaction()裏面,但實際是要pass一個object,當中的purchase才是要passpurchase,否則無法完成整過付款驗證過程,結果Google Play會不斷退款
同時在點擊購買的位置加入請求付款的function:

const rp = async (sku) => {
    try {
      await requestPurchase({
        sku,
        andDangerouslyFinishTransactionAutomaticallyIOS: false,
      });
    } catch (err) {
      console.warn(err.code, err.message);
    }
  };

標籤