MerchantKit 开源项目教程
1. 项目介绍
MerchantKit 是一个现代的 iOS 应用内购买管理框架,旨在简化独立开发者在其应用程序中添加高级可货币化组件的工作。MerchantKit 提供了跟踪已购买产品、提供自动续订订阅、恢复交易等功能,非常适合为应用程序添加解锁的“专业版”层级,无论是作为一次性购买还是持续订阅。
主要特点
- 简化开发:提供直观的 API,支持非消耗品、消耗品和订阅类型的应用内购买。
- 本地化格式器:动态创建本地化字符串,如“£2.99 每月”或“七天免费试用”。
- 无外部依赖:仅依赖于 Apple 提供的 iOS 内置框架。
- 开发者友好:优先考虑开发者的便利性和可访问性,而不是安全性。
2. 项目快速启动
安装
使用 CocoaPods
在 Podfile
中指定:
pod 'MerchantKit'
使用 Carthage
在 Cartfile
中指定:
github "benjaminmayo/merchantkit"
手动安装
下载源代码并将其嵌入到您的应用程序中。
初始化
在您的应用委托中导入 MerchantKit
,并在 application(_:didFinishLaunchingWithOptions:)
方法中创建 Merchant
实例:
import MerchantKit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.merchant = Merchant(configuration: .default, delegate: self)
return true
}
注册产品
在 application(_:didFinishLaunchingWithOptions:)
方法中注册产品:
let product = Product(identifier: "iap.productIdentifier", kind: .nonConsumable)
let otherProduct = Product(identifier: "iap.otherProductIdentifier", kind: .subscription(automaticallyRenews: true))
self.merchant.register([product, otherProduct])
设置 Merchant
在 application(_:didFinishLaunchingWithOptions:)
方法中调用 setup()
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.merchant = Merchant(configuration: .default, delegate: self)
self.merchant.register([product, otherProduct])
self.merchant.setup()
return true
}
3. 应用案例和最佳实践
检查产品是否已购买
let product = merchant.product(withIdentifier: "iap.productidentifier")
print("isPurchased: \(merchant.state(for: product).isPurchased)")
购买产品
let task = merchant.commitPurchaseTask(for: purchase)
task.onCompletion = { result in
switch result {
case .succeeded(_):
print("purchase completed")
case .failed(let error):
print("\(error)")
}
}
task.start()
订阅到期通知
public func merchant(_ merchant: Merchant, didChangeStatesFor products: Set<Product>) {
if let subscriptionProduct = products.first(where: { $0.identifier == "subscription.protier" }) {
let state = merchant.state(for: subscriptionProduct)
switch state {
case .isPurchased(let info):
print("subscribed, expires \(info.expiryDate)")
default:
print("does not have active subscription")
}
}
}
4. 典型生态项目
相关项目
- SwiftyStoreKit:另一个流行的 iOS 应用内购买框架,提供了类似的功能。
- StoreKit:Apple 官方提供的应用内购买 API,MerchantKit 在此基础上进行了封装和简化。
社区支持
- GitHub Issues:通过 GitHub Issues 报告问题和提出建议。
- Stack Overflow:在 Stack Overflow 上搜索或提问关于 MerchantKit 的问题。
通过以上步骤,您可以快速上手并使用 MerchantKit 来管理您的 iOS 应用内购买。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考