美文网首页
React Native IAP苹果支付(ApplePay)

React Native IAP苹果支付(ApplePay)

作者: G_console | 来源:发表于2024-05-10 16:05 被阅读0次

开发环境及设备信息

macOS Sonoma: 14.2.1
Xcode: Version 15.1 (15C65)
测试机:iphoneX iOS16.7.3
node: v18.19.1
pod: v1.15.2
"react": "18.1.0",
"react-native": "0.70.2"
"react-native-iap": "11.0.6"

一、Apple商品(购买项目)

添加购买商品
添加好的订阅商品

1、App内购买项目包含了消耗型商品(比如游戏金币)和非消耗型商品(比如网课、永久皮肤)
2、订阅商品包含了非续费订阅(比如月会员)和自动续费订阅(比如连续包月会员)
3、添加好商品后,就可以用于沙盒测试了,开发完支付功能后才可以提交审核。
4、调起支付时所用的sku,就是所添加商品的商品ID/产品ID(productId)

注意:苹果后台要添加银行账户,否则无法进行支付流程

添加银行账户

二、沙盒SandBox

文档

https://developer.apple.com/help/app-store-connect/test-in-app-purchases/create-sandbox-apple-ids
https://developer.apple.com/documentation/storekit/in-app_purchase/testing_at_all_stages_of_development_with_xcode_and_the_sandbox

步骤

1、创建沙盒账户,不能用真实的Apple账号,但必须是真实的邮箱,因为还需要接收验证信息。
如果有gmail账号的话,可以用“+”号将一个账户拆成任意多个账户使用。具体可以看文档。

沙盒账户创建
2、创建好沙盒账号后,直接去写代码,只要代码能调起支付,会自动弹出沙盒账号登录弹窗。第一次登录成功后,就可以在手机设置 > App Store中看到所登录的沙盒账号了。

三、IAP依赖库 & 支付代码

react-native-iap github地址
第一步:在RN项目中安装react-native-iap,他集合了ApplePay、Play Store、Amazon这些App内支付能力。

//安装依赖
yarn add react-native-iap
//pod安装ios依赖
cd ios
pod install

第二步:用xcode打开项目,然后去Capabilities添加支付能力:
xcode => project => Signing & Capabilities => + Capability => In-App Purchase
第三步:编写支付代码

import {
  type ProductPurchase,
  type ProductIOS,
  type PurchaseError,
  type SubscriptionPurchase,
  type SubscriptionIOS,
  
  initConnection,
  purchaseErrorListener,
  purchaseUpdatedListener,
  
  flushFailedPurchasesCachedAsPendingAndroid,
  getProducts,
  getSubscriptions,

  requestPurchase, 
  RequestPurchaseIOS,
  requestSubscription,
  RequestSubscriptionIOS,
  finishTransaction,

  setup,
  IapIos
} from 'react-native-iap';
/*
  编写一个IAP模块,主要包含以下功能
  1、初始化
  2、获取商品列表、支付商品
  3、获取订阅商品列表、支付订阅商品
  4、监听支付回调
*/
class IAP {
  init() {
    //setup({storekitMode: 'STOREKIT2_MODE'});
    //Storekit 2是苹果支付系统的新一套API标准,高版本IOS设备上可以支持,但开启Sk2的话,Sk1就不能用了。默认是HYBRID_MODE,自动识别>IOS15用Sk2。

    //初始化iap,initConnection后才能使用其他Api
    initConnection().then(res => {
      console.log('iap initConnection:::', res);
    }).catch(err => {
      console.log('iap initConnection Error:::', err);
    })
  }

  //获取商品列表
  getProducts = async (skus:string[]) => {
    return new Promise<ProductIOS[]>(async(resolve, reject) => {
      try {
        const pds = await getProducts({skus});
        resolve(pds);
      } catch (err) {
        reject(err)
      }
    })
  }
  //获取订阅商品列表
  getSubscriptions = async (skus:string[]) => {
    return new Promise<SubscriptionIOS[]>(async(resolve, reject) => {
      try {
        const pds = await getSubscriptions({skus});
        resolve(pds);
      } catch (err) {
        reject(err)
      }
    })
  }

