Как заставить мою систему платежей Stripe работать? - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь внедрить полосу в мое приложение, но когда я использую следующий код, страница оплаты не перестает загружаться. Что я делаю не так?

ViewController(), где кнопка для принятия заказа:

import UIKit
import Firebase
import Stripe

class ViewController: UIViewController {

    var totalAmount = 0

    override func viewDidLoad() {
    }

    @IBAction func goToPaymentButton(_ sender: UIButton) {
        print("checkoutClicked")
        let addCardViewController = STPAddCardViewController()
        addCardViewController.delegate = self
        navigationController?.pushViewController(addCardViewController, animated: true)
    }
}
extension OrderDetialsViewController: STPAddCardViewControllerDelegate {

  func addCardViewControllerDidCancel(_ addCardViewController: STPAddCardViewController) {
    navigationController?.popViewController(animated: true)
    print("0")

  }

    private func addCardViewController(_ addCardViewController: STPAddCardViewController,
                             didCreateToken token: STPToken,
                             completion: @escaping STPErrorBlock) {
        print("addcardviewcontroller")
    totalAmount = 0
    if localData.shoppingCart.itemSizeArray.count > 0{
        for i in 0...localData.shoppingCart.itemSizeArray.count-1{
            if localData.shoppingCart.itemSizeArray[i] == "hd"{
                totalAmount = totalAmount+2000
            }
            else if localData.shoppingCart.itemSizeArray[i] == "d"{
                totalAmount = totalAmount+4000
            }
            else if localData.shoppingCart.itemSizeArray[i] == "free" {
                totalAmount = totalAmount + 0
            }
            else if localData.shoppingCart.itemSizeArray[i] == "home"{
                totalAmount = totalAmount + 500
            }
        }
    }
    StripeClient.shared.completeCharge(with: token, amount: totalAmount) { result in
        print("stripeclientsharedcompletecharge")
      switch result {
      // 1
      case .success:
        print("success")
        completion(nil)

        let alertController = UIAlertController(title: "Congrats",
                              message: "Your payment was successful!",
                              preferredStyle: .alert)
        let alertAction = UIAlertAction(title: "OK", style: .default, handler: { _ in
          self.navigationController?.popViewController(animated: true)
        })
        alertController.addAction(alertAction)
        self.present(alertController, animated: true)
      // 2
      case .failure(let error):
        print("failure")
        completion(error)
      }
    }
  }
}

У меня также есть StripeClient, настроенный следующим образом:

import Foundation
import Alamofire
import Alamofire
import Stripe

enum Result {
  case success
  case failure(Error)
}

final class StripeClient {

  static let shared = StripeClient()

  private init() {
    // private
  }

  private lazy var baseURL: URL = {
    guard let url = URL(string: Constants.baseURLString) else {
      fatalError("Invalid URL")
    }
    return url
  }()
  func completeCharge(with token: STPToken, amount: Int, completion: @escaping (Result) -> Void) {
    // 1
    let url = baseURL.appendingPathComponent("charge")
    // 2
    let params: [String: Any] = [
      "token": token.tokenId,
      "amount": amount,
      "currency": Constants.defaultCurrency,
      "description": Constants.defaultDescription
    ]
    // 3
    Alamofire.request(url, method: .post, parameters: params)
      .validate(statusCode: 200..<300)
      .responseString { response in
        switch response.result {
        case .success:
          completion(Result.success)
        case .failure(let error):
          completion(Result.failure(error))
        }
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...