在我的应用程序中,我有一个流程,用户需要添加付款方式,然后稍后收费。
所以基本上我正在做的是前端正在 ping 应用程序后端以创建条带 setup_intent:
def setup_intent
if current_account.stripe_id.blank?
render json: { data: nil, status: 'No customer ID found' }, status: :not_found
return
end
options = {
customer: current_account.stripe_id,
}
if params[:payment_method_type].present?
options[:payment_method_types] = [params[:payment_method_type]]
else
options[:automatic_payment_methods] = { enabled: true }
end
setup_intent = Stripe::SetupIntent.create(options)
data = {
client_secret: setup_intent.client_secret,
id: setup_intent.id,
}
render json: { data: data, status: "success" }, status: :ok
rescue Stripe::StripeError => e
render json: { data: nil, status: "Error: #{e.message}" }, status: :unprocessable_entity
end
通过后端响应前端获取 client_secret,然后使用它来创建 stripe.js 中可用的 PaymentElement:
fetch('http://localhost:3000/api/v2/payment_methods/setup_intent', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${bearerToken}`
}
})
.then(response => response.json())
.then(response => {
const elements = stripe.elements({
clientSecret: response.data.client_secret,
loader: 'auto',
});
// https://docs.stripe.com/js/elements_object/create_payment_element
const paymentElement = elements.create("payment", {
layout: "auto",
});
paymentElement.mount('#payment');
document.getElementById('submit').addEventListener('click', async function(event) {
// https://docs.stripe.com/js/setup_intents/confirm_card_setup
const response = await stripe?.confirmSetup({
elements,
redirect: 'if_required',
confirmParams: {
return_url: 'http://localhost:3000',
},
});
if (!!response?.error) {
alert(response.error.message);
return;
}
})
});
事情是,在我的应用程序的一个屏幕上,我需要 PaymentElement ,它将仅保存卡作为付款选项,而在另一个屏幕上仅保存 PayPal,在一个屏幕上仅保存 Apple Pay。卡和贝宝一切正常,但我坚持使用苹果支付。
例如,当我想在 PaymentElement 中仅显示卡时,我使用以下网址:
http://localhost:3000/api/v2/payment_methods/setup_intent?payment_method_type=card
对于贝宝:
http://localhost:3000/api/v2/payment_methods/setup_intent?payment_method_type=paypal
但是当我想显示apple pay时:
http://localhost:3000/api/v2/payment_methods/setup_intent?payment_method_type=apple_pay
我遇到错误:
{
"data": null,
"status": "Error: The payment method type \"apple_pay\" is invalid. See https://stripe.com/docs/api/setup_intents/create#create_setup_intent-payment_method_types for the full list of supported payment method types. Please also ensure the provided types are activated in your dashboard (https://dashboard.stripe.com/account/payments/settings) and your account is enabled for any features that you are trying to use."
}
如果我不发送 payment_method_type 查询字符串到路由,后端将使用
automatic_payment_methods: {enabled: true}
创建 setup_intent 并使用 client_secret apple pay 启动 PaymentElement,显示正常。
Apple Pay 支付方式是真正意义上的数字钱包,它只是卡支付方式的便捷包装(带有一些花哨的功能)。这就是为什么
apple_pay
和 google_pay
都不是有效的付款方式类型。
因此,您需要为您的设置意图启用
card
付款方式才能显示 Apple Pay。对于支付元素,这仍然会呈现卡选项。
要仅渲染 Apple Pay UI,我建议您使用 Express Checkout Element。它默认显示所有数字钱包和类似钱包的支付方式类型(ApplePay、GPay、PayPal 等),但您可以