iOS开发:苹果支付2.0简介

苹果重新设计实现了支付框架,并使用Swift提供了新的接口,StoreKit 2.0在今年WWDC21发布了。

更新内容

苹果应用内支付历来被吐槽,不但是开发测试的麻烦,还因为错误信息的缺失以及流程上难以避免的掉单。当然也还有其他一些问题,但掉单是支付的首要问题,而这主要源于苹果为了维护其生态,将支付的帐号绑定了苹果设备体系——而这真不是一个提供通用支付该有的平台特性。

继去年StoreKit支持Xcode Sandbox Testing以及Server to Server通知之后,WWDC21发布的StoreKit 2.0做了一次升级,带来了一些新的特性,包括解决掉单问题的终极方案。

更新内容包括:

  1. 支付请求新增了appAccountToken,订单信息可以关联应用的帐号体系。appAccountToken将会是持久化的,这不同于applicationUsername(时有时无)。
  2. 支持JWS因此可以在本地校验订单。
  3. App内发起退款。
  4. 自动续期订阅商品首购优惠资格查询。
  5. 交易历史订单查询。
  6. 基于Swift的新的异步编程模型async/await。

当然StoreKit 2.0是纯Swift的接口,并且仅在iOS 15+支持。所以旧版系统的兼容是需要的,并且旧版系统发起的订单的处理具体也需要实测。但至少在流程上掉单的问题是可以完美解决的了,这对于营收以及用户体验而言是很好的。

示例代码

下面是官方的示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func purchase(_ product: Product) async throws -> Transaction? {
//Begin a purchase.
let result = try await product.purchase(options: [.appAccountToken(accountToken)])

switch result {
case .success(let verification):
let transaction = try checkVerified(verification)

//Deliver content to the user.
await updatePurchasedIdentifiers(transaction)

//Always finish a transaction.
await transaction.finish()

return transaction
case .userCancelled, .pending:
return nil
default:
return nil
}
}

可以看到已经使用了基于协程的异步编程模型,同步化的流程处理是更直观的,非常的简洁。

参考:

「Meet StoreKit 2」:https://developer.apple.com/videos/play/wwdc2021/10114/

Comments