adyen-ios: Unable to get pay button response in card component method ios

I am using version 4.10.3 adyen payments in ios application as Demo I have a test account and client key I am able to open card controller view in app but the pay button is start showing indicator on click and always gives didfail() and error is 500 http error. this is my code.

//
//  ViewController.swift
//  
//
//  Created by Admin on 14/07/23.
//

import UIKit
import Adyen
import Combine


class ViewController: UIViewController, PaymentComponentDelegate {
   
   // let clientKey = ""
    let clientKey =  "" // I have passed client key.
    var apiContext: APIContext?
    @IBOutlet weak var currencyTF: UITextField!
    @IBOutlet weak var AmountTF: UITextField!
    var cardPaymentMethod: CardPaymentMethod!
    var payment: PaymentMethodsResponse!
    var cardDetails = [String]()
    var cardName = String()
    weak var cardComponentDelegate: CardComponentDelegate?
    var formButton: FormButtonItem?
    var cardComponentG: CardComponent?

    
    
    func didSubmit(_ data: Adyen.PaymentComponentData, from component: Adyen.PaymentComponent) {
      print("Success")
    }
    
    func didFail(with error: Error, from component: Adyen.PaymentComponent) {
        print("failure -->", error)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.cardComponentG?.delegate = self
        let cartID = "33938f63-3abd-485f-9ad7-ed99981e9381" // Replace with your cartID
        let token = "hGgmd1q9gIIznCEVGnRf7opnjbiLVyPM" // Replace with your actual token
        self.hitAPI(cartID: cartID, token: token)
    }
    
    
    @IBAction func paymentCheckout(_ sender: Any) {
        self.test()
    }
    
    func test() {
        
        let apiContext = APIContext(environment: Environment.test, clientKey: clientKey)
        // Add additional required parameters if needed and inject the instance of `APIContext`.
        let confg = CardComponent.Configuration(showsHolderNameField: true, showsStorePaymentMethodField: false)
        let paymentMethod = MyCardPaymentMethod(type: "scheme", name: cardName, brands: cardDetails, fundingSource: .credit)
        let styleBlack =  FormComponentStyle(tintColor: .black)
        
        let cardComponent = CardComponent(paymentMethod: paymentMethod, apiContext: apiContext, configuration:confg, style: styleBlack)
        cardComponent.delegate = self
        // cardComponent.style.backgroundColor = .blue
        
        // Keep the component instance to avoid it being destroyed after the function is executed.

        // Optional. In this example, the Pay button will display 10 EUR.
        if let price = AmountTF.text {
            let amount = (Int(price) ?? 1) * 100
            cardComponent.payment = Payment(amount: Amount(value: amount, currencyCode: "INR"), countryCode: "IN")
        } else {
            cardComponent.payment = Payment(amount: Amount(value: 0,currencyCode: "INR"), countryCode: "IN")
        }
        
        self.cardComponentG = cardComponent
        DispatchQueue.main.async {
            let presentedViewController = cardComponent.viewController // Replace with your view controller
            let transitioningDelegate = BottomPartialTransitioningDelegate()

            presentedViewController.modalPresentationStyle = .formSheet
            presentedViewController.transitioningDelegate = transitioningDelegate

            // Present the view controller
            self.present(presentedViewController, animated: true, completion: nil)
            self.cardComponentG = cardComponent
        }
        self.cardComponentG = cardComponent
    }
}


extension ViewController {
    
    func hitAPI(cartID: String, token: String) {
        let baseURLString = "https://eccobffqaapp.azurewebsites.net/v1/checkout/paymentMethods/"
        let cartIDPathComponent = "\(cartID)"
        let urlString = baseURLString + cartIDPathComponent

        guard let apiURL = URL(string: urlString) else {
            print("Invalid URL")
            return
        }

        var request = URLRequest(url: apiURL)
        request.httpMethod = "GET"
        request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

        // Make the API request using URLSession
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error.localizedDescription)")
                return
            }

            if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    if let data = data {
                        // Process the response data (if needed)
                        do {
                            let responseJSON = try JSONSerialization.jsonObject(with: data, options: [])
                            print("Response JSON: \(responseJSON)")
                            let paymentM = try JSONDecoder().decode(PaymentMethodsResponse.self, from: data)
                            self.payment = paymentM
                            for paym in self.payment.data {
                                self.cardDetails.append(contentsOf: paym.brands)
                                self.cardName = paym.name
                            }
                        } catch {
                            print("Error parsing response data: \(error)")
                        }
                    }
                } else {
                    print("API request failed with status code: \(httpResponse.statusCode)")
                }
            }
        }

        task.resume()
    }
}

struct MyCardPaymentMethod: AnyCardPaymentMethod {
    var type: String

    var name: String

    func buildComponent(using builder: PaymentComponentBuilder) -> PaymentComponent? {
        builder.build(paymentMethod: self)
    }
    var brands: [String]
    var fundingSource: CardFundingSource?
    // Add other required properties and methods as needed
}

// MARK: - Payment Methods
struct PaymentMethodsResponse: Codable {
    let statusCode: Int
    let success: Bool
    let message: String
    let data: [PaymentMethodRes]
}

// MARK: - Datum
struct PaymentMethodRes: Codable {
    let brands: [String]
    let name, type: String
}

class BottomPartialPresentationController: UIPresentationController {
    override var frameOfPresentedViewInContainerView: CGRect {
        // Adjust the frame to control the presentation's height from the bottom
        let containerViewBounds = containerView?.bounds ?? CGRect.zero
        let presentedViewHeight: CGFloat = 300 // Adjust this to your desired height
        let yOrigin = containerViewBounds.height - presentedViewHeight
        return CGRect(x: 0, y: yOrigin, width: containerViewBounds.width, height: presentedViewHeight)
    }
    // You can also implement other methods for animations and interactions if needed
}

class BottomPartialTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return BottomPartialPresentationController(presentedViewController: presented, presenting: presenting)
    }
}

please I need assisatance as soon as possible @joostvandijk help me out on this.

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

I have created a new client key there was some issue in adyen dashboard >> api credential section where I had just provided my app bundle id in ( origin column ) then the same key worked for me. thank you for the assistance @descorp

You can verify if the key is correct by running in your browser: https://checkoutshopper-test.adyen.com/checkoutshopper/v1/clientKeys/{YOUR-CLIENT-KEY}