OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Unable to process stripe payment using Apple pay. The payment method type apple_pay is invalid

  • Thread starter Thread starter Vampavi
  • Start date Start date
V

Vampavi

Guest
I am trying to add stripe payment processor to my apple swiftui code. When I am trying to make the payment I keep getting the following error in my console.

Server side error:

Code:
Received data: {'amount': 1000, 'currency': 'jpy'}
Creating PaymentIntent with amount: 1000 and currency: jpy
Error occurred: Request req_1i6XdalbzHAek8: The payment method type "apple_pay" is invalid. Please ensure the provided type is activated in your dashboard (https://dashboard.stripe.com/account/payments/settings) and your account is enabled for any preview features that you are trying to use.

Server side code (python):

Code:
@app.route('/create-payment-intent', methods=['POST'])
def create_payment_intent():
    try:
        data = request.get_json()
        print("Received data:", data)  # Print the received data for debugging

        amount = data.get('amount')  # Amount in cents
        currency = data.get('currency', 'jpy')  # Default to JPY if not provided

        print(f"Creating PaymentIntent with amount: {amount} and currency: {currency}")

        # Create a PaymentIntent with the order amount and currency
        intent = stripe.PaymentIntent.create(
            amount=amount,
            currency=currency,
            payment_method_types=["card", "apple_pay"],
        )

        print("PaymentIntent created successfully:", intent)

        return jsonify({
            'clientSecret': intent['client_secret']
        })
    except Exception as e:
        print("Error occurred:", e)  # Print the error message
        return jsonify({'error': str(e)}), 403

I have verified that Apple pay is activated in my account. I have tried recreating the certificates and merchant id. This is my payment handler:

Code:
import Foundation
import PassKit
import Firebase
import FirebaseFirestore
import Stripe

typealias PaymentCompletionHandler = (Bool) -> Void

class PaymentHandler: NSObject {
    
    var paymentController: PKPaymentAuthorizationController?
    var paymentSummaryItems = [PKPaymentSummaryItem]()
    var paymentStatus = PKPaymentAuthorizationStatus.failure
    var completionHandler: PaymentCompletionHandler?
    var userInfo: [String: String] = [:]
    
    static let supportedNetworks: [PKPaymentNetwork] = [
        .visa,
        .masterCard,
        .amex
    ]
    
    class func applePayStatus() -> (canMakePayments: Bool, canSetupCards: Bool) {
        return (PKPaymentAuthorizationController.canMakePayments(),
                PKPaymentAuthorizationController.canMakePayments(usingNetworks: supportedNetworks))
    }
    
    func startPayment(userInfo: [String: String], completion: @escaping PaymentCompletionHandler) {
        self.userInfo = userInfo
        completionHandler = completion
        
        paymentStatus = .failure
        paymentSummaryItems = []
        
        let total = PKPaymentSummaryItem(label: "Report", amount: NSDecimalNumber(string: RemoteConfigManager.value(forKey: RCKey.reportCost)), type: .final)
        paymentSummaryItems.append(total)
        
        let paymentRequest = StripeAPI.paymentRequest(withMerchantIdentifier: "merchant.my.merchant.id", country: "JP", currency: "JPY")
        paymentRequest.paymentSummaryItems = paymentSummaryItems
        paymentRequest.supportedNetworks = PaymentHandler.supportedNetworks

        if StripeAPI.canSubmitPaymentRequest(paymentRequest) {
            paymentController = PKPaymentAuthorizationController(paymentRequest: paymentRequest)
            paymentController?.delegate = self
            paymentController?.present(completion: { (presented: Bool) in
                if presented {
                    debugPrint("Presented payment controller")
                } else {
                    debugPrint("Failed to present payment controller")
                    completion(false)
                }
            })
        } else {
            debugPrint("Cannot submit payment request")
            completion(false)
        }
    }
}

extension PaymentHandler: PKPaymentAuthorizationControllerDelegate {
    func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
        let url = URL(string: "https://my_website.com/create-payment-intent")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let body: [String: Any] = [
            "amount": 1000,  // Amount in cents
            "currency": "jpy"
        ]
        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                debugPrint("Network request failed: \(String(describing: error))")
                completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
                return
            }

            do {
                // Print the received JSON for debugging
                if let jsonString = String(data: data, encoding: .utf8) {
                    debugPrint("Received JSON response: \(jsonString)")
                }

                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let clientSecret = json["clientSecret"] as? String {
                    
                    // Create a PaymentMethod from the PKPayment
                    STPAPIClient.shared.createPaymentMethod(with: payment) { paymentMethod, error in
                        if let error = error {
                            debugPrint("Failed to create payment method: \(error)")
                            completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
                            return
                        }

                        guard let paymentMethod = paymentMethod else {
                            debugPrint("Payment method is nil")
                            completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
                            return
                        }

                        // Confirm the PaymentIntent
                        let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret)
                        paymentIntentParams.paymentMethodId = paymentMethod.stripeId

                        STPAPIClient.shared.confirmPaymentIntent(with: paymentIntentParams) { paymentIntent, error in
                            if let error = error {
                                debugPrint("Failed to confirm payment intent: \(error)")
                                completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
                            } else {
                                completion(PKPaymentAuthorizationResult(status: .success, errors: nil))
                            }
                        }
                    }
                } else {
                    debugPrint("Invalid JSON response")
                    completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
                }
            } catch {
                debugPrint("JSON parsing error: \(error)")
                completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
            }
        }
        task.resume()
    }

    func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
        controller.dismiss {
            DispatchQueue.main.async {
                if self.paymentStatus == .success {
                    self.completionHandler?(true)
                } else {
                    self.completionHandler?(false)
                }
            }
        }
    }
}

Stripe Dashboard confirming Apple Pay is active: enter image description here enter image description here