  //购买订阅商品
  purchaseSubscribe = async (sku: string) => {
    try {
      this.subscribe(sku) //...
      /* {
        sku?: Sku;
        andDangerouslyFinishTransactionAutomaticallyIOS?: boolean;
        appAccountToken?: string;
        quantity?: number;
        withOffer?: Apple.PaymentDiscount;  //https://developer.apple.com/documentation/storekit/skpaymentdiscount?language=objc
      } */
      await requestSubscription({
        sku,
      });
    } catch (err) {
      console.warn('iap purchase subscribe:', err);
    }
  }

  //购买商品
  purchaseProduct = async (sku: string) => {
    try {
      this.subscribe(sku)   //调支付就开始监听...
      /*requestPurchase请求参数 {
        sku?: Sku;
        andDangerouslyFinishTransactionAutomaticallyIOS?: boolean;
        appAccountToken?: string;
        quantity?: number;
        withOffer?: Apple.PaymentDiscount;  //https://developer.apple.com/documentation/storekit/skpaymentdiscount?language=objc
      } */
      await requestPurchase({  //调起商品支付
        sku,
        andDangerouslyFinishTransactionAutomaticallyIOS: false,  //We recommend always keeping at false, and verifying the transaction receipts on the server-side.
      });
    } catch (err) {
      console.warn('iap purchase:', err);
    }
  };

  //手动结束交易流程,否则监听回调会一直给你通知上一次交易信息
  handleFinishTransaction = (purchase: SubscriptionPurchase | ProductPurchase) => {
    finishTransaction({
      purchase
      // isConsumable?: boolean | undefined;
      // developerPayloadAndroid?: string | undefined;
    })
  }

  updateListener: any;
  errorListener: any;
  /*
    监听支付回调
  */
  subscribe = async (sku: string, offerToken?: string) => {
    if(this.updateListener && this.errorListener) {
      return;
    }
    this.updateListener = purchaseUpdatedListener(
      (purchase: SubscriptionPurchase | ProductPurchase) => {
        console.log('purchaseUpdatedListener', purchase);
      }
    )
    this.errorListener = purchaseErrorListener(
      (error: PurchaseError) => {
        console.warn('purchaseErrorListener', error);
      },
    );
  };
  /*
    移除监听
  */
  removeSubscribe  = async () => {
    if (this.updateListener) {
      this.updateListener.remove();
      this.updateListener = null;
    }
    if (this.errorListener) {
      this.errorListener.remove();
      this.errorListener = null;
    }
  };
}

const iapModule = new IAP();
iapModule.init();
export default iapModule;
import iapModule from './iap'
//使用:
function handlePay = async(productId) => {
  await  iapModule.getProducts([productId])  //调支付前要先请求商品信息...
  await  iapModule.purchaseProduct(productId)

  //...后续流程,最后finishTransaction;
}

1、实际项目中,要关联用户系统的话,
需要先让后端生成订单号,
前端缓存订单号,再调起IOS支付,
等拿到IOS支付回调后,把支付回调和订单号一起交回后端验证。
2、等后端验证成功后,再通知前端交易成功。
然后前端需要调用finishTransaction通知Apple端结束该次交易。

获取订阅商品列表,返回数据:
[{"countryCode": "USA", "currency": "USD", "description": "测试订阅2024-05-07", "discounts": [], "introductoryPrice": "", "introductoryPriceAsAmountIOS": "", "introductoryPriceNumberOfPeriodsIOS": "", "introductoryPricePaymentModeIOS": "", "introductoryPriceSubscriptionPeriodIOS": "", "localizedPrice": "$0.99", "price": "0.99", "productId": "test_subscribe1", "subscriptionPeriodNumberIOS": "0", "subscriptionPeriodUnitIOS": "", "title": "测试订阅1", "type": "subs"}]
沙盒支付成功,回调内容:
{"originalTransactionDateIOS": "1715133228000", "originalTransactionIdentifierIOS": "2000000591577777", "productId": "102", "purchaseToken": "", "quantityIOS": 1, "transactionDate": 1715133228000, "transactionId": "2000000591577777", "transactionReceipt": ""}

第一次拉起支付后,使用沙箱账号流程

注意:

1、刚添加好商品,第一时间可能拿不到数据,请求不了支付,需要等一段时间
2、刚添加好银行账户也一样,正常摸一天鱼肯定能请求到数据了

IAP好文分享

https://zhuanlan.zhihu.com/p/381650817
https://juejin.cn/post/7231858374828048441

相关文章

网友评论

      本文标题:React Native IAP苹果支付(ApplePay)

      本文链接:https://www.haomeiwen.com/subject/yculfjtx.html