You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用react-native-iap在React Native中实现Restore Purchase功能?

如何使用react-native-iap实现React Native的恢复购买功能

核心API说明

react-native-iap针对iOS和Android平台提供了不同的恢复购买实现方式,以下是具体步骤:

  1. 导入所需模块
import { restorePurchases, getAvailablePurchases, PurchaseError, Platform } from 'react-native-iap';
  1. 实现恢复购买函数
const handleRestorePurchases = async () => {
  try {
    let restoredPurchases;
    // iOS 调用restorePurchases触发官方恢复流程,需用户验证Apple ID
    if (Platform.OS === 'ios') {
      restoredPurchases = await restorePurchases();
    } 
    // Android 直接查询已购记录,无需额外弹窗
    else {
      restoredPurchases = await getAvailablePurchases();
    }

    if (restoredPurchases.length > 0) {
      // 遍历恢复的购买项,处理业务逻辑(如解锁功能、同步后端)
      restoredPurchases.forEach(purchase => {
        console.log('已恢复购买:', purchase.productId);
        // 示例:根据productId解锁对应功能
        unlockAppFeature(purchase.productId);
        // 务必将purchase.transactionReceipt发送到后端验证合法性
        validateReceiptWithBackend(purchase.transactionReceipt);
      });
    } else {
      alert('暂无可恢复的购买记录');
    }
  } catch (error) {
    if (error instanceof PurchaseError) {
      console.error('恢复购买失败:', error.code, error.message);
      alert(`恢复失败:${error.message}`);
    } else {
      console.error('恢复购买时发生未知错误:', error);
    }
  }
};

关键注意事项

  • 平台差异:iOS的restorePurchases()会唤起Apple ID验证弹窗,而Android的getAvailablePurchases()直接查询本地缓存和Google Play服务器的已购记录。
  • 凭证验证:所有恢复的购买记录必须通过后端与苹果/谷歌的官方验证接口校验,避免伪造数据。
  • 权限配置:确保iOS项目已开启内购能力,Android项目的AndroidManifest.xml中添加了com.android.vending.BILLING权限。
  • 版本兼容:使用react-native-iap v10及以上版本,旧版本API可能存在差异。

内容的提问来源于stack exchange,提问作者Technical Inzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:30:16