#cooldude400_best-practices

1 messages ¡ Page 1 of 1 (latest)

minor raftBOT
#

👋 Welcome to your new thread!

⏲️ We'll be here soon! Typically we respond in a few minutes, but sometimes we might take a bit longer if the server is busy or if you have a particularly tricky question.

⏱️ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can always start a new thread if you have another question.

🔗 This thread will always be available, even after it's closed. You can find it again using Discord's search, or you can save this link: https://discord.com/channels/841573134531821608/1303167721738862694

📝 Have more to share? Add more details, code, screenshots, videos, etc. below.

polar flame
#

For Example:

ForEach([ "$3", "$5", "$25", "$100", "$1000"], id: .self) { amount in
AmountButton(width: 250, height: 45, amount: amount, isSelected: amount == selectedAmount) {
selectedAmount = amount
backendModel.amount = amount
backendModel.paymentIntentParams = nil
// Update the selected amount when the button is tapped
backendModel.preparePaymentIntent(amount: backendModel.amount ?? "$3", paymentMethodType: "card", currency: "USD")

            }
            .padding(.top, 12)
        }
        if backendModel.paymentIntentParams != nil {
            PaymentButton(){
                // call our pay method
                applePayModel.pay(
                    clientSecret: backendModel.paymentIntentParams?.clientSecret,
                    amount: backendModel.amount ?? "$3"
                )
            }.padding()
        } else {
            Text("Loading...")
        }
toxic wasp
#

hello! how are you integrating with Stripe? Are you using Express Checkout Element, Payment Element?

polar flame
#

I'm not sure - I think those were only for the web? I'm developing on an IOS app - sorry I didn't specify that

#

//

import Foundation
import Stripe
import PassKit

class ApplePayModel: NSObject, ObservableObject, STPApplePayContextDelegate {

@Published var paymentStatus: STPPaymentStatus?
@Published var lastPaymentError: Error?
var clientSecret: String?


func pay(clientSecret: String?, amount: String){
    self.clientSecret = clientSecret
    // configure apple pay payment request
    let pr = StripeAPI.paymentRequest(withMerchantIdentifier: "merchant.com.helio.prod-helio", country: "US", currency: "USD")
    pr.requiredBillingContactFields = [.emailAddress]
    
    pr.paymentSummaryItems = [
        PKPaymentSummaryItem(label: "Your Monthly Donation", amount: NSDecimalNumber(string: amount.replacingOccurrences(of: "$", with: "")))
    ]
    
    // Present the apple pay context:
    let applePayContext = STPApplePayContext(paymentRequest: pr, delegate: self)
    applePayContext?.presentApplePay()
    
}

func applePayContext(_ context: StripeApplePay.STPApplePayContext, didCreatePaymentMethod paymentMethod: StripePayments.STPPaymentMethod, paymentInformation: PKPayment, completion: @escaping StripeApplePay.STPIntentClientSecretCompletionBlock) {
    // Payment method was created -> confirm paymentintent
    
    if (self.clientSecret != nil){
        // Call the completion block
        completion(clientSecret, nil)
    } else {
        completion(nil, NSError())
    }
}

func applePayContext(_ context: StripeApplePay.STPApplePayContext, didCompleteWith status: StripePayments.STPPaymentStatus, error: (any Error)?) {
    // get the payment status or error
    print("STATUS")
    print(status)
    self.paymentStatus = status
    self.lastPaymentError = error
    if status == .success {
        DispatchQueue.main.async {
            self.paymentStatus = .success
        }
    }
    
}
#

on a similar note - is there a way to add apple pay to the payment sheet? If i could add apple pay and remove link here, I think that would work the best:

func preparePaymentSheet(amount: String) {
currentSheetTask?.cancel()
// MARK: Fetch the PaymentIntent and Customer information from the backend
var request = URLRequest(url: backendCheckoutUrl)
let json: [String: Any] = [
"currency": "USD",
"paymentMethodType": "card"
,
"customer_id":UserDefaults.standard.string(forKey: customerid_key),
"price_point":amount
]
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 customerId = UserDefaults.standard.string(forKey: customerid_key),
// let customerEphemeralKeySecret = json["ephemeralKey"] as? String,
let paymentIntentClientSecret = json["paymentIntent"] as? String,
let publishableKey = json["publishableKey"] as? String,
let self = self

        else {
          print("error")
          print(response)
          print(error)
        // Handle error
        return
      }
        print("Json result")
        print(json)

      STPAPIClient.shared.publishableKey = publishableKey
      // MARK: Create a PaymentSheet instance
      var configuration = PaymentSheet.Configuration()
      configuration.merchantDisplayName = "Helio"

      // Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods
      // that complete payment after a delay, like SEPA Debit and Sofort.
      configuration.allowsDelayedPaymentMethods = false

      DispatchQueue.main.async {
        self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration)
      }
    })
      currentSheetTask = task
    task.resume()
  }
idle whale
#

Hi @polar flame is your primary objective to collect an Apple Pay payment method, and use it to pay invoices generated by a subscription?

polar flame
#

Yes so I currently implement a nagtive apple pay button and a payment sheet. My main issue is that every time the customer selects a different price, I create a payment intent that converts into an incomplete subscription, which is noisy on the backend

#

*native apple pay

idle whale
#

Hmm, I don't think you need to create an extra payment intent

polar flame
#

Can I modify the price on an already created payment intent?

idle whale
#

You should just create a subscription, and send its latest_invoice.payment_intent.client_secret to your iOS app for payment confirmation

polar flame
#

ok, i'll try that, thank you!

idle whale
polar flame
#

seperate from that, it would be great if I could turn link in my paymentsheet off, and turn apple pay in my payment sheet on. Then I can remove my native apple pay button and only use the payment sheet, which would make things a little cleaner. However, I can't seem to get link to go away, despite being disabled in my dashboard.

idle whale
polar flame
#

i think that's it