首页
/ Expo IAP 应用内购买解决方案详解

Expo IAP 应用内购买解决方案详解

2025-07-02 09:32:27作者:卓艾滢Kingsley

项目概述

Expo IAP 是一个专为 Expo 和 React Native 应用设计的跨平台应用内购买解决方案。它为开发者提供了统一的 API 接口,简化了在 iOS 和 Android 平台上实现应用内购买功能的复杂度。

核心特性

  1. 跨平台一致性:一套代码即可处理 iOS 和 Android 的应用内购买逻辑
  2. 现代化开发体验
    • 完整的 TypeScript 类型支持
    • 基于 React Hooks 的简洁 API 设计
    • 完善的错误处理机制
  3. 功能全面
    • 支持一次性购买和订阅模式
    • 内置收据验证功能
    • 优化的性能表现

快速入门指南

安装步骤

npm install expo-iap
# 或
yarn add expo-iap

基础实现流程

  1. 初始化连接:建立与应用商店的连接
  2. 获取商品信息:从应用商店获取配置的商品数据
  3. 展示商品:在应用中显示可购买商品
  4. 处理购买请求:响应用户购买操作
  5. 完成交易:确认交易并交付商品

完整示例代码

import React, { useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { useIAP } from 'expo-iap';

const SimpleStore = () => {
  const {
    connected,
    products,
    getProducts,
    requestPurchase,
    currentPurchase,
    finishTransaction,
  } = useIAP();

  const productIds = ['com.example.coins.pack1', 'com.example.premium'];

  useEffect(() => {
    if (connected) {
      getProducts(productIds);
    }
  }, [connected]);

  useEffect(() => {
    if (currentPurchase) {
      const completePurchase = async () => {
        try {
          console.log('Purchase completed:', currentPurchase.id);
          await finishTransaction({
            purchase: currentPurchase,
            isConsumable: true,
          });
        } catch (error) {
          console.error('Failed to complete purchase:', error);
        }
      };
      completePurchase();
    }
  }, [currentPurchase]);

  const handlePurchase = async (productId: string) => {
    try {
      await requestPurchase({
        request: { sku: productId },
      });
    } catch (error) {
      console.error('Purchase failed:', error);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.status}>
        Store: {connected ? 'Connected ✅' : 'Connecting...'}
      </Text>

      {products.map((product) => (
        <View key={product.id} style={styles.product}>
          <Text style={styles.title}>{product.title}</Text>
          <Text style={styles.price}>{product.displayPrice}</Text>
          <Button title="Buy Now" onPress={() => handlePurchase(product.id)} />
        </View>
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { padding: 20 },
  status: { fontSize: 16, marginBottom: 20 },
  product: {
    padding: 15,
    marginVertical: 5,
    backgroundColor: '#f0f0f0',
    borderRadius: 8,
  },
  title: { fontSize: 16, fontWeight: 'bold' },
  price: { fontSize: 14, color: '#666', marginVertical: 5 },
});

export default SimpleStore;

平台支持情况

平台 支持状态 说明
iOS 完全支持 支持 StoreKit 1 和 2
Android 完全支持 支持 Google Play Billing
Expo Go 部分支持 需要定制开发客户端
开发客户端 完全支持
裸 React Native 完全支持

进阶功能

  1. 收据验证:确保购买的真实性和安全性
  2. 订阅管理:处理自动续订和订阅状态变更
  3. 错误处理:详细的错误代码和恢复建议
  4. 性能优化:减少不必要的渲染和网络请求

最佳实践建议

  1. 连接管理:合理处理商店连接状态,避免频繁重连
  2. 商品缓存:适当缓存商品信息,减少网络请求
  3. 错误恢复:为常见错误提供友好的用户界面
  4. 测试策略:充分利用平台的沙盒环境进行测试

常见问题解决方案

  1. 连接失败:检查平台配置是否正确,网络连接是否正常
  2. 商品不显示:确认商品ID是否正确,是否已在应用商店配置
  3. 购买未完成:确保正确处理了交易完成逻辑
  4. 收据验证失败:检查服务器验证逻辑是否正确

Expo IAP 为 React Native 开发者提供了简单高效的解决方案,大大降低了实现应用内购买功能的门槛。通过合理的架构设计和丰富的功能支持,开发者可以快速构建稳定可靠的应用内购买系统。

登录后查看全文
热门项目推荐