Swift3 蘋果內購

z小志發表於2018-01-23

##1、引入標頭檔案

  import StoreKit
複製程式碼

##2、在viewDidLoad新增

  SKPaymentQueue.default().add(self) 
 
  //新增代理
  SKPaymentTransactionObserver,SKProductsRequestDelegate
複製程式碼

##2、支付

   if (SKPaymentQueue.canMakePayments()) {
        self.getProductInfo(payID: "蘋果內購商品ID")
   }else{
        MDHubHelper.share.showError(msg: NSLocalizedString(str: "無法購買"))
   }

   func getProductInfo(payID:String) {
        SKPaymentQueue.default().add(self)
        let array = NSArray.init(object: payID)
        
        let request = SKProductsRequest.init(productIdentifiers: NSSet(array: array as! [Any]) as! Set<String>)
        request.delegate = self
        request.start()
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
        
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
        
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchased:
                self.completeTransaction(transaction: transaction)
            //請求服務端
            case .purchasing:
                MDHubHelper.share.showStatus(msg:NSLocalizedString(str: "正在支付"))
            //正在交易
            case .failed:
                MDHubHelper.share.showError(msg: NSLocalizedString(str: "支付失敗"))
                self.failedTransaction(transaction: transaction)
            case .restored:
                MDHubHelper.share.showError(msg: NSLocalizedString(str: "已購買該商品"))
                self.restoreTransaction(transaction: transaction)
            default:
                self.failedTransaction(transaction: transaction)
                break
            }
        }
    }
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        
        let myProduct = response.products
        
        if (myProduct.count == 0) {
            MDHubHelper.share.showError(msg: NSLocalizedString(str: "無內購資訊"))
            return
        }
        lPayment = SKPayment.init(product: myProduct[0])
        SKPaymentQueue.default().add(lPayment)
    }
    
    //自定義函式
    func completeTransaction(transaction:SKPaymentTransaction) {
        
        let recvURL = Bundle.main.appStoreReceiptURL
        let receiptData = NSData(contentsOf: recvURL!)
        let encodeStr = receiptData?.base64EncodedString(options: .endLineWithLineFeed)
        
        MDNetRequest.share.notifyApplePaySuccess(url: UrlApplePay, params: ["order_id":self.orderId!,"receipt":encodeStr!,"transactionId":transaction.transactionIdentifier!,"session_id":MDDataSource.share.session!], successBlock: {
            MDHubHelper.share.hidHubView()
            MDHubHelper.share.showError(msg: NSLocalizedString(str:"購買成功"))
        }, failBlock: {
            MDHubHelper.share.hidHubView()
            MDHubHelper.share.showError(msg: NSLocalizedString(str: "通知伺服器失敗"))
        }) { (err) in
            MDHubHelper.share.showError(msg: NSLocalizedString(str: "請求伺服器錯誤"))
        }
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    func failedTransaction(transaction:SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    func restoreTransaction(transaction:SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(transaction)
    }

複製程式碼

相關文章