//
// RechargeManager.swift
// FastMeow
//
// Created by caoyicheng on 2022/2/26.
//
import UIKit
import StoreKit
private let RechargeInstance = RechargeManager()
class RechargeManager: NSObject, SKPaymentTransactionObserver, SKProductsRequestDelegate {
typealias RechargeManagerSuccessBlock = ( _ receipt: Data, _ transationId: String) -> Void
typealias RechargeManagerFailseBlock = () -> Void
var successBlock: RechargeManagerSuccessBlock!
var failseBlock: RechargeManagerFailseBlock!
var productID: String!
var orderID: String!
// MARK: ======================================生命周期========================================
class var share: RechargeManager {
let obj = RechargeInstance
obj.initAction()
return obj
}
// MARK: 初始化
@objc func initAction() {
SKPaymentQueue.default().add(self)
}
// MARK: 开始内购
func startPurchWithID(productID: String,
orderID: String,
success: @escaping RechargeManagerSuccessBlock,
failse: @escaping RechargeManagerFailseBlock) {
if SKPaymentQueue.canMakePayments() {
self.productID = productID
self.orderID = orderID
self.successBlock = success
self.failseBlock = failse
let request = SKProductsRequest.init(productIdentifiers: [productID])
request.delegate = self
request.start()
} else {
failse()
print("购买失败-未授权")
}
}
// MARK: 交易结束
func completeTransaction(transaction: SKPaymentTransaction) {
let recepitURL = Bundle.main.appStoreReceiptURL
do {
let receipt = try Data(contentsOf: recepitURL!)
let transationID = transaction.transactionIdentifier ?? ""
self.toServiceVerifyPurchaseWithPaymentTransaction(transaction: transaction,
productId: self.productID,
orderId: self.orderID,
payload: receipt,
transationID: transationID)
} catch {
// 交易失败
self.failseBlock()
SKPaymentQueue.default().finishTransaction(transaction)
print("购买失败-查看本地交易URL为null")
}
}
// MARK: 向服务器验证交易
@objc func toServiceVerifyPurchaseWithPaymentTransaction(transaction: SKPaymentTransaction, productId: String, orderId: String, payload: Data, transationID: String) {
let requestUrl = Utils.Base_Url + Utils.api_iosPayApplePay
let dic = ["payload" : payload.base64EncodedString(), // 校验体(base64字符串)
"payOrderId" : orderId, // 支付订单Id
"productId" : productId, // 产品ID
"transactionId" : transationID // 内购支付返回的交易ID
]
Alamofire.request(requestUrl,
method: .post,
parameters: dic,
encoding: URLEncoding.default,
headers: NetWorkManager.share.setHeader()).responseData { (response) in
print("")
print("请求地址:")
print(requestUrl)
print("请求参数:")
print(dic)
print("响应数据:")
print(JSON(response.result.value as Any))
if response.error == nil {
let resposeModel = ResposeModel.deserialize(from: JSON(response.result.value).dictionaryValue)
if resposeModel!.code == "200" {
print("购买成功")
self.successBlock(payload, transationID)
SKPaymentQueue.default().finishTransaction(transaction)
} else {
print("购买失败")
}
} else {
// 请求失败
print("请求失败")
}
}
}
// MARK: ======================================代理方法========================================
// MARK: 请求查看存在的产品
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let products = response.products
if products.count == 0 {
print("没有商品")
self.failseBlock()
return
}
var product: SKProduct?
for item in products {
if item.productIdentifier == self.productID {
product = item
break
}
}
if product != nil {
print("购买产品信息:")
print(product!.description)
print(product!.localizedTitle)
print(product!.localizedDescription)
print(product!.price)
print(product!.productIdentifier)
let payment = SKPayment.init(product: product!)
// payment.applicationUsername = ""
SKPaymentQueue.default().add(payment)
} else {
self.failseBlock()
}
}
// MARK: 交易状态
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transtion in transactions {
if transtion.transactionState == .purchased {
// 购买成功
self.completeTransaction(transaction: transtion)
print("购买成功")
} else if transtion.transactionState == .purchasing {
// 正在购买
print("正在购买")
} else if transtion.transactionState == .restored {
// 恢复
SKPaymentQueue.default().finishTransaction(transtion)
print("购买恢复")
} else if transtion.transactionState == .failed {
// 购买失败
self.failseBlock()
SKPaymentQueue.default().finishTransaction(transtion)
print("购买失败")
} else {
print("其他")
self.failseBlock()
SKPaymentQueue.default().finishTransaction(transtion)
}
}
}
}