iOS: Swift: MobilePaymentsSDK: Payments screen would not get presented for card reader swipe

I am expecting this below method would present attached screen on my app. But, it does not.

May I know the reasons in what instances this method makeSquareTransaction() would not present the payment screen? Or, how do I correct this method?

func makeSquareTransaction(
    centsAmount: Int,
    notes: String,
    from viewController: UIViewController) {
    guard let vc = viewController as? PaymentManagerDelegate else {
        print("PaymentManagerDelegate is required")
        return
    }
    let amountMoney = Money(amount: UInt(centsAmount), currency: .USD)
    let paymentParams = makePaymentParameters(amountMoney: amountMoney)
    let paymentPromptParameters = PromptParameters(
        mode: .default,
        additionalMethods: .all
    )
    
    MobilePaymentsSDK.shared.paymentManager.startPayment(
        paymentParams,
        promptParameters: paymentPromptParameters,
        from: viewController,
        delegate: vc
    )
}

func makePaymentParameters(amountMoney: Money) -> PaymentParameters {
    PaymentParameters(
        // Unique idempotency String for payment
        idempotencyKey: String(UUID().uuidString.prefix(8)),

        // Amount to transact and always in USD
        amountMoney: Money(amount: amountMoney.amount, currency: .USD),

        // Supports only online
        processingMode: .onlineOnly
    )
}

Are you getting an error when this code runs? If so what’s the error message. :slight_smile:

  1. No, I don’t get any error.
  2. I can’t enable SSL on this to monitor the traffic on Square production APIs to see if this calls any API and what could be the error.

Common Reasons for Payment Screen Not Appearing

  1. SDK Initialization First, verify the SDK is properly initialized. Add this before calling makeSquareTransaction:
// Add at app startup or before payments
func initializeSDK() {
    do {
        try MobilePaymentsSDK.shared.initialize(applicationLaunchOptions: nil)
        print("Square SDK initialized successfully")
    } catch {
        print("Failed to initialize Square SDK: \(error)")
    }
}
  1. Delegate Implementation Ensure your view controller properly implements PaymentManagerDelegate:
class YourViewController: UIViewController, PaymentManagerDelegate {
    // Required delegate methods
    func paymentManager(_ paymentManager: PaymentManager, didCompletePayment result: PaymentResult) {
        // Handle successful payment
    }
    
    func paymentManager(_ paymentManager: PaymentManager, didFailPayment error: Error) {
        // Handle payment failure
    }
    
    func paymentManagerDidCancel(_ paymentManager: PaymentManager) {
        // Handle payment cancellation
    }
}
  1. Modified Payment Parameters Here’s the complete makePaymentParameters function with all required fields:
func makePaymentParameters(amountMoney: Money) -> PaymentParameters {
    return PaymentParameters(
        idempotencyKey: UUID().uuidString,
        amountMoney: amountMoney,
        // Add these required parameters
        autocomplete: false,
        locationId: "YOUR_LOCATION_ID",
        customerId: nil,  // Optional
        notes: notes,     // Optional
        statementDescription: nil,  // Optional
        metadata: nil     // Optional
    )
}
  1. Updated Transaction Method Here’s the corrected makeSquareTransaction method with error handling:
func makeSquareTransaction(
    centsAmount: Int,
    notes: String,
    from viewController: UIViewController
) {
    // Verify SDK initialization
    guard MobilePaymentsSDK.shared.isInitialized else {
        print("Square SDK not initialized")
        return
    }
    
    // Verify delegate
    guard let vc = viewController as? PaymentManagerDelegate else {
        print("PaymentManagerDelegate is required")
        return
    }
    
    // Create payment parameters
    let amountMoney = Money(amount: UInt(centsAmount), currency: .USD)
    let paymentParams = makePaymentParameters(amountMoney: amountMoney)
    
    // Create prompt parameters
    let paymentPromptParameters = PromptParameters(
        mode: .default,
        additionalMethods: .all
    )
    
    // Start payment with completion handler
    DispatchQueue.main.async {
        MobilePaymentsSDK.shared.paymentManager.startPayment(
            paymentParams,
            promptParameters: paymentPromptParameters,
            from: viewController,
            delegate: vc
        ) { result in
            switch result {
            case .success:
                print("Payment screen presented successfully")
            case .failure(let error):
                print("Failed to present payment screen: \(error)")
            }
        }
    }
}

Implementation Checklist

  1. Verify Info.plist Settings
<key>NSCameraUsageDescription</key>
<string>Required for card scanning</string>
<key>NSMicrophoneUsageDescription</key>
<string>Required for tap to pay</string>
<key>NSNFCReaderUsageDescription</key>
<string>Required for tap to pay</string>
  1. Add Required Capabilities In Xcode:
  • Enable “Near Field Communication Tag Reading” capability
  • Enable “Payment Processing” capability
  1. Usage Example
class YourViewController: UIViewController, PaymentManagerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeSDK()
    }
    
    @IBAction func onPayButtonTapped(_ sender: Any) {
        makeSquareTransaction(
            centsAmount: 1000, // $10.00
            notes: "Test payment",
            from: self
        )
    }
    
    // Delegate methods implementation
    func paymentManager(_ paymentManager: PaymentManager, didCompletePayment result: PaymentResult) {
        print("Payment completed: \(result)")
    }
    
    func paymentManager(_ paymentManager: PaymentManager, didFailPayment error: Error) {
        print("Payment failed: \(error)")
    }
    
    func paymentManagerDidCancel(_ paymentManager: PaymentManager) {
        print("Payment cancelled")
    }
}

Debugging Steps

  1. Add logging to track the flow:
print("SDK Initialized: \(MobilePaymentsSDK.shared.isInitialized)")
print("Payment Parameters: \(paymentParams)")
print("View Controller: \(viewController)")
  1. Check for any console errors or warnings
  2. Verify you’re calling this on the main thread

Thank you for your reply @Bryan-Square

The suggested usage of the methods from SDK might have changed because I get the below errors. Could you please check?


Compilation Error - 1

image


Compilation Error - 2

[quote=“Bryan-Square, post:4, topic:22625”]


Compilation Error - 3

This error occurs when I add the block to the startPayment method that has check for the result.


I am able to add “Near Field Communication Tag Reading” capability. But not “Payment Processing” as such capability is not listed when I searched.

Thank you much

Hi @Bryan-Square , I hope you had chance to check this. The code you suggested are having compilation errors. Could that be from older version of SDK? I am using 2.2.3 version of SquarePaymentsSDK

What was the last version that you had working? :slight_smile:

Hi @Bryan-Square

Sorry for the late reply, I was out of station.
We were migrating from SquareReaderSDK to SquarePaymentsSDK. This is the first time we are using SquarePaymentsSDK and the version is 2.2.3.

So it’s just the payment that’s failing? are you able to connect a reader? :slight_smile:

Here are the series of events happened on this chat. 3rd point onwards.

  1. I followed the SDK example and developed code.
  2. With the code that I developed - I am unable to present the Payment Screen. I believe - similar to ReaderSDK, I will be able to connect my Reader once I present the Square payment screen attached to this comment. But, I am unable to present that Square screen.
  3. So, I raised this ticket.
  4. You suggested some code changes.
  5. I incorporated those changes. And, I am having compilation errors with the code-changes that you mentioned on this comment.
  6. I mentioned those compilation errors in this comment on this same thread..

Connecting to a reader will be on a different screen then the payment screen. If you revert the changes back to when it was working are there any errors? :slight_smile: