#tarunmv30

1 messages · Page 1 of 1 (latest)

shell kindleBOT
kind stream
#

hello! what do you need help with specifically?

vestal shell
#

my bad new to discord\

kind stream
#

also, please don't paste whole screenshots like that. can you paste the relevant code here? What troublehshooting steps have you taken so far, are you seeing any error messages?

vestal shell
#

    private static let backendURL = URL(string: "https://us-central1-neilsurbanoven.cloudfunctions.net/stripe")!
    private var paymentIntentClientSecret: String?

    private lazy var payButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("Pay now", for: .normal)
        button.backgroundColor = .systemIndigo
        button.layer.cornerRadius = 5
        button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
        button.addTarget(self, action: #selector(pay), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isEnabled = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        StripeAPI.defaultPublishableKey = "pk_test_51MSCbfJMYkCh6QmLjYSQLK5gPtmLvaUMn0KrXsbFVnqVROCRere3kLrAQnKOT2Uepb5fRqv34vjgNAArl8wzPwWd00OoOZlDFj"
        view.backgroundColor = .systemBackground
        view.addSubview(payButton)
        
        NSLayoutConstraint.activate([
            payButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
            payButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
            payButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16)
        ])
        self.fetchPaymentIntent()
    }
#
        let url = Self.backendURL.appendingPathComponent("/create-payment-intent")
        let shoppingCartContent: [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: shoppingCartContent)

        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
            
            DispatchQueue.main.async {
                self?.payButton.isEnabled = true
                print("Got to the pay button")
            }
        })
        task.resume()
    }

    func displayAlert(title: String, message: String? = nil) {
        DispatchQueue.main.async {
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default))
            self.present(alertController, animated: true)
        }
    }
real owl
#

👋 What exactly do you need help with?

vestal shell
#

this is the code i have for my checkout view controller

#

which is straight from the docs

#

im trying to incorporate this into a view to display the payment button

#
import SwiftUI
import StripePaymentSheet

struct CheckoutView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Welcome to my app!")
                CheckoutViewControllerRepresentable()
            }
        }
    }
}

struct CheckoutViewControllerRepresentable: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UINavigationController {
        let viewController = CheckoutViewController()
        let navigationController = UINavigationController(rootViewController: viewController)
        return navigationController
    }
    
    func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
    }
}
real owl
#

Okie, did you have print("Got to the pay button") on your console?

vestal shell
#

this is how im displaying it in the view

#

Yes it printed

#

thats what the view looks like on the simulator

real owl
#

This is before the fetchPaymentIntent(), your code wasn't display the raw button in the first place

#

The quickstart Doc you were looking into doesn't incorporate SwiftUI

vestal shell
#

okay let me try

real owl
vestal shell
#

be back in a min

real owl
#

You are doing CheckoutViewController in UiKit but trying to call it from SwiftUI, which is why it doesn't work

vestal shell
#

gotcha my bad

#

i GOT IT THANK YOU SO MUCH!

#

wait it only worked because I was using the glitch server

#

im using cloud functions to host and for some reason it wont work even though the function is properly deployed

real owl
#

So that's different issue. You would want to make sure you can curl your cloud function before call from iOS

vestal shell
#

How would i go about doing that?

#
class MyBackendModel: ObservableObject {
    let backendCheckoutUrl = URL(string: "https://us-central1-neilsurbanoven.cloudfunctions.net/stripe/create-payment-intent")!  // An example backend endpoint
    @Published var paymentSheet: PaymentSheet?
    @Published var paymentResult: PaymentSheetResult?

    func preparePaymentSheet() {
        // MARK: Fetch the PaymentIntent and Customer information from the backend
        var request = URLRequest(url: backendCheckoutUrl)
        request.httpMethod = "POST"
        let task = URLSession.shared.dataTask(
            with: request,
            completionHandler: { (data, _, _) in
                guard let data = data,
                    let json = try? JSONSerialization.jsonObject(with: data, options: [])
                        as? [String: Any],
                    let customerId = json["customer"] as? String,
                    let customerEphemeralKeySecret = json["ephemeralKey"] as? String,
                    let paymentIntentClientSecret = json["paymentIntent"] as? String,
                    let publishableKey = json["publishableKey"] as? String
                else {
                    print("There was an errir with the data")
                    return
                }
#

its printing the error statement

#

the curl was successful

real owl
#

Have you tried putting breakpoint into the completionHandler ?

#

That function expects customer, ephemeralKey paymentIntent and publishableKey

#

While you only returns clientSecret

vestal shell
#

let me fix that

#

Now I am getting this error, at least the buy button appeared but the payment sheet fails to display and show that error\

#

it seems my publishable key isnt properly sending

#

do you know why thats happening?

#

wait let me see