# MobilePay 支付 Learn how to accept MobilePay, a popular payment method in Denmark and Finland. # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=checkout. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. > Stripe 可以通过评估货币、付款方式限制和其他参数,自动为客户展示相关支付方式。 > > - 请遵循[接受付款](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted)指南,构建一个使用[动态支付方式](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)的 Checkout 集成。 - 如果您不想使用动态支付方式,请按照以下步骤在 Checkout 集成中手动配置支付方式。 Use this guide to enable MobilePay on [Checkout](https://docs.stripe.com/payments/checkout.md), our hosted checkout form, and learn the differences between accepting payments using dynamic payment methods and manually configuring payment methods. ## Determine compatibility **支持的商家所在地**:EEA **支持的货币**:`eur, dkk, sek, nok` **展示货币**:`eur, dkk, sek, nok` **支付模式**:Yes **设置模式**:No **订阅模式**:No A Checkout Session must satisfy all of the following conditions to support MobilePay payments: - *Prices* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions) for all line items must be expressed in Euro, Danish Krona, Swedish Krona or Norwegian Krona (currency codes `eur`, `dkk`, `sek` or `nok`). ## Set up Stripe [Server-side] 首先,您需要一个 Stripe 账户。[立即注册](https://dashboard.stripe.com/register)。 用我们的官方库从您的应用程序访问 Stripe API: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Accept a payment > 该指南建立于基本的[接受付款](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout) Checkout 集成的基础之上。 ### Enable MobilePay as a payment method 创建新的 [Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) 时,您需要: 1. Add `mobilepay` to the list of `payment_method_types`. 1. Make sure all your `line_items` use the `eur`, `dkk`, `sek` or `nok` currency. #### Stripe-hosted page ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=dkk" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=mobilepay" \ --data-urlencode "success_url=https://example.com/success" ``` #### Embedded form ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=dkk" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=mobilepay" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### 履行订单 接受付款后,学习如何[履行订单](https://docs.stripe.com/checkout/fulfillment.md)。 ## Handle post-payment events 付款完成时,Stripe 会发送一个 [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) 事件。使用管理平台、自定义 *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 或一个合作伙伴方案来接收这些事件并运行操作,例如,向客户发送订单确认邮件、在数据库中记录订单,或启动配送流程。 侦听这些事件,而不是等待客户端的回调。在客户端上,客户可以在执行回调之前关闭浏览器窗口或退出应用程序,而且恶意客户端可以操纵响应。将集成设置为侦听异步事件还有助于您在未来接受更多支付方式。了解[所有受支持的支付方式之间的差异](https://stripe.com/payments/payment-methods-guide)。 - **在管理平台中手动处理事件** [在管理平台中查看测试支付情况](https://dashboard.stripe.com/test/payments),发送邮件收据,处理提现事宜,或重试失败的付款。 - **创建自定义 Webhook** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Test the integration #### Mobile web app testing To test your integration, choose MobilePay as the payment method and tap **Pay**. In a testing environment, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the MobilePay mobile application, where you can approve or decline the payment. #### Desktop web app testing To test your integration in a testing environment, this redirects you to a test payment page where you can approve or decline the test payment. In live mode, enter the phone number linked to MobilePay to send a push notification to your MobilePay mobile application. You can approve or decline the payment in the MobilePay mobile application. ## Optional: Authorize a payment and then capture later MobilePay supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). ### 告诉 Stripe 仅授权 To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-capture_method) to `manual` when creating the Checkout Session. This parameter instructs Stripe to only authorize the amount on the customer’s card linked to MobilePay. ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=mobilepay" \ -d "line_items[0][price_data][currency]=dkk" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d "payment_intent_data[capture_method]=manual" \ --data-urlencode "success_url=https://example.com/success.html" ``` After the authorization is successful, Stripe sends a [payment_intent.amount_capturable_updated](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.amount_capturable_updated) event. See [Events](https://docs.stripe.com/api/events.md) to learn more. ### 捕获资金 After the authorization succeeds, the PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture` and you can [capture](https://docs.stripe.com/api/payment_intents/capture.md) the authorized funds. Stripe only support manual captures of the full amount. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/capture \ -u "<>:" \ -d amount_to_capture=2000 ``` ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. ## See also - [More about MobilePay](https://docs.stripe.com/payments/mobilepay.md) - [Checkout fulfillment](https://docs.stripe.com/checkout/fulfillment.md) - [Customize Checkout](https://docs.stripe.com/payments/checkout/customization.md) # Elements > This is a Elements for when payment-ui is elements. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=elements. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. This guide shows you how to embed a custom Stripe payment form in your website or application using the [Payment Element](https://docs.stripe.com/payments/payment-element.md). The Payment Element allows you to support MobilePay and other payment methods automatically. For advanced configurations and customizations, refer to the [Accept a Payment](https://docs.stripe.com/payments/accept-a-payment.md) integration guide. ## Set up Stripe [Server-side] First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register). Use our official libraries for access to the Stripe API from your application: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Create a PaymentIntent [Server-side] Stripe uses a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process. #### Manage payment methods from the Dashboard Create a PaymentIntent on your server with an amount and currency. You can manage payment methods from the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. Before creating the Payment Intent, make sure to turn **MobilePay** on in the [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) page. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### List payment methods manually If you don’t want to use the Dashboard or want to manually specify payment methods, you can list them using the `payment_method_types` attribute. Create a PaymentIntent on your server with an amount, currency, and a list of payment methods. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=eur \ -d "payment_method_types[]=mobilepay" ``` ### 检索客户端私钥 PaymentIntent 中包含的是一个*客户端私钥* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)),用于在客户端安全地完成支付流程。有不同的方法可以将客户端私钥传递到客户端。 #### 单页应用 使用浏览器的 `fetch` 功能,从您的服务器上的端点获取客户端私钥。如果您的客户端是单页应用,特别是用现代的前端框架(例如 React)搭建的情况,则该方法最为合适。创建服务于客户端私钥的服务器端点: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` 然后在客户端用 JavaScript 获取客户端私钥: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### 服务端呈现 从服务器将客户端私钥传递到客户端。如果在将静态内容发送到浏览器之前,您的应用程序会在服务器上生成静态内容,则此种方法最有效。 在您的结账表单中添加 [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。在您的服务器代码中,从 PaymentIntent 检索客户端密钥: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## Collect payment details [Client-side] 用 [Payment Element](https://docs.stripe.com/payments/payment-element.md) 在客户端收集支付信息。Payment Element 是一个预构建的 UI 组件,它简化了多种支付方式的收集支付详情的流程。 Payment Element 中包含一个 iframe,它通过一个 HTTPS 连接安全地将支付信息发送到 Stripe。避免将 Payment Element 放在另一个 iframe 中,因为有些支付方式需要重定向到另一个页面进行付款确认。 如果您选择使用 iframe 并希望支持 Apple Pay 或 Google Pay,则必须将 iframe 的 [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) 属性设置为`"payment *"`。 结账页面地址必须以 `https://` rather 开头,而非 `http://` for,您的集成才能正常工作。您可以在不使用 HTTPS 的情况下测试集成,但在准备接收真实付款时,请务必[启用 HTTPS](https://docs.stripe.com/security/guide.md#tls)。 #### HTML + JS ### 设置 Stripe.js Payment Element 自动可以获取,这是 Stripe.js 的功能。在您的结账页面包含 Stripe.js 脚本,方法是将它添加到您的 HTML 文件的 `head` 部分。为保持 PCI 合规,始终从 js.stripe.com 加载 Stripe.js。不要把脚本打包或自行保留副本。 ```html Checkout ``` 用下面的 JavaScript 在您的结账页面创建一个 Stripe 实例: ```javascript // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` ### 将 Payment Element 添加到您的支付页面 Payment Element 需要存在于您的支付页面的某个地方。用您的支付表单中的唯一 ID 创建一个空的 DOM 节点(容器): ```html
``` 加载了之前的表单后,创建一个 Payment Element 实例,并将它放入容器的 DOM 节点。创建 [Elements](https://docs.stripe.com/js/elements_object/create) 实例时,将上一步的 [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) 传入 `options`: 认真处理客户端私钥,因为它会完成收款。不要记录它,而是把它嵌入到 URL,或显示给除客户以外的所有人。 ```javascript const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options); // Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement on mount: // // linkAuthenticationElement.mount("#link-authentication-element", { // defaultValues: { // email: 'jenny.rosen@example.com', // } // }) // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### React ### 设置 Stripe.js 从 npm 公共注册表安装 [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) 和 [Stripe.js 加载器](https://www.npmjs.com/package/@stripe/stripe-js): ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### 向您的支付页面添加并配置 Elements 提供程序 要使用 Payment Element 组件,请将您的结账页面组件包裹在 [Elements 提供程序](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider)中。用您的公钥调用 `loadStripe`,并将返回的 `Promise` 传递到 `Elements` 提供程序。另外,将来自上一步的 [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) 作为 `options` 传递到 `Elements` 提供程序。 ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const options = { // passing the client secret obtained in step 3 clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### 添加 Payment Element 组件 用 `PaymentElement` 组件构建您的表单。 ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { return (
// Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement // // ); }; export default CheckoutForm; ``` ## Submit the payment to Stripe [Client-side] 使用 [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment),用来自 Payment Element 的详情完成付款。为该函数提供一个 [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url),告诉 Stripe 在用户完成付款后将他们重定向到哪里。您的用户可能会先被重定向到一个中间站点,如银行授权页面,然后才被重定向到 `return_url`。付款成功时,银行卡付款将立即重定向到 `return_url`。 #### HTML + JS ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React 从您的支付表单组件调用 [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) 时,使用 [useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) 和 [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook) 钩子。 如果您不想用 hooks,而是想使用传统的类组件 (Class Components),则可以使用 [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer)。 ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ); }; export default CheckoutForm; ``` 确保 `return_url` 对应于您网站上显示付款状态的一个页面。Stripe 将客户重定向到 `return_url` 时,我们会提供以下 URL 查询参数。 | 参数 | 描述 | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | `PaymentIntent` 的唯一标识符。 | | `payment_intent_client_secret` | `PaymentIntent` 对象的 [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 | > 如果您有可以用来跟踪客户浏览器会话的工具,则您可能需要将 `stripe.com` 域名添加到推荐人列表。重定向会导致一些工具创建新的会话,从而阻止您跟踪完整的会话。 用以下某个查询参数检索 PaymentIntent。检查 [PaymentIntent 的状态](https://docs.stripe.com/payments/paymentintents/lifecycle.md),以决定向客户显示的内容。您还可以在提供 `return_url` 时附加自己的查询参数,它们会在重定向过程中持续存在。 #### HTML + JS ```javascript // Initialize Stripe.js using your publishable key const stripe = Stripe('<>'); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } }); ``` #### React ```jsx import React, {useState, useEffect} from 'react'; import {useStripe} from '@stripe/react-stripe-js'; const PaymentStatus = () => { const stripe = useStripe(); const [message, setMessage] = useState(null); useEffect(() => { if (!stripe) { return; } // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe .retrievePaymentIntent(clientSecret) .then(({paymentIntent}) => { // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': setMessage('Success! Payment received.'); break; case 'processing': setMessage("Payment processing. We'll update you when payment is received."); break; case 'requires_payment_method': // Redirect your user back to your payment page to attempt collecting // payment again setMessage('Payment failed. Please try another payment method.'); break; default: setMessage('Something went wrong.'); break; } }); }, [stripe]); return message; }; export default PaymentStatus; ``` ## Redirect and authenticate transactions Customers can authenticate MobilePay transactions with mobile or desktop apps. The client that the customer uses determines the authentication method after calling `confirmPayment`. #### Mobile app authentication After you call `confirmPayment`, Stripe redirects your customers to MobilePay to approve or decline the payment. After your customers authorize the payment, the page redirects them to the Payment Intent’s `return_url`. Stripe adds `payment_intent`, `payment_intent_client_secret`, `redirect_pm_type`, and `redirect_status` as URL query parameters (along with any existing query parameters in the `return_url`). An authentication session expires after 5 minutes, and the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, your customer sees a payment error and must restart the payment process. #### Desktop web app authentication After you call `confirmPayment`, Stripe redirects your customers to a MobilePay-hosted page where they can input the phone number associated with their MobilePay account. This sends a push notification to their MobilePay app for payment authentication. After your customer successfully authenticates the payment, the page redirect them back to the `return_url`. If you prefer not to redirect customers on the web after payment, pass `redirect: if_required` to the Payment Element. An authentication session expires after 5 minutes, and the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, your customer sees a payment error and must restart the payment process. ## Handle post-payment events 付款完成时,Stripe 会发送一个 [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) 事件。使用管理平台、自定义 *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 或一个合作伙伴方案来接收这些事件并运行操作,例如,向客户发送订单确认邮件、在数据库中记录订单,或启动配送流程。 侦听这些事件,而不是等待客户端的回调。在客户端上,客户可以在执行回调之前关闭浏览器窗口或退出应用程序,而且恶意客户端可以操纵响应。将集成设置为侦听异步事件还有助于您在未来接受更多支付方式。了解[所有受支持的支付方式之间的差异](https://stripe.com/payments/payment-methods-guide)。 - **在管理平台中手动处理事件** [在管理平台中查看测试支付情况](https://dashboard.stripe.com/test/payments),发送邮件收据,处理提现事宜,或重试失败的付款。 - **创建自定义 Webhook** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Test the integration #### Mobile web app testing To test your integration, choose MobilePay as the payment method and tap **Pay**. In a testing environment, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the MobilePay mobile application, where you can approve or decline the payment. #### Desktop web app testing To test your integration in a testing environment, it redirects you to a test payment page where you can approve or decline the test payment. In live mode, enter the phone number linked to MobilePay to send a push notification to your MobilePay mobile application. You can approve or decline the payment in the MobilePay mobile application. ## Optional: Authorize a payment and then capture later MobilePay supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). ### 告诉 Stripe 仅授权 To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s card linked to MobilePay. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d capture_method=manual \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` After the authorization is successful, Stripe sends a [payment_intent.amount_capturable_updated](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.amount_capturable_updated) event. See [Events](https://docs.stripe.com/api/events.md) to learn more. ### 捕获资金 After the authorization succeeds, the PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture` and you can [capture](https://docs.stripe.com/api/payment_intents/capture.md) the authorized funds. Stripe only support manual captures of the full amount. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/capture \ -u "<>:" \ -d amount_to_capture=1099 ``` ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # 直接收款 API > This is a 直接收款 API for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=direct-api. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. ## Set up Stripe [Server-side] First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register). Use our official libraries for access to the Stripe API from your application: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Create a PaymentIntent [Server-side] A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect a payment from a customer and tracks the lifecycle of the payment process through each stage. Create a `PaymentIntent` on your server and specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). If you already have an integration using the [Payment Intents API](https://docs.stripe.com/payments/payment-intents.md), add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types). ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` ### Example response ```json { "id": "pi_12345", "amount": 1099, "client_secret": "pi_12345_secret_abcdef", "currency": "dkk", "payment_method": "pm_12345", "payment_method_types": [ "mobilepay" ], "status": "requires_confirmation" } ``` ### 检索客户端私钥 PaymentIntent 中包含的是一个*客户端私钥* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)),用于在客户端安全地完成支付流程。有不同的方法可以将客户端私钥传递到客户端。 #### 单页应用 使用浏览器的 `fetch` 功能,从您的服务器上的端点获取客户端私钥。如果您的客户端是单页应用,特别是用现代的前端框架(例如 React)搭建的情况,则该方法最为合适。创建服务于客户端私钥的服务器端点: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` 然后在客户端用 JavaScript 获取客户端私钥: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### 服务端呈现 从服务器将客户端私钥传递到客户端。如果在将静态内容发送到浏览器之前,您的应用程序会在服务器上生成静态内容,则此种方法最有效。 在您的结账表单中添加 [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。在您的服务器代码中,从 PaymentIntent 检索客户端密钥: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## Confirm the PaymentIntent Use the PaymentIntent [ID](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-id) from [step 2](https://docs.stripe.com/payments/mobilepay/accept-a-payment.md#create-payment-intent) to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent. This declares that the customer intends to pay with the specified *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs). Stripe initiates a payment after confirming the PaymentIntent. The [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) indicates where Stripe redirects the customer after they complete the payment. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/confirm \ -u "<>:" \ --data-urlencode "return_url=https://example.com/checkout/complete" ``` ### Example response ```json { "id": "pi_12345", "amount": 1099, "currency": "dkk", "payment_method": "pm_12345", "next_action": { "redirect_to_url": { "return_url": "https://example.com/checkout/complete", "url": "https://pm-redirects.stripe.com/authorize/acct_123/pa_nonce_abc" }, "type": "redirect_to_url" }, "payment_method_types": [ "mobilepay" ], "status": "requires_action" } ``` To authorize the payment, redirect your customer to the URL in the [next_action[redirect_to_url][url]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-redirect_to_url-url) field. - On desktop, the URL opens a MobilePay landing page where the customer can enter their phone number, which identifies their MobilePay account. They can then use the MobilePay smartphone app to proceed with payment authorization. - On mobile devices, the URL opens the MobilePay application directly (if present) or directs to the MobilePay landing page, similar to the desktop process. Your customer has 5 minutes to open the redirect URL and authorize the payment in the MobilePay app. If the underlying card charge fails, your customer can choose a different card and retry in the MobilePay app. If the payment isn’t authorized within 5 minutes, the payment fails and the PaymentIntent’s status transitions to `requires_payment_method`. ## Handle post-payment events 付款完成时,Stripe 会发送一个 [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) 事件。使用管理平台、自定义 *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 或一个合作伙伴方案来接收这些事件并运行操作,例如,向客户发送订单确认邮件、在数据库中记录订单,或启动配送流程。 侦听这些事件,而不是等待客户端的回调。在客户端上,客户可以在执行回调之前关闭浏览器窗口或退出应用程序,而且恶意客户端可以操纵响应。将集成设置为侦听异步事件还有助于您在未来接受更多支付方式。了解[所有受支持的支付方式之间的差异](https://stripe.com/payments/payment-methods-guide)。 - **在管理平台中手动处理事件** [在管理平台中查看测试支付情况](https://dashboard.stripe.com/test/payments),发送邮件收据,处理提现事宜,或重试失败的付款。 - **创建自定义 Webhook** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Test the integration Using your [test API keys](https://docs.stripe.com/keys.md#test-live-modes), create a PaymentIntent. After confirming the PaymentIntent, follow the `next_action` redirect URL to a test page with options to authorize or fail the payment. - Click **Authorize test payment** to test the case when the payment is successful. The PaymentIntent transitions from `requires_action` to `succeeded`. - Click **Fail test payment** to test the case when the customer fails to authenticate. The PaymentIntent transitions from `requires_action` to `requires_payment_method`. ## Optional: Authorize a payment and then capture later MobilePay supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). ### 告诉 Stripe 仅授权 To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s card linked to MobilePay. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d capture_method=manual \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` After the authorization is successful, Stripe sends a [payment_intent.amount_capturable_updated](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.amount_capturable_updated) event. See [Events](https://docs.stripe.com/api/events.md) to learn more. ### 捕获资金 After the authorization succeeds, the PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture` and you can [capture](https://docs.stripe.com/api/payment_intents/capture.md) the authorized funds. Stripe only support manual captures of the full amount. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/capture \ -u "<>:" \ -d amount_to_capture=1099 ``` ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # iOS > This is a iOS for when payment-ui is mobile and platform is ios. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=mobile&platform=ios. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. Stripe recommends using the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios), an embeddable payment form, to add MobilePay and other payment methods to your integration with the least amount of effort. This guide covers how to accept MobilePay from your native mobile application using your own custom payment form. Your native mobile application redirects your customer to the MobilePay mobile application to complete the payment. Completing the purchase requires no additional action in the MobilePay mobile application. ## 设置 Stripe [服务器端] [客户端] 首先,您需要有 Stripe 账户。[立即注册](https://dashboard.stripe.com/register)。 ### 服务器端 该集成要求您的服务器上的端点与 Stripe API 通讯。请用官方库从您的服务器访问 Stripe API: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ### 客户端 [Stripe iOS SDK](https://github.com/stripe/stripe-ios) 是开源的,[有完整的文档](https://stripe.dev/stripe-ios/index.html),并且与支持 iOS 13 或更高版本操作系统的应用程序兼容。 #### Swift Package Manager 要安装 SDK,按这些步骤进行: 1. 在 Xcode 中,选择**文件** > **添加工具包依赖…**并输入 `https://github.com/stripe/stripe-ios-spm` 作为仓库 URL。 1. 从我们的[发布页面](https://github.com/stripe/stripe-ios/releases)选择最新的版本号。 1. 将 **StripePaymentsUI** 产品添加到[您的目标应用程序](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)。 #### CocoaPods 1. 如果您还没有[CocoaPods](https://guides.cocoapods.org/using/getting-started.html),请安装其最新版本。 1. 如果您目前没有 [Podfile](https://guides.cocoapods.org/syntax/podfile.html),请运行以下命令创建一个: ```bash pod init ``` 1. 将这一行代码添加到您的 `Podfile`: ```podfile pod 'StripePaymentsUI' ``` 1. 运行以下命令: ```bash pod install ``` 1. 今后,一定记得用 `.xcworkspace` 文件来打开您在 Xcode 中的项目,不要使用 `.xcodeproj` 文件。 1. 将来,要更新到 SDK 的最新版本,运行: ```bash pod update StripePaymentsUI ``` #### Carthage 1. 如果您还没有[Carthage](https://github.com/Carthage/Carthage#installing-carthage),请安装其最新版本。 1. 将这一行代码添加到您的 `Cartfile`。 ```cartfile github "stripe/stripe-ios" ``` 1. 按照 [Carthage 安装说明](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos)进行。确保嵌入[这里](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking)所列的所有必要框架。 1. 将来,要更新到 SDK 的最新版本,运行以下命令即可: ```bash carthage update stripe-ios --platform ios ``` #### 手动框架 1. 前往我们的 [GitHub 发布页面](https://github.com/stripe/stripe-ios/releases/latest),下载并解压缩 **Stripe.xcframework.zip**。 1. 将 **StripePaymentsUI.xcframework** 拖拽到您的 Xcode 项目中 **General**(常规)设置的 **Embedded Binaries**(嵌入式二进制文件)部分。一定要选择 **Copy items if needed**(需要时复制项目)。 1. 为[这里](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking)所列的所有必要框架重复第 2 步。 1. 将来,要更新到 SDK 的最新版本,重复第 1-3 步。 > 有关最新 SDK 发布及过往版本的详细信息,请查看 GitHub 上的[发布](https://github.com/stripe/stripe-ios/releases)页面。要想在新版本发布时接收通知,请[查看仓库的发布](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository)。 在应用程序启动时使用您的 Stripe [公钥](https://dashboard.stripe.com/test/apikeys) 配置 SDK。这样可使您的应用程序向 Stripe API 发出请求。 #### Swift ```swift import UIKitimportStripePaymentsUI @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {StripeAPI.defaultPublishableKey = "<>" // do any other necessary launch configuration return true } } ``` > 测试时使用您的[测试密钥](https://docs.stripe.com/keys.md#obtain-api-keys),发布应用时使用[真实模式](https://docs.stripe.com/keys.md#test-live-modes)密钥。 ## Create a PaymentIntent [Server-side] [Client-side] ### Server-side A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). - Add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) for your `PaymentIntent`. Make sure that you enable MobilePay in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). - Set `payment_method_data[type]` to `mobilepay` to create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` The PaymentIntent includes a *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)). Send the client secret to the client to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent in the next step. ### Client-side On the client, request a PaymentIntent from your server and store its client secret. #### Swift ```swift class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? // ...continued from previous step override func viewDidLoad() { // ...continued from previous step startCheckout() } func startCheckout() { // Request a PaymentIntent from your server and store its client secret // Click View full sample to see a complete implementation } } ``` ## Submit the payment to Stripe [Client-side] When a customer taps to pay with MobilePay, confirm the `PaymentIntent` to complete the payment. Configure an `STPPaymentIntentParams` object with the `PaymentIntent` [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). The client secret is different from your API keys that authenticate Stripe API requests. Handle it carefully because it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. ### Set up a return URL 客户可能会离开您的应用来验证(例如,去 Safari 或他们的网银应用)。若允许他们在验证后自动返回到您的应用,[配置一个自定义页面内跳转协议 (URL Scheme)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app),并设置您的应用程序代理将 URL 转发到 SDK。Stripe 不支持[通用链接](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content)。 #### SceneDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } let stripeHandled = StripeAPI.handleURLCallback(with: url) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } ``` #### AppDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } return false } ``` #### SwiftUI #### Swift ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!").onOpenURL { incomingURL in let stripeHandled = StripeAPI.handleURLCallback(with: incomingURL) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } } } } ``` ### Confirm the payment Use the PaymentIntent client secret from [step 2](https://docs.stripe.com/payments/mobilepay/accept-a-payment.md#create-payment-intent) to confirm the PaymentIntent using [STPPaymentHandler.shared.confirmPayment()](https://stripe.dev/stripe-ios/stripepayments/documentation/stripepayments/stppaymenthandler/confirmpayment\(_:with:completion:\)). This opens the MobilePay application directly (if present) or a webview showing the MobilePay landing page. After the customer authorizes the payment, the completion block contains the status of the payment. #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) paymentIntentParams.paymentMethodParams = STPPaymentMethodParams( mobilePay: STPPaymentMethodMobilePayParams(), billingDetails: nil, metadata: nil ) paymentIntentParams.returnURL = "your-app://stripe-redirect" // Set returnURL to your app's return URL that you set up in the previous step STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (handlerStatus, paymentIntent, error) in switch handlerStatus { case .succeeded: // Payment succeeded // ... case .canceled: // Payment canceled // ... case .failed: // Payment failed // ... @unknown default: fatalError() } } ``` Your customer has 5 minutes to authorize the payment in the MobilePay app. If the underlying card charge fails, your customer can choose a different card and retry in the MobilePay app. ## Handle post-payment events 付款完成时,Stripe 会发送一个 [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) 事件。使用管理平台、自定义 *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 或一个合作伙伴方案来接收这些事件并运行操作,例如,向客户发送订单确认邮件、在数据库中记录订单,或启动配送流程。 侦听这些事件,而不是等待客户端的回调。在客户端上,客户可以在执行回调之前关闭浏览器窗口或退出应用程序,而且恶意客户端可以操纵响应。将集成设置为侦听异步事件还有助于您在未来接受更多支付方式。了解[所有受支持的支付方式之间的差异](https://stripe.com/payments/payment-methods-guide)。 - **在管理平台中手动处理事件** [在管理平台中查看测试支付情况](https://dashboard.stripe.com/test/payments),发送邮件收据,处理提现事宜,或重试失败的付款。 - **创建自定义 Webhook** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Test the integration Use your [test API keys](https://docs.stripe.com/keys.md#test-live-modes) to create a PaymentIntent. After confirming the PaymentIntent, follow the `next_action` redirect URL to a test page with options to authorize or fail the payment. - Click **Authorize test payment** to test the case when the payment is successful. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `succeeded`. - Click **Fail test payment** to test the case when the customer fails to authenticate. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `requires_payment_method`. ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # Android > This is a Android for when payment-ui is mobile and platform is android. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=mobile&platform=android. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. Stripe recommends using the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android), an embeddable payment form, to add MobilePay and other payment methods to your integration with the least amount of effort. This guide covers how to accept MobilePay from your native mobile application using your own custom payment form. Your native mobile application redirects your customer to the MobilePay mobile application to complete the payment. Completing the purchase requires no additional action in the MobilePay mobile application. ## 设置 Stripe [服务器端] [客户端] 首先,您需要有 Stripe 账户。[立即注册](https://dashboard.stripe.com/register)。 ### 服务器端 该集成要求您的服务器上的端点与 Stripe API 通讯。请用官方库从您的服务器访问 Stripe API: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ### 客户端 [Stripe Android SDK](https://github.com/stripe/stripe-android) 是开源的,且[有完整的文档](https://stripe.dev/stripe-android/)。 安装 SDK 时,将 `stripe-android` 添加到您的 [app/build.gradle](https://developer.android.com/studio/build/dependencies) 文件的 `dependencies` 块中: #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Stripe Android SDK implementation("com.stripe:stripe-android:23.3.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.3.0") } ``` > 有关最新 SDK 发布及过往版本的详细信息,请查看 GitHub 上的[发布](https://github.com/stripe/stripe-android/releases)页面。要想在新版本发布时接收通知,请[查看仓库的发布情况](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)。 用您的 Stripe [公钥](https://dashboard.stripe.com/apikeys)配置 SDK,以便它可以向 Stripe API 发送请求,例如在您的 `Application` 子类中: #### Kotlin ```kotlin import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "<>" ) } } ``` > 测试时使用您的[测试密钥](https://docs.stripe.com/keys.md#obtain-api-keys),发布应用时使用[真实模式](https://docs.stripe.com/keys.md#test-live-modes)密钥。 Stripe 的示例还用 [OkHttp](https://github.com/square/okhttp) 和 [GSON](https://github.com/google/gson) 向服务器发送了 HTTP 请求。 ## Create a PaymentIntent [Server-side] [Client-side] ### Server-side A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). - Add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types). Make sure that you enable MobilePay in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). - Set `payment_method_data[type]` to `mobilepay` to create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` The PaymentIntent includes a *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)). Send the client secret to the client to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent in the next step. ### Client-side On the client, request a PaymentIntent from your server and store its client secret. #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click View full sample to see a complete implementation } } ``` ## Submit the payment to Stripe [Client-side] When a customer taps to pay with MobilePay, confirm the `PaymentIntent` to complete the payment. Configure a `ConfirmPaymentIntentParams` object with the `PaymentIntent` [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). The client secret is different from your API keys that authenticate Stripe API requests. Handle it carefully because it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. ### Confirm the payment Use the PaymentIntent client secret from [step 2](https://docs.stripe.com/payments/mobilepay/accept-a-payment.md#create-payment-intent) to confirm the PaymentIntent using [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/index.html#74063765%2FFunctions%2F-1622557690). This opens the MobilePay application directly (if present) or a webview showing the MobilePay landing page. After the customer authorizes the payment, `onPaymentResult` contains the status of the payment. #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private val paymentLauncher: PaymentLauncher by lazy { PaymentLauncher.create( this, PaymentConfiguration.getInstance(applicationContext).publishableKey, PaymentConfiguration.getInstance(applicationContext).stripeAccountId, ::onPaymentResult ) } private fun startCheckout() { // ... val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = PaymentMethodCreateParams.createMobilePay(), clientSecret = paymentIntentClientSecret ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { val message = when (paymentResult) { is PaymentResult.Completed -> { "Completed!" } is PaymentResult.Canceled -> { "Canceled!" } is PaymentResult.Failed -> { // This string comes from the PaymentIntent's error message. // See: https://docs.stripe.com/api/payment_intents/object#payment_intent_object-last_payment_error-message "Failed: " + paymentResult.throwable.message } } } } ``` Your customer has 5 minutes to authorize the payment in the MobilePay app. If the underlying card charge fails, your customer can choose a different card and retry in the MobilePay app. ## Handle post-payment events 付款完成时,Stripe 会发送一个 [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) 事件。使用管理平台、自定义 *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 或一个合作伙伴方案来接收这些事件并运行操作,例如,向客户发送订单确认邮件、在数据库中记录订单,或启动配送流程。 侦听这些事件,而不是等待客户端的回调。在客户端上,客户可以在执行回调之前关闭浏览器窗口或退出应用程序,而且恶意客户端可以操纵响应。将集成设置为侦听异步事件还有助于您在未来接受更多支付方式。了解[所有受支持的支付方式之间的差异](https://stripe.com/payments/payment-methods-guide)。 - **在管理平台中手动处理事件** [在管理平台中查看测试支付情况](https://dashboard.stripe.com/test/payments),发送邮件收据,处理提现事宜,或重试失败的付款。 - **创建自定义 Webhook** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Test the integration Use your [test API keys](https://docs.stripe.com/keys.md#test-live-modes) to create a PaymentIntent. After confirming the PaymentIntent, follow the `next_action` redirect URL to a test page with options to authorize or fail the payment. - Click **Authorize test payment** to test the case when the payment is successful. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `succeeded`. - Click **Fail test payment** to test the case when the customer fails to authenticate. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `requires_payment_method`. ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # React Native > This is a React Native for when payment-ui is mobile and platform is react-native. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=mobile&platform=react-native. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. Stripe recommends using the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=react-native), an embeddable payment form, to add MobilePay and other payment methods to your integration with the least amount of effort. This guide covers how to accept MobilePay from your native mobile application using your own custom payment form. Your native mobile application redirects your customer to a webview to complete the payment on MobilePay. ## Set up Stripe [Server-side] [Client-side] First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register). ### Server-side This integration requires endpoints on your server that talk to the Stripe API. Use the official libraries for access to the Stripe API from your server: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ### Client-side [React Native SDK](https://github.com/stripe/stripe-react-native) 是开源的,有完整的文档。在内部,它利用的是[原生 iOS](https://github.com/stripe/stripe-ios) 和 [Android](https://github.com/stripe/stripe-android) SDK。要安装 Stripe 的 React Native SDK,在您的项目目录中运行以下某个指令(取决于您使用的软件包管理器)。 #### yarn ```bash yarn add @stripe/stripe-react-native ``` #### npm ```bash npm install @stripe/stripe-react-native ``` 然后,安装一些其他必要的依赖项: - 对于 iOS,请转到 **ios** 目录并运行 `pod install` 以确保同时安装了所需的本地依赖项。 - 对于 Android,无需安装其他依赖项。 > 建议按照[官方 TypeScript 指南](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project)添加 TypeScript 支持。 ### Stripe 初始化 要在您的 React Native 应用中初始化 Stripe,使用 `StripeProvider` 组件包裹您的支付界面,或者使用 `initStripe` 初始化方法。只需要 `publishableKey` 中的 API [公钥](https://docs.stripe.com/keys.md#obtain-api-keys)。下例显示的是用 `StripeProvider` 组件初始化 Stripe 的方式。 ```jsx import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( {/* Your app code here */} ); } ``` > 测试与开发时使用 API [测试模式](https://docs.stripe.com/keys.md#obtain-api-keys),发布时使用[真实模式](https://docs.stripe.com/keys.md#test-live-modes)密钥。 ## Create a PaymentIntent [Server-side] [Client-side] ### Server-side A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). - Add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types). Make sure that you enable MobilePay in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` The PaymentIntent includes a *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)). Send the client secret to the client to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent in the next step. ### Client-side On the client, request a PaymentIntent from your server and store its client secret: ```javascript function PaymentScreen() { const fetchPaymentIntentClientSecret = async () => { const response = await fetch(`${API_URL}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ currency: 'dkk', }), }); const {clientSecret} = await response.json(); return clientSecret; }; const handlePayPress = async () => { // See below }; return (