Could you tell me how to debug? I am clueless what more can I do.
<p>I am trying to add stripe payment processor to my apple swiftui code. When I am trying to make the payment I keep getting the following error in my console.</p>
<p>Server side error:</p>
<pre><code>Received data: {'amount': 1000, 'currency': 'jpy'}
Creating PaymentIntent with amount: 1000 and currency: jpy
Error occurred: Request req_1i6XdalbzHAek8: The payment method type "apple_pay" is invalid. Please ensure the provided type is activated in your dashboard (https://dashboard.stripe.com/account/payments/settings) and your account is enabled for any preview features that you are trying to use.
</code></pre>
<p>Server side code (python):</p>
<pre><code>@app.route('/create-payment-intent', methods=['POST'])
def create_payment_intent():
try:
data = request.get_json()
print("Received data:", data) # Print the received data for debugging

amount = data.get('amount') # Amount in cents
currency = data.get('currency', 'jpy') # Default to JPY if not provided

print(f"Creating PaymentIntent with amount: {amount} and currency: {currency}")

# Create a PaymentIntent with the order amount and currency
intent = stripe.PaymentIntent.create(
amount=amount,
currency=currency,
payment_method_types=["card", "apple_pay"],
)

print("PaymentIntent created successfully:", intent)

return jsonify({
'clientSecret': intent['client_secret']
})
except Exception as e:
print("Error occurred:", e) # Print the error message
return jsonify({'error': str(e)}), 403
</code></pre>
<p>I have verified that Apple pay is activated in my account. I have tried recreating the certificates and merchant id.
This is my payment handler:</p>
<pre><code>import Foundation
import PassKit
import Firebase
import FirebaseFirestore
import Stripe

typealias PaymentCompletionHandler = (Bool) -> Void

class PaymentHandler: NSObject {

var paymentController: PKPaymentAuthorizationController?
var paymentSummaryItems = [PKPaymentSummaryItem]()
var paymentStatus = PKPaymentAuthorizationStatus.failure
var completionHandler: PaymentCompletionHandler?
var userInfo: [String: String] = [:]

static let supportedNetworks: [PKPaymentNetwork] = [
.visa,
.masterCard,
.amex
]

class func applePayStatus() -> (canMakePayments: Bool, canSetupCards: Bool) {
return (PKPaymentAuthorizationController.canMakePayments(),
PKPaymentAuthorizationController.canMakePayments(usingNetworks: supportedNetworks))
}

func startPayment(userInfo: [String: String], completion: @escaping PaymentCompletionHandler) {
self.userInfo = userInfo
completionHandler = completion

paymentStatus = .failure
paymentSummaryItems = []

let total = PKPaymentSummaryItem(label: "Report", amount: NSDecimalNumber(string: RemoteConfigManager.value(forKey: RCKey.reportCost)), type: .final)
paymentSummaryItems.append(total)

let paymentRequest = StripeAPI.paymentRequest(withMerchantIdentifier: "merchant.my.merchant.id", country: "JP", currency: "JPY")
paymentRequest.paymentSummaryItems = paymentSummaryItems
paymentRequest.supportedNetworks = PaymentHandler.supportedNetworks

if StripeAPI.canSubmitPaymentRequest(paymentRequest) {
paymentController = PKPaymentAuthorizationController(paymentRequest: paymentRequest)
paymentController?.delegate = self
paymentController?.present(completion: { (presented: Bool) in
if presented {
debugPrint("Presented payment controller")
} else {
debugPrint("Failed to present payment controller")
completion(false)
}
})
} else {
debugPrint("Cannot submit payment request")
completion(false)
}
}
}

extension PaymentHandler: PKPaymentAuthorizationControllerDelegate {
func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
let url = URL(string: "https://my_website.com/create-payment-intent")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
"amount": 1000, // Amount in cents
"currency": "jpy"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])

let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
debugPrint("Network request failed: \(String(describing: error))")
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
return
}

do {
// Print the received JSON for debugging
if let jsonString = String(data: data, encoding: .utf8) {
debugPrint("Received JSON response: \(jsonString)")
}

if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let clientSecret = json["clientSecret"] as? String {

// Create a PaymentMethod from the PKPayment
STPAPIClient.shared.createPaymentMethod(with: payment) { paymentMethod, error in
if let error = error {
debugPrint("Failed to create payment method: \(error)")
completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
return
}

guard let paymentMethod = paymentMethod else {
debugPrint("Payment method is nil")
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
return
}

// Confirm the PaymentIntent
let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret)
paymentIntentParams.paymentMethodId = paymentMethod.stripeId

STPAPIClient.shared.confirmPaymentIntent(with: paymentIntentParams) { paymentIntent, error in
if let error = error {
debugPrint("Failed to confirm payment intent: \(error)")
completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
} else {
completion(PKPaymentAuthorizationResult(status: .success, errors: nil))
}
}
}
} else {
debugPrint("Invalid JSON response")
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
}
} catch {
debugPrint("JSON parsing error: \(error)")
completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
}
}
task.resume()
}

func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
controller.dismiss {
DispatchQueue.main.async {
if self.paymentStatus == .success {
self.completionHandler?(true)
} else {
self.completionHandler?(false)
}
}
}
}
}
</code></pre>
<p>Stripe Dashboard confirming Apple Pay is active:
<a href="https://i.sstatic.net/GP4tFwwQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GP4tFwwQ.png" alt="enter image description here" /></a>
<a href="https://i.sstatic.net/2Z39piM6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2Z39piM6.png" alt="enter image description here" /></a></p>
<p>Could you tell me how to debug? I am clueless what more can I do.</p>
Continue reading...
 

Latest posts

I
Replies
0
Views
1
impact christian
I
Top