同样适用于MacOS开发
import Cocoa
import StoreKit
class PMMAppleSubscriptionService: NSObject {
var productId : String!
func sendPayquest(productId:String) -> Void {
SKPaymentQueue.default().remove(self)
SKPaymentQueue.default().add(self)
if SKPaymentQueue.canMakePayments() == true {
let set : Set = [productId]
let request = SKProductsRequest.init(productIdentifiers: set)
request.delegate = self
request.start()
}
}
//MARK: 从沙盒中获取交易凭证并且拼接成请求体数据
func verifyPurchaseWithPaymentTransaction(resultState:Int) -> Void {
guard let receiptUrl = Bundle.main.appStoreReceiptURL else { return }
let receiptData = Data.ReferenceType(contentsOf: receiptUrl)
if receiptData != nil {
let encodeStr = receiptData?.base64EncodedString(options: .endLineWithLineFeed)
let sendString = String.init(format: "{\"receipt-data\" : \"%@\"}", encodeStr!)
//上传凭证到本地服务器
}else{
LogService.logInfo("no receipt")
/* 没有本地 receipt -- 处理异常. */
}
SKPaymentQueue.default().remove(self)
}
}
extension PMMAppleSubscriptionService : SKProductsRequestDelegate {
//MARK: 收到产品返回信息
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
LogService.logInfo("--------------收到产品反馈消息---------------------")
let product = response.products
if product.count == 0 {
LogService.logError("找不到商品信息")
return
}
var p : SKProduct? = nil
product.forEach { item in
LogService.logInfo(item.description)
LogService.logInfo(item.localizedTitle)
LogService.logInfo(item.localizedDescription)
LogService.logInfo(item.price)
LogService.logInfo(item.productIdentifier)
if item.productIdentifier == self.productId {
p = item
}
}
let payment = SKPayment(product: p ?? SKProduct())
SKPaymentQueue.default().add(payment)
}
//MARK: 请求失败
func request(_ request: SKRequest, didFailWithError error: Error) {
LogService.logError("支付失败")
SKPaymentQueue.default().remove(self)
}
//MARK: 请求结束
func requestDidFinish(_ request: SKRequest) {
LogService.logError("请求结束")
}
}
extension PMMAppleSubscriptionService : SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
transactions.forEach { tran in
switch tran.transactionState {
case .purchased:
self.verifyPurchaseWithPaymentTransaction(resultState: tran.transactionState.rawValue)
SKPaymentQueue.default().finishTransaction(tran)
break
case .purchasing:
break
case .failed:
SKPaymentQueue.default().finishTransaction(tran)
LogService.logError("购买失败")
SKPaymentQueue.default().remove(self)
break
case .restored:
SKPaymentQueue.default().finishTransaction(tran)
break
case .deferred:
break
@unknown default:
break
}
}
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
LogService.logError("交易结束")
}
}
网友评论