无法使用Apple pay处理条纹支付。付款方式类型 apple_pay 无效

问题描述 投票:0回答:1

我正在尝试将 Stripe 支付处理器添加到我的 Apple SwiftUI 代码中。当我尝试付款时,我的控制台中不断出现以下错误。

服务器端错误:

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.

服务器端代码(python):

@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

我已验证我的帐户中已激活 Apple pay。我尝试重新创建证书和商家 ID。 这是我的付款处理程序:

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 仪表板确认 Apple Pay 已激活: enter image description here enter image description here

你能告诉我如何调试吗?我不知道我还能做什么。

ios iphone swiftui stripe-payments applepay
1个回答
0
投票

您设置了

payment_method_types=["card", "apple_pay"]
,但 Stripe 中没有
apple_pay
付款方式。所以您看到的错误是预期的。

如果您想创建与 Apple Pay 配合使用的 PaymentIntent,您可以使用

payment_method=["card"]"
,因为 Apple Pay 是一种银行卡支付方式。

© www.soinside.com 2019 - 2024. All rights reserved.