第一次订阅内容的时候,没有问题可以正常订阅成功。
但是等订阅到期或者取消后,第二次重新订阅总是失败。(测试中也没有弹出苹果订阅支付的弹窗)
代码中那一部分出错了?急,谢谢大神~
//
// TYPayManager.swift
// XiangXuniOS
//
//
import UIKit
import HandyJSON
import StoreKit
import SwiftDate
enum SIAPPurchType {
case Success // 购买成功
case Failed // 购买失败
case Cancle // 取消购买
case VerFailed // 订单校验失败
case VerSuccess // 订单校验成功
case NotAllow // 不允许内购
}
class TYPayManagerReceiptModel: HandyJSON {
var in_app: [TYPayManagerReceiptInAppModel] = []
required init() {}
}
class TYPayManagerReceiptInAppModel: HandyJSON{
/// 过期时间
var expires_date: Date?
/// 过期时间的时间戳
var expires_date_ms = 0
required init() {}
}
class TYPayManager: NSObject{
static let shared = TYPayManager()
var payOrderStatus: ((Int) -> ())?
var statusBlock: ((SIAPPurchType) -> ())?
var purchID: String!
/// 内购生成的订单号
var order_no = ""
var tips: QMUITips?
class var share: TYPayManager {
let obj = shared
obj.initAction()
return obj
}
/// 内购
func initAction() -> Void {
SKPaymentQueue.default().add(self)
}
func restore(order_no: String, view: UIView, completeHandle: @escaping ((SIAPPurchType) -> ())){
let tips = QMUITips.showLoading(in: view)
self.tips = tips
self.order_no = order_no
self.statusBlock = completeHandle
SKPaymentQueue.default().restoreCompletedTransactions()
}
// MARK: 开始内购
func startPurchWithID(purchID: String, order_no: String, view: UIView, completeHandle: @escaping ((SIAPPurchType) -> ())) {
let tips = QMUITips.showLoading(in: view)
self.tips = tips
print(message: purchID)
self.order_no = order_no
if SKPaymentQueue.canMakePayments() {
self.purchID = purchID
self.statusBlock = completeHandle
let request = SKProductsRequest.init(productIdentifiers: [purchID])
request.delegate = self
request.start()
} else {
completeHandle(.NotAllow)
}
}
// MARK: 交易失败
func failedTransaction(transaction: SKPaymentTransaction) {
if let tips = self.tips{
tips.hide(animated: true)
}
self.statusBlock?(.Failed)
SKPaymentQueue.default().finishTransaction(transaction)
}
// MARK: 交易结束
func completeTransaction(transaction: SKPaymentTransaction) {
let productIdentifier = transaction.payment.productIdentifier
if productIdentifier.count > 0 {
// 向自己的服务器验证购买凭证
}
self.verifyPurchaseWithPaymentTransaction(transaction: transaction, isTestServer: false)
}
// MARK: 验证交易
func verifyPurchaseWithPaymentTransaction(transaction: SKPaymentTransaction, isTestServer: Bool) {
let recepitURL = Bundle.main.appStoreReceiptURL
let receipt = try! Data(contentsOf: recepitURL!)
if let tips = self.tips{
tips.hide(animated: true)
}
self.toServiceVerifyPurchaseWithPaymentTransaction(receipt: receipt, transaction: transaction, isTestServer: false)
}
// MARK: 再次向服务器验证交易
func toServiceVerifyPurchaseWithPaymentTransaction(receipt: Data, transaction: SKPaymentTransaction, isTestServer: Bool) {
let para = ["receipt-data" : receipt.base64EncodedString(options: .endLineWithLineFeed), "password" : "7032ef52286840be8f2d32e7ee22b516"]
var appStoreUrl = "https://sandbox.itunes.apple.com/verifyReceipt"
if isProductServer {
appStoreUrl = "https://buy.itunes.apple.com/verifyReceipt"
}
var verTips: QMUITips?
if self.order_no.count > 0{
verTips = QMUITips.showLoading("加载中,请稍后", in: (QMUIHelper.visibleViewController()?.view)!, hideAfterDelay: 20)
}
HttpUtils.shared.postJson(url: appStoreUrl, parameters: para) { (result: TYPayManagerReceiptModel?) in
print(message: "应该是后台进行验证的")
if let tips = verTips{
tips.hide(animated: true)
}
if let in_app = result?.in_app{
for item in in_app{
let expires_date = Date(timeIntervalSince1970: TimeInterval(item.expires_date_ms / 1000))
Keychain.shared.expiresDate = expires_date.toString(.custom("yyyy年MM月dd号"))
Keychain.shared.expiresDateSecond = "\(item.expires_date_ms / 1000)"
SKPaymentQueue.default().finishTransaction(transaction)
}
}
SKPaymentQueue.default().finishTransaction(transaction)
self.statusBlock?(.VerSuccess)
} failure: { error in
SKPaymentQueue.default().finishTransaction(transaction)
if let tips = verTips{
tips.hide(animated: true)
}
self.statusBlock?(.VerFailed)
}
}
}
extension TYPayManager: SKPaymentTransactionObserver, SKProductsRequestDelegate{
// MARK: 交易状态
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transtion in transactions {
if transtion.transactionState == .purchased {
if let tips = self.tips{
tips.hide(animated: true)
}
// 购买成功
print(message: "购买成功")
self.completeTransaction(transaction: transtion)
break;
} else if transtion.transactionState == .purchasing {
// 正在购买
print(message: "正在购买")
break;
} else if transtion.transactionState == .restored {
// 恢复
print(message: "已经购买过商品")
self.completeTransaction(transaction: transtion)
SKPaymentQueue.default().finishTransaction(transtion)
break;
} else if transtion.transactionState == .failed {
// 购买失败
print(message: "购买失败")
self.failedTransaction(transaction: transtion)
SKPaymentQueue.default().finishTransaction(transtion)
break;
} else {
break;
}
}
}
// MARK: 请求查看存在的产品
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let products = response.products
if products.count == 0 {
print("没有商品")
return
}
var product: SKProduct?
for item in products {
if item.productIdentifier == self.purchID {
product = item
break
}
}
if product != nil {
print("产品信息:")
print(product)
let payment = SKPayment.init(product: product!)
SKPaymentQueue.default().add(payment)
}
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
if let tips = self.tips{
tips.hide(animated: true)
}
if queue.transactions.count > 0{
print(message: "有可恢复的购买项")
for item in queue.transactions{
print(message: item.original?.transactionDate)
print(message: item.original?.transactionIdentifier)
}
}else{
print(message: "没有可恢复的购买项")
QMUITips.show(withText: "没有可恢复的购买项", in: (QMUIHelper.visibleViewController()?.view)!)
}
}
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: any Error) {
print(message: "恢复失败")
if let tips = self.tips{
tips.hide(animated: true)
}
QMUITips.show(withText: "没有可恢复的购买项", in: (QMUIHelper.visibleViewController()?.view)!)
}
}