SwiftUI集成Stripe Apple Pay报错:payment_method_type apple_pay无效
Stripe Apple Pay 支付报错排查求助
服务器端报错日志:
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
客户端Swift PaymentHandler代码
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处于激活状态,也尝试重新生成证书和商户ID,但发起支付时仍持续出现上述服务器端报错,目前不知该如何调试,寻求帮助。
内容的提问来源于stack exchange,提问作者Vampavi
相关产品推荐
相关产品推荐

