I am trying to link stripe to firestore cloud but it show error - "error loading page: failed to decode response from the server" as shown in the image -
My cloud function i.e. index.js -
const admin = require('firebase-admin'); const express = require('express') admin.initializeApp(); const functions = require('firebase-functions'); const stripe = require('stripe') ("sk_________"); // When a user is created, register them with Stripe exports.createStripeCustomer = functions.auth.user().onCreate(async (user) => { const customer = await stripe.customers.create({email: user.email}); return admin.firestore().collection('stripe_customers').doc(user.uid).set({customer_id: customer.id}); }); exports.createPaymentIntent = functions.https.onCall(async (req, res) => { const amount = req.amount; const customer = req.customer; console.log(customer) const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', }); const clientSecret = paymentIntent.clientSecret console.log(clientSecret) return clientSecret }); exports.getPaymentMethods = functions.https.onCall(async (req, res) => { const customer = req.customer; const type = "card" stripe.paymentMethods.list({customer : customer, type: type}, function(err, paymentMethods) { if (err !== null) { console.log("ERROR") } else { return paymentMethods } return }) }); exports.createEphemeralKey = functions.https.onCall(async(data, context) => { const stripeVersion = data.stripe_version; const customerId = data.customer_id; return stripe.ephemeralKeys.create( {customer: customerId}, {stripe_version: stripeVersion} ).then((key) => { return key }).catch((err) => { console.log(err) }) }) My CheckoutViewController -
import UIKit import Stripe import Firebase let backendUrl = "https://fireupgoods-a0036.firebaseio.com/" class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? lazy var cardTextField: STPPaymentCardTextField = { let cardTextField = STPPaymentCardTextField() return cardTextField }() lazy var payButton: UIButton = { let button = UIButton(type: .custom) button.layer.cornerRadius = 5 button.backgroundColor = .systemBlue button.titleLabel?.font = UIFont.systemFont(ofSize: 22) button.setTitle("Pay now", for: .normal) button.addTarget(self, action: #selector(pay), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() StripeAPI.defaultPublishableKey = "pk_test_TYooMQauvdEDq54NiTphI7jxpk_test_51HmAsMFzRM1fSBZ2tTT1SxPxRBzParFfjm6s0aXD0F5dYLeOSVCKtiZ4lq0TGwJxPhHpsq6Hga7I0QzRWisPYMdj00bDxAMTKf" view.backgroundColor = .white let stackView = UIStackView(arrangedSubviews: [cardTextField, payButton]) stackView.axis = .vertical stackView.spacing = 20 stackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.leftAnchor.constraint(equalToSystemSpacingAfter: view.leftAnchor, multiplier: 2), view.rightAnchor.constraint(equalToSystemSpacingAfter: stackView.rightAnchor, multiplier: 2), stackView.topAnchor.constraint(equalToSystemSpacingBelow: view.safeAreaLayoutGuide.topAnchor, multiplier: 2), ]) startCheckout() } func displayAlert(title: String, message: String, restartDemo: Bool = false) { DispatchQueue.main.async { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) self.present(alert, animated: true, completion: nil) } } func startCheckout() { // Create a PaymentIntent as soon as the view loads let url = URL(string: backendUrl + "create-payment-intent")! let json: [String: Any] = [ "items": [ ["id": "xl-shirt"] ] ] var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try? JSONSerialization.data(withJSONObject: json) let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (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], let clientSecret = json["clientSecret"] as? String else { let message = error?.localizedDescription ?? "Failed to decode response from server." self?.displayAlert(title: "Error loading page", message: message) return } print("Created PaymentIntent") self?.paymentIntentClientSecret = clientSecret }) task.resume() } @objc func pay() { guard let paymentIntentClientSecret = paymentIntentClientSecret else { return; } // Collect card details let cardParams = cardTextField.cardParams let paymentMethodParams = STPPaymentMethodParams(card: cardParams, billingDetails: nil, metadata: nil) let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) paymentIntentParams.paymentMethodParams = paymentMethodParams // Submit the payment let paymentHandler = STPPaymentHandler.shared() paymentHandler.confirmPayment(paymentIntentParams, with: self) { (status, paymentIntent, error) in switch (status) { case .failed: self.displayAlert(title: "Payment failed", message: error?.localizedDescription ?? "") break case .canceled: self.displayAlert(title: "Payment canceled", message: error?.localizedDescription ?? "") break case .succeeded: self.displayAlert(title: "Payment succeeded", message: paymentIntent?.description ?? "") break @unknown default: fatalError() break } } } } extension CheckoutViewController: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { return self } } screenshot of the error -
I also have Firebase code which which I have not posted here which sends data from a viewcontroller to Firebase. If you wish I can post it here. My issue immediate issue is that I want to make this error go away and link Stripe card payments to stripe with backend whihch is Firebase. Later, I also want to link Stripe Google Pay with Firebase.
How to sort it out ?
https://stackoverflow.com/questions/66083588/stripe-firestore-error-loading-page-failed-to-decode-response-from-the-server February 07, 2021 at 09:05AM
没有评论:
发表评论