SwiftyStoreKit swift内购
1.在 itunesconnect.apple.com,中配置内购项目,如图右侧有一个(查看公共秘钥)(验证购买时需要使用)
-
根据你们产品的不同选择对应的项目
-
创建就很简单了,每一项都有介绍这里就不多说了
使用此 App 的bundleID 唯一标示
- 创建一个项目,项目的 bundleID 要与 iTunesconnect 中项目的id相同。
Cocoapods 导入 SwiftyStoreKit
- pod 'SwiftyStoreKit' (内购轮子)
- pod 'Alamofire' (网络请求轮子)
一切准备就绪-下面代码部分
import SwiftyStoreKit
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
for purchase in purchases {
if purchase.transaction.transactionState == .purchased || purchase.transaction.transactionState == .restored {
if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("purchased: \(purchase)")
}
}
}
return true
}
/// 购买商品
class func purchase(productID: String,
inPurchaseClosure:@escaping ((_ inPurchaseResult: InPurchaseResult)->())) {
SwiftyStoreKit.purchaseProduct(productID, quantity: 1, atomically: true) { (result) in
switch result {
case .success(let purchase):
print("Purchase Success: \(purchase.productId)")
// 正式验证
self.verifyReceipt(service: .production)
inPurchaseClosure(LFPayTool.InPurchaseResult.success)
case .error(let error):
inPurchaseClosure(LFPayTool.InPurchaseResult.failure)
switch error.code {
case .unknown:
print("Unknown error. Please contact support")
case .clientInvalid:
print("Not allowed to make the payment")
case .paymentCancelled:
break
case .paymentInvalid:
print("The purchase identifier was invalid")
case .paymentNotAllowed:
print("The device is not allowed to make the payment")
case .storeProductNotAvailable:
print("The product is not available in the current storefront")
case .cloudServicePermissionDenied:
print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed:
print("Could not connect to the network")
case .cloudServiceRevoked:
print("User has revoked permission to use this cloud service")
default:
print((error as NSError).localizedDescription)
}
}
}
}
/// 本地验证(SwiftyStoreKit 已经写好的类) AppleReceiptValidator
// .production 苹果验证 .sandbox 本地验证
class func verifyReceipt(service: AppleReceiptValidator.VerifyReceiptURLType) {
//let sharedSecret = ""
let receiptValidator = AppleReceiptValidator(service: service, sharedSecret: nil)
SwiftyStoreKit.verifyReceipt(using: receiptValidator) { (result) in
switch result {
case .success (let receipt):
let status: Int = receipt["status"] as! Int
if status == 21007 {
// sandbox验证
self.verifyReceipt(service: .sandbox)
}
print("receipt:\(receipt)")
break
case .error(let error):
print("error:\(error)")
break
}
}
}