应用内购买-购买失败的比例很高-SKError代码2或0

时间:2019-04-11 21:47:50

标签: swift in-app-purchase storekit

我们在应用内购买应用时遇到了严重的问题。

我们提供3种IAP:自动更新订阅3M,自动更新订阅1Y,一次性非购买(终身访问)

在我们的案例中,有70-80%的交易失败,并且我们大多收到SKError代码= 0或code = 2-无法连接到iTunes Store。根据SKError文档,它是未知错误(代码0)或已取消交易(错误2)。

同一用户有时会多次购买失败,因此很难相信用户有意连续3或4次取消同一产品的交易。

无论iOS版本,设备型号,我们的应用程序版本如何,都会发生。 以下是我们用于提取产品并进行交易的代码。

我们已经检查了多个具有相同问题的线程,但找不到任何解决方案。

我们不提供任何促销活动,产品标识符有效... 一些用户可以毫无问题地进行购买。

有什么想法吗?

import Foundation
import SwiftyStoreKit
import StoreKit

final class IAPService: NSObject {

    static let shared = IAPService()
    public var isSubscriptionAvailable = false

    private var identifiers = ["product_x_id",
                               "product_y_id",
                               "product_z_id"]
    var products: [SKProduct] = []
    var purchaseProducts: [PurchaseProduct] = []

    private var successBlock: ((String?,String?)->())? //product Id, receipt
    private var errorBlock: ((String)->())?

    private var productsRequest: SKProductsRequest?
    private var productsRequestCompletionHandler: (()->())?

    override init() {
        super.init()
        SKPaymentQueue.default().add(self)
        self.loadProducts()
    }


    func loadProducts(completion: (()->())? = nil) {
        productsRequest?.cancel()
        productsRequestCompletionHandler = completion

        productsRequest = SKProductsRequest(productIdentifiers: Set(identifiers))
        productsRequest?.delegate = self
        productsRequest?.start()
    }

    func purchaseProduct(identifier: String, onSuccess: ((String?,String?) -> ())?, onError: ((String?)  -> ())?) {
        guard products.count > 0 else {
            loadProducts {
                self.purchaseProduct(identifier: identifier, onSuccess: onSuccess, onError: onError)
            }
            return
        }
        guard let product = self.products.first(where: { (skProduct) -> Bool in
            return skProduct.productIdentifier == identifier
        }) else {
            onError?("IAP error: cannot find product id")
            return
        }
        clearHandlers()
        self.successBlock = onSuccess
        self.errorBlock = onError

        print("Buying \(product.productIdentifier)...")
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }

    public func restorePurchases(onSuccess: ((String?,String?) -> ())?, onError: ((String?)  -> ())?) {
        clearHandlers()
        self.successBlock = onSuccess
        self.errorBlock = onError
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    public func fetchReceipt(productId: String) {
        SwiftyStoreKit.fetchReceipt(forceRefresh: false) { (result) in
            switch result {
            case .success(let receiptData):
                self.successBlock?(productId, receiptData.base64EncodedString(options: []))
                self.clearHandlers()
                break
            case .error(let error):
                print("Receipt verification failed: \(error.localizedDescription)")

                self.errorBlock?(error.localizedDescription)
                self.clearHandlers()
                break
            }
        }
    }

    private func clearHandlers() {
        successBlock = nil
        errorBlock = nil
        productsRequestCompletionHandler = nil
        productsRequest = nil
    }
}

extension IAPService: SKProductsRequestDelegate {

    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        print("Loaded list of products...")
        let skProducts = response.products

        skProducts.forEach { (skProduct) in
            products.append(skProduct)
        }
        productsRequestCompletionHandler?()
        clearHandlers()
    }

    public func request(_ request: SKRequest, didFailWithError error: Error) {
        print("Failed to load list of products: \(error.localizedDescription)")
        productsRequestCompletionHandler?()
        clearHandlers()
    }
}


extension IAPService: SKPaymentTransactionObserver {

    public func paymentQueue(_ queue: SKPaymentQueue,
                             updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchased:
                complete(transaction: transaction)
                break
            case .failed:
                fail(transaction: transaction)
                break
            case .restored:
                restore(transaction: transaction)
                break
            case .deferred:
                break
            case .purchasing:
                break
            }
        }
    }

    private func complete(transaction: SKPaymentTransaction) {
        print("complete...")
        deliverPurchaseNotificationFor(identifier: transaction.payment.productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func restore(transaction: SKPaymentTransaction) {
        guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }

        print("restore... \(productIdentifier)")
        deliverPurchaseNotificationFor(identifier: productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func fail(transaction: SKPaymentTransaction) {
        print("fail...")
        var failureReason: String = ""

        if let skError = transaction.error as? SKError {
            switch skError.code {  // https://developer.apple.com/reference/storekit/skerror.code
            case .unknown:
                failureReason = "Unknown or unexpected error occurred"
                break
            case .paymentCancelled:
                failureReason = "Payment cancelled by user"
                break
            case .clientInvalid:
                failureReason = "Invalid Client"
                break
            case .paymentInvalid:
                failureReason = "Invalid Payment"
                break
            case .paymentNotAllowed:
                failureReason = "Payment not allowed"
                break
            case .cloudServiceNetworkConnectionFailed:
                failureReason = "Cloud service network connection failed"
                break
            case .cloudServicePermissionDenied:
                failureReason = "Cloud service permission denied"
                break
            case .storeProductNotAvailable:
                failureReason = "Store product not available"
                break
            case .cloudServiceRevoked:
                failureReason = "Cloud service revoked"
                break
            case .privacyAcknowledgementRequired:
                failureReason = "Privacy Acknowledgement Required"
                break
            case .unauthorizedRequestData:
                failureReason = "Unauthorized Request Data"
                break
            case .invalidOfferIdentifier:
                failureReason = "Invalid offer identifier"
                break
            case .invalidSignature:
                failureReason = "Invalid signature"
                break
            case .missingOfferParams:
                failureReason = "Missing offer params"
                break
            case .invalidOfferPrice:
                failureReason = "Invalid offer price"
                break
            }
            failureReason += " code: \(skError.code.rawValue)"
        }
        else if let isCancelledError = transaction.error?.isCancelledError, isCancelledError == true {
            failureReason = "isCancelledError"
        }
        else {
            failureReason = "\(transaction.error.debugDescription)"
        }

        SKPaymentQueue.default().finishTransaction(transaction)

        errorBlock?(failureReason)
        self.clearHandlers()
    }

    private func deliverPurchaseNotificationFor(identifier: String?) {
        guard let identifier = identifier else { return }

        fetchReceipt(productId: identifier)
    }
}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我收到错误代码0或错误代码2(即使购买成功,通常也会触发错误代码2),并一直与Apple的开发人员技术支持来回发送电子邮件。在过去的几个月里。

这似乎是一个已知问题,当前在某些使用Apple的应用程序中会发生,在您的情况下,最好的做法是直接向Apple提出代码支持支持的技术支持事件(TSI)。

或者,您也可以使用反馈助手来提出错误报告。

不幸的是,这似乎是在Store Kit / App Store方面引起的,需要Apple逐一检查确实发生的情况。