# BLIK 支付 Learn how to accept BLIK, a common payment method in Poland. # Checkout > 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 集成中手动配置支付方式。 BLIK is a [single use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method that requires customers to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. The bank sends a push notification to your customer’s mobile phone asking to authorize the payment inside their banking application. The BLIK code is valid for 2 minutes; customers have 60 seconds to authorize the payment after starting a payment. After 60 seconds, it times out and they must request a new BLIK code. Customers typically approve BLIK payments in less than 10 seconds. ## 确定兼容性 **支持的商家所在地**:AT, AU, BE, BG, CA, CH, CY, CZ, DE, DK, EE, ES, FI, FR, GB, GR, HR, HU, IE, IS, IT, LI, LT, LU, LV, MT, NL, NO, PL, PT, RO, SE, SG, SI, SK, US **支持的货币**:`pln` **展示货币**:`pln` **支付模式**:Yes **设置模式**:Not yet **订阅模式**:Not yet A Checkout Session must satisfy all of the following conditions to support BLIK 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 Złoty (currency code `pln`). ## 收款 > This guide builds on the foundational [accept a payment](https://docs.stripe.com/payments/accept-a-payment.md?ui=stripe-hosted) Checkout integration. This guides you through enabling BLIK and shows the differences between accepting payments using dynamic payment methods and manually configuring payment methods. ### Enable BLIK as a payment method 创建新的 [Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) 时,您需要: 1. Add `blik` to the list of `payment_method_types`. 1. Make sure all your `line_items` use the `pln` currency. #### Stripe 托管页面 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=pln" \ -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]=blik" \ --data-urlencode "success_url=https://example.com/success" ``` #### Full embedded page ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=pln" \ -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]=blik" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` #### Elements ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=pln" \ -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]=blik" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=elements ``` ### What customers see Inside their Banking app, customers see four lines related to each BLIK transaction: - If you provided a value for [payment_intent_data.description](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-description), the first two lines display it (max 70 characters). - If you provided a value for [payment_intent_data.statement_descriptor](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-statement_descriptor) (typically, an order ID), line 3 displays it (max 22 characters). - The fourth line automatically populates with the URL of your website. ### 履行订单 接受付款后,学习如何[履行订单](https://docs.stripe.com/checkout/fulfillment.md)。 ## 测试您的集成 When testing your Checkout integration, select BLIK as the payment method and click the **Pay** button. Use a *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes) to test a successful payment by entering any 6-digit code (such as `123456`) in the payment form. ## 处理退款和争议 The refund period for BLIK is up to 13 months after the original payment. Customers can dispute a payment through their bank up to 13 months after the original payment. There’s no appeal process. Learn more about [BLIK disputes](https://docs.stripe.com/payments/blik.md#disputed-payments). ## Optional: Simulate failures in a sandbox BLIK payments can fail for different reasons. There are immediate failures (for example, the code is expired or invalid), delayed errors (the bank declines) or timeouts (the customer didn’t respond in time). You can simulate each failure scenarios by passing `email` values matching certain patterns (documented below) when creating the `PaymentIntent`, as part of the [billing details](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_data-billing_details), with any 6-digit as BLIK code. You can enter the `email` in the contact information section of the Checkout page. ### Immediate Failures | 失败代码 | 解释 | Email pattern | | ---------------------------------- | ------------------------------------- | ------------------- | | `payment_method_invalid_parameter` | 传递的代码不是一个有效的 BLIK 代码。 | `.*invalid_code@.*` | | `payment_method_invalid_parameter` | 传递的代码过期了。BLIK 代码 2 分钟后过期,请向客户请求另一个代码。 | `.*expired_code@.*` | ### Declines (8 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | ------------------------ | ------------------------- | | `payment_method_provider_decline` | 付款被拒绝了,原因是达到了该银行账户的支付限额。 | `.*limit_exceeded@.*` | | `payment_method_provider_decline` | 银行账户资金不足,无法完成购买。 | `.*insufficient_funds@.*` | | `payment_method_provider_decline` | 客户拒绝了这笔付款。 | `.*customer_declined@.*` | | `payment_method_provider_decline` | 付款被客户的银行拒绝了,原因未知。 | `.*bank_declined@.*` | | `payment_method_provider_decline` | 付款被拒绝,原因未知。 | `.*blik_declined@.*` | ### Timeouts (60 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | -------------------- | ----------------------- | | `payment_method_provider_timeout` | 客户未在分配的 60 秒内批准该笔付款。 | `.*customer_timeout@.*` | | `payment_method_provider_timeout` | 向客户的银行发出的请求超时了。 | `.*bank_timeout@.*` | | `payment_method_provider_timeout` | 向 BLIK 网络发出的请求超时了。 | `.*blik_timeout@.*` | ## See also - [More about BLIK](https://docs.stripe.com/payments/blik.md) - [Checkout fulfillment](https://docs.stripe.com/checkout/fulfillment.md) - [Customizing Checkout](https://docs.stripe.com/payments/checkout/customization.md) # 直接收款 API > We recommend that you follow the [Accept a payment](https://docs.stripe.com/payments/accept-a-payment.md) guide unless you need to use manual server-side confirmation, or your integration requires presenting payment methods separately. If you’ve already integrated with Elements, see the [Payment Element migration guide](https://docs.stripe.com/payments/payment-element/migration.md). BLIK is a [single use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method that requires customers to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. The bank sends a push notification to your customer’s mobile phone asking to authorize the payment inside their banking application. The BLIK code is valid for 2 minutes; customers have 60 seconds to authorize the payment after starting a payment. After 60 seconds, it times out and they must request a new BLIK code. Customers typically approve BLIK payments in less than 10 seconds. ## 设置 Stripe [服务器端] 首先,您需要有 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' ``` ## 创建 PaymentIntent [服务器端] 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. First, create a `PaymentIntent` on your server and specify the amount to collect and the `pln` currency, because BLIK only supports `pln`. If you already have an integration using the [Payment Intents API](https://docs.stripe.com/payments/payment-intents.md), add `blik` 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`. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=pln \ -d "payment_method_types[]=blik" \ --data-urlencode "description=A description of what you're selling" \ -d statement_descriptor=ORDER_123 ``` ### 检索客户端私钥 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 ``` ## 收集支付方式详情 [客户端] To submit the payment to Stripe, you need to confirm the PaymentIntent with your customer’s 6-digit BLIK code. You can get this code by creating a form on your client to collect the required code from the customer. #### HTML + JS ```html
``` #### React #### npm Install [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) and the [Stripe.js loader](https://www.npmjs.com/package/@stripe/stripe-js) from the npm public registry. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` #### umd We also provide a UMD build for sites that don’t use npm or modules. Include the Stripe.js script, which exports a global `Stripe` function, and the UMD build of React Stripe.js, which exports a global `ReactStripe` object. Always load the Stripe.js script directly from **js.stripe.com** to remain PCI compliant. Don’t include the script in a bundle or host a copy of it yourself. ```html ``` > 可通过 [CodeSandbox 内的演示](https://codesandbox.io/s/react-stripe-official-q1loc?fontsize=14&hidenavigation=1&theme=dark)尝试 React Stripe.js,不需要新建项目。 ### 在您的页面添加 Stripe.js 和 Elements To integrate Stripe.js and (optionally) use Elements components for other payment methods, wrap the root of your React app in an [Elements provider](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider). Call `loadStripe` with your publishable key and pass the returned `Promise` to the `Elements` provider. ```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() { return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Create a form to accept payments If you intend to use the [useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) hook to access Stripe.js features, you can create a normal React component. If you prefer traditional class components over hooks, you can instead use an [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). #### Hooks ```jsx import React from 'react'; import {useStripe} from '@stripe/react-stripe-js'; export default function CheckoutForm() { return (
); } ``` #### Class Components ```jsx import React from 'react'; import {ElementsConsumer} from '@stripe/react-stripe-js'; class CheckoutForm extends React.Component { render() { const {stripe} = this.props; return (
); } } export default function InjectedCheckoutForm() { return ( {({stripe, elements}) => ( )} ); } ``` ## 向 Stripe 提交付款 [客户端] Use the PaymentIntent object from [step 2](https://docs.stripe.com/payments/blik/accept-a-payment.md#web-create-payment-intent) and the 6-digit BLIK code you collected in [step 3](https://docs.stripe.com/payments/blik/accept-a-payment.md#web-collect-payment-method-details) 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). After the PaymentIntent is confirmed, it initiates a payment. Rather than sending the entire PaymentIntent object to the client, use its [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). This client secret is different from your API keys that authenticate Stripe API requests. Handle the client secret carefully, because it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. Also, because the 6-digit BLIK code is only valid for 2 minutes, you can only pass it into the payment method options when confirming the PaymentIntent. In a *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes), any 6-digit code works. #### HTML + JS 客户通过 Blik 点击支付时,用 Stripe.js 向 Stripe 提交付款。[Stripe.js](https://docs.stripe.com/payments/elements.md) 是构建支付流程的基础 JavaScript 库。它会自动处理一些复杂操作,例如下面的重定向,使您能够将集成扩展到其他支付方式。在您的结账页面包含 Stripe.js 脚本,方法是将它添加到您的 HTML 文件的 `head` 部分。 ```html Checkout ``` 用下面的 JavaScript 在您的结账页面创建一个 Stripe.js 实例。 ```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('<>'); ``` Use [stripe.confirmBlikPayment](https://docs.stripe.com/js/payment_intents/confirm_blik_payment) to confirm the payment. `confirmBlikPayment` doesn’t return until the confirmation succeeds or fails. If you want to implement your own logic to update payment status, you can disable Stripe.js polling of the API by setting the `handleActions` parameter to `false`. ```javascript const form = document.getElementById('payment-form'); const codeInput = document.getElementById('code'); form.addEventListener('submit', (event) => { event.preventDefault(); const {error} = await stripe.confirmBlikPayment( '{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { blik: {}, }, payment_method_options: { blik: { code: code.value, }, }, } ); }); ``` #### React 客户通过 Blik 点击支付时,用 Stripe.js 向 Stripe 提交付款。[Stripe.js](https://docs.stripe.com/payments/elements.md) 是构建支付流程的基础 JavaScript 库。它会自动处理一些复杂操作,例如下面的重定向,使您能够将集成扩展到其他支付方式。在您的结账页面包含 Stripe.js 脚本,方法是将它添加到您的 HTML 文件的 `head` 部分。 ```html Checkout ``` 用下面的 JavaScript 在您的结账页面创建一个 Stripe.js 实例。 ```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('<>'); ``` Use [stripe.confirmBlikPayment](https://docs.stripe.com/js/payment_intents/confirm_blik_payment) to confirm the payment. `confirmBlikPayment` doesn’t return until the confirmation succeeds or fails. You can disable the polling of the API by setting the `handleActions` parameter to `false`. #### Hooks To call `stripe.confirmBlikPayment` from your payment form component, use the [useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) hook. ```jsx import React from 'react'; import {useStripe} from '@stripe/react-stripe-js'; export default function CheckoutForm() { const stripe = useStripe(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } // For brevity, this example is using uncontrolled components for // the code input. In a real world app you will // probably want to use controlled components. // https://reactjs.org/docs/uncontrolled-components.html // https://reactjs.org/docs/forms.html#controlled-components const code = event.target['code']; const {error} = await stripe.confirmBlikPayment('{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { blik: {}, }, payment_method_options: { blik: { code, }, }, }); if (error) { // Show error to your customer. console.log(error.message); } // Otherwise the customer will be redirected away from your // page to complete the payment with their bank. }; return (
); } ``` #### Class Components ```jsx import React from 'react'; import {ElementsConsumer} from '@stripe/react-stripe-js'; class CheckoutForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe} = this.props if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } // For brevity, this example is using uncontrolled components for // the accountholder's name. In a real world app you will // probably want to use controlled components. // https://reactjs.org/docs/uncontrolled-components.html // https://reactjs.org/docs/forms.html#controlled-components const code = event.target['code']; const {error} = await stripe.confirmBlikPayment('{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { blik: {}, }, payment_method_options: { blik: { code, }, }, }); if (error) { // Show error to your customer. console.log(error.message); } // Otherwise the customer will be redirected away from your // page to complete the payment with their bank. }; render() { const {stripe} = this.props; return (
); } } export default function InjectedCheckoutForm() { return ( {({stripe, elements}) => ( )} ); } ``` After confirming the PaymentIntent with valid parameters, the PaymentIntent’s `status` becomes `requires_action`. The `next_action` has the `blik_authorize` type: this means that the next step is completed by your customer, who has 60 seconds to confirm the payment inside their mobile banking app. We recommend showing a timer or a dialog to your customer to prompt them to authorize the payment within the time. ### What customers see Inside their Banking app, customers see four lines related to each BLIK transaction: - If you provided a value for `description` when creating the PaymentIntent, the first two lines display it (max 70 characters). - If you provided a value for `statement_descriptor` (typically, an order ID), line 3 displays it (max 22 characters). - The fourth line automatically populates with the URL of your website. ## 履行订单 [服务器端] [Use a method such as webhooks](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks) to handle order *fulfillment* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected). When a customer completes payment, the `PaymentIntent`’s status transitions to `succeeded` and sends the [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) event. If a customer doesn’t pay, the `PaymentIntent` sends the [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) webhook event and returns to a status of `requires_payment_method`. ## Optional: Simulate failures in a sandbox BLIK payments can fail for different reasons. There are immediate failures (for example, the code is expired or invalid), delayed errors (the bank declines) or timeouts (the customer didn’t respond in time). You can simulate each failure scenarios by passing `email` values matching certain patterns (documented below) when creating the `PaymentIntent`, as part of the [billing details](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_data-billing_details), with any 6-digit as BLIK code. When confirming the `PaymentIntent` server side, a request simulating an invalid BLIK code would look like: #### curl ```bash curl https://api.stripe.com/v1/payment_intents/{{PAYMENT_INTENT_ID}}/confirm \ -u <>: \ -d "payment_method_data[type]"="blik" \ -d "payment_method_options[blik][code]"="{{CODE}}" \ -d "payment_method_data[billing_details][email]"="invalid_code@example.com" ``` ### Immediate Failures | 失败代码 | 解释 | Email pattern | | ---------------------------------- | ------------------------------------- | ------------------- | | `payment_method_invalid_parameter` | 传递的代码不是一个有效的 BLIK 代码。 | `.*invalid_code@.*` | | `payment_method_invalid_parameter` | 传递的代码过期了。BLIK 代码 2 分钟后过期,请向客户请求另一个代码。 | `.*expired_code@.*` | ### Declines (8 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | ------------------------ | ------------------------- | | `payment_method_provider_decline` | 付款被拒绝了,原因是达到了该银行账户的支付限额。 | `.*limit_exceeded@.*` | | `payment_method_provider_decline` | 银行账户资金不足,无法完成购买。 | `.*insufficient_funds@.*` | | `payment_method_provider_decline` | 客户拒绝了这笔付款。 | `.*customer_declined@.*` | | `payment_method_provider_decline` | 付款被客户的银行拒绝了,原因未知。 | `.*bank_declined@.*` | | `payment_method_provider_decline` | 付款被拒绝,原因未知。 | `.*blik_declined@.*` | ### Timeouts (60 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | -------------------- | ----------------------- | | `payment_method_provider_timeout` | 客户未在分配的 60 秒内批准该笔付款。 | `.*customer_timeout@.*` | | `payment_method_provider_timeout` | 向客户的银行发出的请求超时了。 | `.*bank_timeout@.*` | | `payment_method_provider_timeout` | 向 BLIK 网络发出的请求超时了。 | `.*blik_timeout@.*` | # iOS BLIK is a [single use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method that requires customers to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. The bank sends a push notification to your customer’s mobile phone asking to authorize the payment inside their banking application. The BLIK code is valid for 2 minutes; customers have 60 seconds to authorize the payment after starting a payment. After 60 seconds, it times out and they must request a new BLIK code. Customers typically approve BLIK payments in less than 10 seconds. ## 设置 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)密钥。 ## 创建 PaymentIntent [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. ### 服务器端 First, create a `PaymentIntent` on your server and specify the amount to collect and the `pln` currency (BLIK doesn’t support other currencies). Add `blik` 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`. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=pln \ -d "payment_method_types[]=blik" \ --data-urlencode "description=A description of what you're selling" \ -d statement_descriptor=ORDER_123 ``` ### 客户端 在客户端,从您的服务器请求 PaymentIntent 并保存它的客户端私钥。 #### Swift ```swift class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? func startCheckout() { // Request a PaymentIntent from your server and store its client secret } } ``` ## 收集支付方式详情 [客户端] In your app, collect the required 6-digit BLIK code from the customer. Create a [STPConfirmBLIKOptions](https://stripe.dev/stripe-ios/stripe-payments/Classes/STPConfirmBLIKOptions.html) with the BLIK code. #### Swift ```swift let blikOptions = STPConfirmBLIKOptions(code: "777123") ``` ## 向 Stripe 提交付款 [客户端] Retrieve the client secret from the PaymentIntent you created in step 2 and the 6-digit BLIK code you collected in step 3 to call [STPPaymentHandler confirmPayment](https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentHandler.html#/c:@M@StripePayments@objc\(cs\)STPPaymentHandler\(im\)confirmPayment:withAuthenticationContext:completion:). #### Swift ```swift ​​let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) ​​paymentIntentParams.paymentMethodParams = STPPaymentMethodParams( ​​ blik: STPPaymentMethodBLIKParams(), billingDetails: nil, ​​ metadata: nil ​​) let confirmPaymentMethodOptions = STPConfirmPaymentMethodOptions() confirmPaymentMethodOptions.blikOptions = blikOptions paymentIntentParams.paymentMethodOptions = confirmPaymentMethodOptions STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (handlerStatus, paymentIntent, error) in switch handlerStatus { case .succeeded: // Show a timer or a dialog to your customer to prompt them to authorize the payment. // Poll your server or Stripe API for the PaymentIntent status update case .canceled: // Payment was canceled case .failed: // Payment failed @unknown default: fatalError() } } ``` After confirmation with valid parameters, the status of the PaymentIntent becomes `requires_action` and calls the completion block with succeeded handlerStatus. The `next_action` has the `blik_authorize` type: this means that the next step is completed by your customer, who has 60 seconds to confirm the payment inside their mobile banking app. We recommend: - Showing a timer or dialog to your customer to prompt them to authorize the payment - Polling your server or Stripe API for the PaymentIntent status update - Displaying the payment confirmation to your customer as soon as the PaymentIntent status updates to `succeeded` ## Optional: 处理付款后事件 付款完成时,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** [构建自定义 Webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) 处理程序,用于监听事件并创建自定义异步支付流程。使用 Stripe CLI 在本地测试和调试 Webhook 集成。 - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Optional: Simulate failures in a sandbox BLIK payments can fail for different reasons. There are immediate failures (for example, the code is expired or invalid), delayed errors (the bank declines) or timeouts (the customer didn’t respond in time). You can simulate each failure scenarios by passing `email` values matching certain patterns (documented below) when creating the `PaymentIntent`, as part of the [billing details](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_data-billing_details), with any 6-digit as BLIK code. ### Immediate Failures | 失败代码 | 解释 | Email pattern | | ---------------------------------- | ------------------------------------- | ------------------- | | `payment_method_invalid_parameter` | 传递的代码不是一个有效的 BLIK 代码。 | `.*invalid_code@.*` | | `payment_method_invalid_parameter` | 传递的代码过期了。BLIK 代码 2 分钟后过期,请向客户请求另一个代码。 | `.*expired_code@.*` | ### Declines (8 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | ------------------------ | ------------------------- | | `payment_method_provider_decline` | 付款被拒绝了,原因是达到了该银行账户的支付限额。 | `.*limit_exceeded@.*` | | `payment_method_provider_decline` | 银行账户资金不足,无法完成购买。 | `.*insufficient_funds@.*` | | `payment_method_provider_decline` | 客户拒绝了这笔付款。 | `.*customer_declined@.*` | | `payment_method_provider_decline` | 付款被客户的银行拒绝了,原因未知。 | `.*bank_declined@.*` | | `payment_method_provider_decline` | 付款被拒绝,原因未知。 | `.*blik_declined@.*` | ### Timeouts (60 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | -------------------- | ----------------------- | | `payment_method_provider_timeout` | 客户未在分配的 60 秒内批准该笔付款。 | `.*customer_timeout@.*` | | `payment_method_provider_timeout` | 向客户的银行发出的请求超时了。 | `.*bank_timeout@.*` | | `payment_method_provider_timeout` | 向 BLIK 网络发出的请求超时了。 | `.*blik_timeout@.*` | # Android BLIK is a [single use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method that requires customers to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. The bank sends a push notification to your customer’s mobile phone asking to authorize the payment inside their banking application. The BLIK code is valid for 2 minutes; customers have 60 seconds to authorize the payment after starting a payment. After 60 seconds, it times out and they must request a new BLIK code. Customers typically approve BLIK payments in less than 10 seconds. ## 设置 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.9.1") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.9.1") } ``` > 有关最新 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 请求。 ## 创建 PaymentIntent [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. ### 服务器端 First, create a `PaymentIntent` on your server and specify the amount to collect and the `pln` currency (BLIK doesn’t support other currencies). Add `blik` 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`. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=pln \ -d "payment_method_types[]=blik" \ --data-urlencode "description=A description of what you're selling" \ -d statement_descriptor=ORDER_123 ``` ### 客户端 在客户端,从您的服务器请求 PaymentIntent 并保存它的客户端私钥。 #### Kotlin ```kotlin class BlikPaymentActivity: AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret } } ``` ## 收集支付方式详情 [客户端] In your app, collect the required 6-digit BLIK code from the customer. Create a `PaymentMethodOptionsParams` with the BLIK code. #### Kotlin ```kotlin val paymentMethodOptionsParams = PaymentMethodOptionsParams.Blik(code = "777123"), ``` ## 向 Stripe 提交付款 [客户端] Retrieve the client secret from the PaymentIntent you created in step 2 and the 6-digit BLIK code you collected in step 3 and call [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/index.html#74063765%2FFunctions%2F-1622557690). #### Kotlin ```kotlin class BlikPaymentActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private val paymentLauncher: PaymentLauncher by lazy { PaymentLauncher.Companion.create( this, PaymentConfiguration.getInstance(applicationContext).publishableKey, PaymentConfiguration.getInstance(applicationContext).stripeAccountId, ::onPaymentResult ) } private fun startCheckout() { // ... val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = PaymentMethodCreateParams.createBlik(), clientSecret = paymentIntentClientSecret, paymentMethodOptions = paymentMethodOptionsParams ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { val message = when (paymentResult) { is PaymentResult.Completed -> { // Show a timer or a dialog to your customer to prompt them to authorize the payment. // Poll your server or Stripe API for the PaymentIntent status update } is PaymentResult.Canceled -> { "Canceled!" } is PaymentResult.Failed -> { // This string comes from the PaymentIntent's error message. // See here: https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-message "Failed: " + paymentResult.throwable.message } } } } ``` After confirmation with valid parameters, the status of the PaymentIntent becomes `requires_action` and `onPaymentResult` is called with `PaymentResult.Completed`. The `next_action` has the `blik_authorize` type: this means that the next step is completed by your customer, who has 60 seconds to confirm the payment inside their mobile banking app. We recommend: - Showing a timer or dialog to your customer to prompt them to authorize the payment - Polling your server or Stripe API for the PaymentIntent status update - Displaying the payment confirmation to your customer as soon as the PaymentIntent status updates to `succeeded` ## Optional: 处理付款后事件 付款完成时,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** [构建自定义 Webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) 处理程序,用于监听事件并创建自定义异步支付流程。使用 Stripe CLI 在本地测试和调试 Webhook 集成。 - **集成一个预构建的 App** 通过集成合作伙伴的应用程序,处理常见的企业事件,如[自动化](https://stripe.partners/?f_category=automation) 或[市场营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## Optional: Simulate failures in a sandbox BLIK payments can fail for different reasons. There are immediate failures (for example, the code is expired or invalid), delayed errors (the bank declines) or timeouts (the customer didn’t respond in time). You can simulate each failure scenarios by passing `email` values matching certain patterns (documented below) when creating the `PaymentIntent`, as part of the [billing details](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_data-billing_details), with any 6-digit as BLIK code. ### Immediate Failures | 失败代码 | 解释 | Email pattern | | ---------------------------------- | ------------------------------------- | ------------------- | | `payment_method_invalid_parameter` | 传递的代码不是一个有效的 BLIK 代码。 | `.*invalid_code@.*` | | `payment_method_invalid_parameter` | 传递的代码过期了。BLIK 代码 2 分钟后过期,请向客户请求另一个代码。 | `.*expired_code@.*` | ### Declines (8 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | ------------------------ | ------------------------- | | `payment_method_provider_decline` | 付款被拒绝了,原因是达到了该银行账户的支付限额。 | `.*limit_exceeded@.*` | | `payment_method_provider_decline` | 银行账户资金不足,无法完成购买。 | `.*insufficient_funds@.*` | | `payment_method_provider_decline` | 客户拒绝了这笔付款。 | `.*customer_declined@.*` | | `payment_method_provider_decline` | 付款被客户的银行拒绝了,原因未知。 | `.*bank_declined@.*` | | `payment_method_provider_decline` | 付款被拒绝,原因未知。 | `.*blik_declined@.*` | ### Timeouts (60 second delay) | 失败代码 | 解释 | Email pattern | | --------------------------------- | -------------------- | ----------------------- | | `payment_method_provider_timeout` | 客户未在分配的 60 秒内批准该笔付款。 | `.*customer_timeout@.*` | | `payment_method_provider_timeout` | 向客户的银行发出的请求超时了。 | `.*bank_timeout@.*` | | `payment_method_provider_timeout` | 向 BLIK 网络发出的请求超时了。 | `.*blik_timeout@.*` |