Hosted checkout page integration

Hosted Checkout Page is a comprehensive, all-in-one solution designed to streamline the checkout process. By consolidating Apple Pay, instant bank transfers, and card payments into a single, intuitive interface, it provides a frictionless transaction experience that drives higher conversion rates.

Implementation


import SwiftUI
import PayablMerchant
import Combine


class CartViewModel: ObservableObject {
  @Published var isLoading = false
  let backendCheckoutUrl = URL(string: "backend_endpoint/payment_page")!  // In your server, this API should call mobile/init API
  func prepareOrder() async -> PBLConfiguration? {
      var request = URLRequest(url: backendCheckoutUrl)
      request.httpMethod = "POST"
      return await withCheckedContinuation { [weak self] continuation in
          let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
              guard let data = data,
                    let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
              else { return }
              let sessionId = json["sessionId"]
              let transactionId = json["transactionId"]
              let ephemeralKey = json["empheralKey"]
            return continuation.resume(
              returning: PBLConfiguration(
                sessionId: sessionId as! String,
                ephemeralKey: ephemeralKey as! String,
                customerId: "[email protected]",
                environment: .sandbox,
                transactionId: transactionId as! Int,
                appleMerchantId: "merchant.payabl.isdk"  // Apple merchant id registered in developer.apple.com
              )
            )
          })
        task.resume()
      }
  }
}
extension CartViewModel: PBLPaymentPageTapDelegate {
  func paymentPageCompleted(result: PBLPaymentResult) {
    print(result)
  }
  
  func paymentPageTapped(onLoadSessionCompleted: @escaping (PBLConfiguration) -> Void) {
    Task {
      guard let config = await prepareOrder() else { return }
      onLoadSessionCompleted(config)
    }
  }
}
extension CartViewModel: PBLErrorDelegate {
  func errorOccured(error: any Error) {
    print("error from sdk: ", error)
  }
}


struct ContentView: View {
    @StateObject var cartVM = CartViewModel()
    var body: some View {
        VStack {
          PBLPaymentButton(delegate: cartVM, errorDelegate: cartVM) {
            ZStack {
              Text("Checkout")
                .foregroundStyle(.white)
                .font(.body)
                .frame(maxWidth: .infinity, minHeight: 45)
            }
          }
        }
        .foregroundStyle(.white)
        .background(.black)
        .clipShape(RoundedRectangle(cornerRadius: 10))
        .padding()
    }
}