iOS IAP paymentQueue: обновленные транзакции

SKPaymentTransactionObserver.paymentQueue:updatedTransactions возвращает массив транзакций. Когда я делаю платеж, как я узнаю, какую транзакцию я сделал? Всегда ли возвращается одна транзакция при совершении платежа?

Между тем, эта функция наблюдателя также вызывается при восстановлении транзакций. Итак, какова лучшая практика для обработки обновленных транзакций?

Кстати, мой продукт подписки - это подписка с автоматическим продлением.

1 ответ

Итерируйте цикл транзакций и проверяйте каждую транзакцию.

    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                completeTransaction(transaction: transaction)
                break
            case .failed:
                failedTransaction(transaction: transaction)
                break
            case .restored:
                restoreTransaction(transaction: transaction)
                break
            case .deferred:
                // TODO show user that is waiting for approval

                break
            case .purchasing:
                break
            }
        }
    }

    private func completeTransaction(transaction: SKPaymentTransaction) {

        print("completeTransaction...")

        deliverPurchaseForIdentifier(identifier: transaction.payment.productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)

    }

    private func restoreTransaction(transaction: SKPaymentTransaction) {


        guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }

        print("restoreTransaction... \(productIdentifier)")


        deliverPurchaseForIdentifier(identifier: productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func failedTransaction(transaction: SKPaymentTransaction) {

        if let error = transaction.error as NSError? {
            if error.domain == SKErrorDomain {
                // handle all possible errors
                switch (error.code) {
                case SKError.unknown.rawValue:
                    print("Unknown error")

                    BaseViewController.currentViewController?.Alert(title: MFErrors.purchaseFaild.messgae.title, msg: MFErrors.purchaseFaild.messgae.body)

                case SKError.clientInvalid.rawValue:
                    print("client is not allowed to issue the request")

                    BaseViewController.currentViewController?.Alert(title: MFErrors.accountNotAllowedToMakePurchase.messgae.title, msg: MFErrors.accountNotAllowedToMakePurchase.messgae.body)

                case SKError.paymentCancelled.rawValue:
                    print("user cancelled the request")

                case SKError.paymentInvalid.rawValue:
                    print("purchase identifier was invalid")

                case SKError.paymentNotAllowed.rawValue:
                    print("this device is not allowed to make the payment")
                    BaseViewController.currentViewController?.Alert(title: MFErrors.purchaseFaild.messgae.title, msg: MFErrors.purchaseFaild.messgae.body)
                default:
                    break;
                }
            }

            ProgressViewManager.shared.hide()
        }

        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func deliverPurchaseForIdentifier(identifier: String?) {

        guard let identifier = identifier else { return }

       //Check if this transactions is a subscription
       //SubscriptionsProductIdentifiers is an array of subscriptions product ids you sent to the app store to get SKProducts

        //If subscription
        if SubscriptionsProductIdentifiers.contains(identifier) {


        }else{
           //If non-consumable, consumables etc... 

        }


    }

Вот полный Менеджер магазина в моем предыдущем ответе: Как обработать должен AddStorePayment для покупок в приложении в iOS 11?

Другие вопросы по тегам