Невозможно обработать платеж с помощью Apple Pay. Тип способа оплаты apple_pay недействителен.IOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Невозможно обработать платеж с помощью Apple Pay. Тип способа оплаты apple_pay недействителен.

Сообщение Anonymous »

Я пытаюсь добавить процессор платежей 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. Я попытался воссоздать сертификаты и идентификатор продавца.
Это мой обработчик платежей:

Код: Выделить всё

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:
Изображение
Изображение

Не могли бы вы мне сказать как отладить? Я понятия не имею, что еще я могу сделать.

Подробнее здесь: https://stackoverflow.com/questions/786 ... type-apple
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • API оплаты PayFort «Отсутствует параметр» для оплаты Apple Pay
    Гость » » в форуме IOS
    0 Ответы
    82 Просмотры
    Последнее сообщение Гость
  • Добавьте комиссию при оформлении заказа WooCommerce в зависимости от выбранного способа доставки, способа оплаты и почто
    Anonymous » » в форуме Php
    0 Ответы
    32 Просмотры
    Последнее сообщение Anonymous
  • Проблема оплаты Stripe в отношении PaymentIntent требует способа оплаты
    Anonymous » » в форуме C#
    0 Ответы
    132 Просмотры
    Последнее сообщение Anonymous
  • Проблема оплаты Stripe в отношении PaymentIntent требует способа оплаты
    Anonymous » » в форуме C#
    0 Ответы
    96 Просмотры
    Последнее сообщение Anonymous
  • Как отображать настраиваемые поля оплаты при выборе способа оплаты в WooCommerce Checkout?
    Anonymous » » в форуме Php
    0 Ответы
    39 Просмотры
    Последнее сообщение Anonymous

Вернуться в «IOS»