无法正确解析JSON使用带有条纹的Firebase

人气:356 发布:2022-10-16 标签: ios firebase swift stripe-payments

问题描述

错误是- 线程7:";无法根据协议STPCustomerEphEmeralKeyProvider分析临时密钥响应。确保您的后端将临时密钥的未经修改的JSON发送到您的应用程序。有关详细信息,请参阅https://stripe.com/docs/mobile/ios/standard#prepare-your-api"

错误的屏幕截图是- 我的MyAPIClient-

    import Stripe
       import UIKit
         class MyAPIClient: NSObject, STPCustomerEphemeralKeyProvider {
let baseURL = URL(string: "https://api.stripe.com")!

    func createCustomerKey(withAPIVersion apiVersion: String, completion: @escaping STPJSONResponseCompletionBlock) {
        let url = self.baseURL.appendingPathComponent("ephemeral_keys")
        var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)!
        urlComponents.queryItems = [URLQueryItem(name: "api_version", value: apiVersion)]
        var request = URLRequest(url: urlComponents.url!)
        request.httpMethod = "POST"
        let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
            guard let response = response as? HTTPURLResponse,
                response.statusCode == 200,
                let data = data,
                let json = ((try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]) as [String : Any]??) else {
                completion(nil, error)
                return
            }
            completion(json, nil)
        })
        task.resume()
    }
}

视图控制器代码-

   import UIKit
   import Stripe
   import FirebaseFunctions

  class paymentViewController: UIViewController {

@IBOutlet weak var paymentMethodButton: UIButton!
@IBOutlet weak var proceedToCheckoutButton: UIButton!

var paymentContext: STPPaymentContext!

override func viewDidLoad() {
    super.viewDidLoad()
    setupStripeConfig()
}

@IBAction func checkoutButtonClicked(_ sender: Any) {
    paymentContext.requestPayment()
}

@IBAction func paymentMethodClicked(_ sender: Any) {
    print("Payment Method Button Clicked")
    paymentContext.presentPaymentOptionsViewController()
}

func setupStripeConfig() {
    let config = STPPaymentConfiguration.shared()
    config.requiredBillingAddressFields = .none
    config.requiredShippingAddressFields = .none

    let customerContext = STPCustomerContext(keyProvider: MyAPIClient())
    paymentContext = STPPaymentContext(customerContext: customerContext, configuration: config, theme: .default())
    paymentContext.paymentAmount = 1000

    paymentContext.delegate = self
    paymentContext.hostViewController = self
     }
    }

   extension paymentViewController: STPPaymentContextDelegate {

  func paymentContextDidChange(_ paymentContext: STPPaymentContext) {
    self.paymentMethodButton.titleLabel?.text = paymentContext.selectedPaymentOption?.label
}


func paymentContext(_ paymentContext: STPPaymentContext, didFailToLoadWithError error: Error) {
    //When stripeID isn't valid or Ephemeral key could not be retrieved for some reason. Handle this with UIAlert stating error and make user re-enter info
    self.navigationController?.popViewController(animated: true)
}

func paymentContext(_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPPaymentStatusBlock) {

    var data = [
        "customer":"Abhishek"
    ]
    //Pull Payment Method
    Functions.functions().httpsCallable("getPaymentMethods").call(data) { (result, err) in
        if err != nil {
            print("Error (String(describing: err))")
            return
        }

        print(result)
    }


       let idempotency = UUID().uuidString.replacingOccurrences(of: "-", with: "")
        var paymentMethod = paymentContext.selectedPaymentOption

    let dataToSend: [String : Any] = [
        "amount" : 5000,
        "customer" : "Abhishek",
    ]

       Functions.functions().httpsCallable("createPaymentIntent").call(dataToSend) { (result, err) in
        if err != nil {
            print("Error (String(describing: err))")
            return
           }

          //var paymentParam = STPPaymentIntentParams(clientSecret: result as! String)
        print(result)
       }
   }

  func paymentContext(_ paymentContext: STPPaymentContext, didFinishWith status: STPPaymentStatus, error: Error?) {

   }

  }

如何整理?

推荐答案

创建临时密钥的请求必须在服务器端发出(使用密钥),并且您的iOS代码应该向您自己的服务器发出请求,该服务器将调用Stiped的API。

现在,您的代码(在MyApiClient中)正在尝试直接调用Strike的API来创建临时密钥客户端。这不起作用,如果您记录请求响应或检查仪表板以查看您最近的请求,您可能会看到某种错误消息。

您应该查看一下Strip的文档,了解如何创建临时密钥here--它们遍历了所有代码,并且有一个可以用于测试的毛刺端点。由于您使用的是Firebase,因此您还可以查看Havehere的示例。

116