# 接受支付宝付款 用 Stripe API 和 Checkout 接受支付宝付款,这是中国人广泛使用的一种数字钱包 # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/alipay/accept-a-payment?payment-ui=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 集成中手动配置支付方式。 Alipay 是一种[单次使用](https://docs.stripe.com/payments/payment-methods.md#usage)的支付方式,客户需要[验证](https://docs.stripe.com/payments/payment-methods.md#customer-actions)他们的付款。客户在您的网站或应用程序中被跳转到 Alipay 页面,授权付款,然后返回您的网站或应用,然后在这里收到付款成功或失败的[即时通知](https://docs.stripe.com/payments/payment-methods.md#payment-notification)。 ## 确定兼容性 **客户地域**:China **支持的货币**:`aud, cad, eur, gbp, hkd, jpy, nzd, sgd, usd, myr` **展示货币**:`aud, cad, cny, eur, gbp, hkd, jpy, nzd, sgd, usd, myr` **支付模式**:Yes **设置模式**:No **订阅模式**:No 要支持支付宝付款,Checkout Session 必须满足以下全部条件: - 所有行项目的*价格* (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)都必须使用同一币种。 - 如果您的某些行项目使用的是不同币种,则为每个币种单独创建 Checkout Sessions。 - 只能使用一次性行项目。 不支持经常性*订阅* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)方案。 ## 收款 > 使用本指南之前,先构建一个集成来用 Checkout [接受付款](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout)。 本指南将指导您如何启用支付宝,并说明使用动态支付方式收款与手动配置支付方式之间的差异。 ### 启用支付宝这一支付方式 创建新的 [Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) 时,您需要: 1. 将`支付宝`添加到 `payment_method_types` 列表。 1. 确保所有的 `line_items` 都使用相同的货币。 #### Stripe 托管页面 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=hkd" \ -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]=alipay" \ --data-urlencode "success_url=https://example.com/success" ``` #### 嵌入式表单 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=hkd" \ -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]=alipay" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### 履行订单 接受付款后,学习如何[履行订单](https://docs.stripe.com/checkout/fulfillment.md)。 ## 测试您的集成 测试您的 Checkout 集成时,选择支付宝这一支付方式,然后点击**支付**按钮。 ## 处理退款和争议 支付宝的退款期限最长为原始付款的 90 以内。 支付宝不涉及争议流程——客户用他们的支付宝账户进行验证。 ## See also - [有关支付宝的更多信息](https://docs.stripe.com/payments/alipay.md) - [Checkout 履行](https://docs.stripe.com/checkout/fulfillment.md) - [自定义 Checkout](https://docs.stripe.com/payments/checkout/customization.md) # 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/alipay/accept-a-payment?payment-ui=mobile&platform=ios. Alipay 是一种[单次使用](https://docs.stripe.com/payments/payment-methods.md#usage)的支付方式,客户需要[验证](https://docs.stripe.com/payments/payment-methods.md#customer-actions)他们的付款。客户在您的网站或应用程序中被跳转到 Alipay 页面,授权付款,然后返回您的网站或应用,然后在这里收到付款成功或失败的[即时通知](https://docs.stripe.com/payments/payment-methods.md#payment-notification)。 ## 设置 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 [服务器端] [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) 是一个用来表示您从客户收款意图的对象,并可用于跟踪付款流程的生命周期。在您的服务器上创建一个 `PaymentIntent`,并指定要收取的金额和[支持的币种](https://docs.stripe.com/payments/alipay.md#supported-currencies)。如果您有现成的 [Payment Intents](https://docs.stripe.com/payments/payment-intents.md) 集成,则将 `alipay` 添加到 [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 "payment_method_types[]=alipay" \ -d amount=1099 \ -d currency=hkd ``` ## 重定向到支付宝钱包 [客户端] 进入您的应用程序的设置中的“信息”选项卡,[为您的应用注册一个自定义 URL Scheme(网页地址协议)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)。 ![在 Xcode 中设置一个自定义页面内跳转协议 (URL Scheme)](https://b.stripecdn.com/docs-statics-srv/assets/ios-custom-url-scheme.e7bbf5f60cbb1a96f157f5cd89410120.png) 支付宝应用打开此 URL,客户完成付款后,返回到您的应用。将 URL 转发给您的 `UISceneDelegate` 或 `UIApplicationDelegate` 中 Stripe SDK。 #### 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 } ``` 当客户点击支付宝进行支付时,用 [STPPaymentHandler confirmPayment](https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentHandler.html#/c:@M@StripePayments@objc\(cs\)STPPaymentHandler\(im\)confirmPayment:withAuthenticationContext:completion:) 确认 PaymentIntent。这样将启动支付宝应用,如果没有安装支付宝的话,会显示一个网络视图。 #### Swift ```swift import UIKit import StripePayments class CheckoutViewController: UIViewController { // ... func pay() { let clientSecret = ... // The client secret of the PaymentIntent let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret) paymentIntentParams.paymentMethodParams = STPPaymentMethodParams(alipay: STPPaymentMethodAlipayParams(), billingDetails: nil, metadata: nil) paymentIntentParams.paymentMethodOptions = STPConfirmPaymentMethodOptions() paymentIntentParams.paymentMethodOptions?.alipayOptions = STPConfirmAlipayOptions() paymentIntentParams.returnURL = "{{URL SCHEME}}://safepay/" // Replace {{URL SCHEME}} with your own custom URL scheme. STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (status, intent, error) in switch status { case .canceled: // Payment was canceled case .failed: // Payment failed case .succeeded: // Payment was successful @unknown default: fatalError() } } } } extension CheckoutViewController: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { return self } } ``` 支付宝打开以 `safepay/` 开头的返回页面。例如,如果您的自定义网页地址协议是 `myapp`,则回调页面必须是 `myapp://safepay/`。 ## 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)。 ### 接收事件并启动公司操作 在接收和处理公司操作方面有几个选项。 #### 手动 用 Stripe 管理平台查看您的所有 Stripe 付款,发送邮件收据,处理提现或重试失败的付款。 - [在管理平台内查看测试付款](https://dashboard.stripe.com/test/payments) #### 自定义代码 构建一个 Webhook 处理程序,侦听事件并构建自定义同步付款流程。用 Stripe CLI 在本地测试并调试您的 Webhook 集成。 - [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) #### 预构建应用 通过集成合作伙伴应用程序处理常见业务事件,例如[自动化](https://stripe.partners/?f_category=automation)或[营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## 支持的货币 Your account must have a bank account for one of the following currencies. You can create Alipay payments in the currencies that map to your country. The default local currency for Alipay is `cny` and customers also see their purchase amount in `cny`. | 货币 | 国家/地区 | | ----- | -------------------------------------------------------------------------------------------------------- | | `cny` | 任何国家 | | `aud` | 澳大利亚 | | `cad` | 加拿大 | | `eur` | 奥地利、比利时、保加利亚、塞浦路斯、捷克共和国、丹麦、爱沙尼亚、芬兰、法国、德国、希腊、爱尔兰、意大利、拉脱维亚、立陶宛、卢森堡、马耳他、荷兰、挪威、葡萄牙、罗马尼亚、斯洛伐克、斯洛文尼亚、西班牙、瑞典、瑞士 | | `gbp` | 英国 | | `hkd` | 香港 | | `jpy` | 日本 | | `myr` | 马来西亚 | | `nzd` | 新西兰 | | `sgd` | 新加坡 | | `usd` | 美国 | 如果您拥有以另一种货币开设的银行账户,并希望以该货币创建支付宝支付,可以[联系支持服务](https://support.stripe.com/email)。我们会根据具体情况为其他货币提供支持服务。 # 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/alipay/accept-a-payment?payment-ui=mobile&platform=android. Alipay 是一种[单次使用](https://docs.stripe.com/payments/payment-methods.md#usage)的支付方式,客户需要[验证](https://docs.stripe.com/payments/payment-methods.md#customer-actions)他们的付款。客户在您的网站或应用程序中被跳转到 Alipay 页面,授权付款,然后返回您的网站或应用,然后在这里收到付款成功或失败的[即时通知](https://docs.stripe.com/payments/payment-methods.md#payment-notification)。 ## 设置 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.2.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.2.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 请求。 ## 集成支付宝 SDK [客户端] 对于使用支付宝的应用间跳转流程的应用内付款,必须集成[支付宝 SDK](https://global.alipay.com/docs/ac/app/download)。如果您不想集成支付宝 SDK,则 Stripe SDK 会用一个 WebView 将客户重定向到支付宝。集成支付宝 SDK 后可为您的客户提供一个更加无缝的使用体验,但会让您的应用程序的下载尺寸变大。更多详情,请查看[使用 WebView](https://docs.stripe.com/payments/alipay/accept-a-payment.md#android-using-a-webview)。 解压后,将 `alipaySdk-{version}.aar` 添加到您的应用程序的 `libs` 目录。将 `libs` 文件夹添加到您的项目的依赖库列表: ```groovy allprojects { repositories { flatDir { dirs 'libs' } } } ``` 向应用程序添加依赖: ```groovy dependencies { // ... // Replace {version} with the version number of the Alipay SDK that you downloaded above implementation(name:"alipaySdk-{version}", ext:"aar") } ``` ## 创建 PaymentIntent [服务器端] [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) 是一个用来表示您从客户收款意图的对象,并可用于跟踪付款流程的生命周期。在您的服务器上创建一个 `PaymentIntent`,并指定要收取的金额和[支持的币种](https://docs.stripe.com/payments/alipay.md#supported-currencies)。如果您有现成的 [Payment Intents](https://docs.stripe.com/payments/payment-intents.md) 集成,则将 `alipay` 添加到 [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 "payment_method_types[]=alipay" \ -d amount=1099 \ -d currency=hkd ``` ## 重定向到支付宝钱包 [客户端] 从您的服务器请求 PaymentIntent 并保存它的客户端私钥。 #### Kotlin ```kotlin class AlipayActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { // ... fetchPaymentIntent() } private fun fetchPaymentIntent() { // Request a PaymentIntent from your server and store its client secret } } ``` 当客户点击支付宝进行支付时,用 Stripe `confirmAlipayPayment` 确认 PaymentIntent。必须提供一个 AlipayAuthenticator 来将来自 Stripe SDK 的数据传递给支付宝 SDK。验证器通过提供的数据字串调用支付宝 `payV2` 方式。支付宝 SDK 打开支付宝应用程序(若安装),或显示它自己的 UI 并自动将结果返回到 Stripe SDK。 > 支付宝 Android SDK 不支持测试付款。要全面测试此集成,请使用[真实模式](https://docs.stripe.com/keys.md#test-live-modes)。 #### Kotlin ```kotlin import com.alipay.sdk.app.PayTask class AlipayActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private val stripe: Stripe by lazy { Stripe( applicationContext, PaymentConfiguration.getInstance(applicationContext).publishableKey ) } // Call this function when the customer taps "Pay with Alipay" private fun startCheckout() { // ... lifecycleScope.launch { runCatching { stripe.confirmAlipayPayment( ConfirmPaymentIntentParams.createAlipay(paymentIntentClientSecret), { data -> PayTask(this@AlipayActivity).payV2(data, true) } ) }.fold( onSuccess = { result -> val paymentIntent = result.intent val status = paymentIntent.status when (status) { StripeIntent.Status.Succeeded -> { // Payment succeeded } StripeIntent.Status.RequiresAction -> { // Customer didn't complete the payment // You can try to confirm this Payment Intent again } else -> { // Payment failed/canceled } } }, onFailure = { // Payment failed } ) } } } ``` ## Optional: 使用 WebView [客户端] 如果不想集成支付宝 SDK,则在您调用 `confirmPayment` 时,Stripe SDK 可将客户重定向到一个支付宝 WebView。支付宝网站打开支付宝应用程序(若安装),或允许客户在网页上完成付款。 #### Kotlin ```kotlin class AlipayActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private val stripe: Stripe by lazy { Stripe( applicationContext, PaymentConfiguration.getInstance(applicationContext).publishableKey ) } // Call this method when the customer taps "Pay with Alipay" private fun startCheckout() { // ... val confirmParams = ConfirmPaymentIntentParams.createAlipay(paymentIntentClientSecret) stripe.confirmPayment(this, confirmParams) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Handle the result of stripe.confirmPayment stripe.onPaymentResult(requestCode, data, object : ApiResultCallback { override fun onSuccess(result: PaymentIntentResult) { val paymentIntent = result.intent val status = paymentIntent.status when (status) { StripeIntent.Status.Succeeded -> { // Payment succeeded } StripeIntent.Status.RequiresAction -> { // Customer didn't complete the payment // You can try to confirm this Payment Intent again } else -> { // Payment failed/canceled } } } override fun onError(e: Exception) { // Payment failed } }) } } ``` ## 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)。 ### 接收事件并启动公司操作 在接收和处理公司操作方面有几个选项。 #### 手动 用 Stripe 管理平台查看您的所有 Stripe 付款,发送邮件收据,处理提现或重试失败的付款。 - [在管理平台内查看测试付款](https://dashboard.stripe.com/test/payments) #### 自定义代码 构建一个 Webhook 处理程序,侦听事件并构建自定义同步付款流程。用 Stripe CLI 在本地测试并调试您的 Webhook 集成。 - [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) #### 预构建应用 通过集成合作伙伴应用程序处理常见业务事件,例如[自动化](https://stripe.partners/?f_category=automation)或[营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## 支持的货币 Your account must have a bank account for one of the following currencies. You can create Alipay payments in the currencies that map to your country. The default local currency for Alipay is `cny` and customers also see their purchase amount in `cny`. | 货币 | 国家/地区 | | ----- | -------------------------------------------------------------------------------------------------------- | | `cny` | 任何国家 | | `aud` | 澳大利亚 | | `cad` | 加拿大 | | `eur` | 奥地利、比利时、保加利亚、塞浦路斯、捷克共和国、丹麦、爱沙尼亚、芬兰、法国、德国、希腊、爱尔兰、意大利、拉脱维亚、立陶宛、卢森堡、马耳他、荷兰、挪威、葡萄牙、罗马尼亚、斯洛伐克、斯洛文尼亚、西班牙、瑞典、瑞士 | | `gbp` | 英国 | | `hkd` | 香港 | | `jpy` | 日本 | | `myr` | 马来西亚 | | `nzd` | 新西兰 | | `sgd` | 新加坡 | | `usd` | 美国 | 如果您拥有以另一种货币开设的银行账户,并希望以该货币创建支付宝支付,可以[联系支持服务](https://support.stripe.com/email)。我们会根据具体情况为其他货币提供支持服务。 # 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/alipay/accept-a-payment?payment-ui=mobile&platform=react-native. Alipay 是一种[单次使用](https://docs.stripe.com/payments/payment-methods.md#usage)的支付方式,客户需要[验证](https://docs.stripe.com/payments/payment-methods.md#customer-actions)他们的付款。客户在您的网站或应用程序中被跳转到 Alipay 页面,授权付款,然后返回您的网站或应用,然后在这里收到付款成功或失败的[即时通知](https://docs.stripe.com/payments/payment-methods.md#payment-notification)。 ## 设置 Stripe [服务器端] [客户端] ### 服务器端 该集成要求您的服务器上的端点与 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' ``` ### 客户端 [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)密钥。 ## 创建 PaymentIntent [服务器端] [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) 是一个用来表示您从客户收款意图的对象,并可用于跟踪付款流程的生命周期。在您的服务器上创建一个 `PaymentIntent`,并指定要收取的金额和[支持的币种](https://docs.stripe.com/payments/alipay.md#supported-currencies)。如果您有现成的 [Payment Intents](https://docs.stripe.com/payments/payment-intents.md) 集成,则将 `alipay` 添加到 [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 "payment_method_types[]=alipay" \ -d amount=1099 \ -d currency=hkd ``` ## 重定向到支付宝钱包 [客户端] 对于银行重定向和数字钱包支付方式,Stripe React Native SDK 指定的是 `safepay/` 作为返回页面 的主机。客户用支付宝完成付款后,会被重定向到 `myapp://safepay/`,其中 `myapp` 就是您的自定义页面内跳转协议。 当客户退出您的应用时(例如,在 Safari 浏览器或其银行应用程序中进行验证),为他们提供一种方式,以便他们自动返回到您的应用程序。很多支付方式类型_要求_提供一个返回 URL。如果您不提供这样一个 URL,我们就无法向您的用户显示需要返回 URL 的支付方式,即使您已启用了这些支付方式。 要提供返回 URL,请执行以下操作: 1. [注册](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app#Register-your-URL-scheme) 自定义 URL。不支持通用链接。 1. [配置](https://reactnative.dev/docs/linking) 您的自定义 URL。 1. 设置您的根组件,将 URL 转发到 Stripe SDK,如下所示。 > 如果您在使用 Expo,则在 `app.json` 文件中[设置您的协议](https://docs.expo.io/guides/linking/#in-a-standalone-app)。 ```jsx import { useEffect, useCallback } from 'react'; import { Linking } from 'react-native'; import { useStripe } from '@stripe/stripe-react-native'; export default function MyApp() { const { handleURLCallback } = useStripe(); const handleDeepLink = useCallback( async (url: string | null) => { if (url) { const stripeHandled = await handleURLCallback(url); if (stripeHandled) { // This was a Stripe URL - you can return or add extra handling here as you see fit } else { // This was NOT a Stripe URL – handle as you normally would } } }, [handleURLCallback] ); useEffect(() => { const getUrlAsync = async () => { const initialUrl = await Linking.getInitialURL(); handleDeepLink(initialUrl); }; getUrlAsync(); const deepLinkListener = Linking.addEventListener( 'url', (event: { url: string }) => { handleDeepLink(event.url); } ); return () => deepLinkListener.remove(); }, [handleDeepLink]); return ( ); } ``` 有关 Native URL Scheme(页面内跳转协议)的更多信息,请参考 [Android](https://developer.android.com/training/app-links/deep-linking) 和 [iOS](https://developer.apple.com/documentation/xcode/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app) 文档。 ## 确认付款 [客户端] 当客户点击支付宝进行支付时,调用 `confirmPayment`,展示一个网络视图,让客户在这里完成付款。 ```javascript export default function AlipayPaymentScreen() { const [email, setEmail] = useState(''); const { confirmPayment, loading } = useConfirmPayment(); const handlePayPress = async () => { const { clientSecret } = await fetchPaymentIntentClientSecret(); const { error, paymentIntent } = await confirmPayment(clientSecret, { paymentMethodType: 'Alipay', }); if (error) { Alert.alert(`Error code: ${error.code}`, error.message); } else if (paymentIntent) { Alert.alert( 'Success', `The payment was confirmed successfully! currency: ${paymentIntent.currency}` ); } }; return ( setEmail(value.nativeEvent.text)} /> ``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## 重定向到支付宝钱包 [客户端] 客户通过 Alipay 点击支付时,用 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('<>'); ``` 使用 `PaymentIntent` 的[客户端私钥](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)并调用 `stripe.confirmAlipayPayment`来处理 支付宝重定向。添加一个 `return_url`,确定在客户完成付款后让 Stripe 将他们重定向到哪里。 ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async function(event) { event.preventDefault(); // Set the clientSecret of the PaymentIntent const { error } = await stripe.confirmAlipayPayment(clientSecret, { // Return URL where the customer should be redirected after the authorization return_url: `${window.location.href}`, }); if (error) { // Inform the customer that there was an error. const errorElement = document.getElementById('error-message'); errorElement.textContent = error.message; } }); ``` `return_url` 对应于您网站上显示付款结果的一个页面。通过对 `PaymentIntent` 进行[状态验证](https://docs.stripe.com/payments/payment-intents/verifying-status.md#checking-status),您可以确定要显示的内容。要验证状态,Stripe 到 `return_url` 的重定向会包含以下 URL 查询参数。您还可以将自己的查询参数附加到 `return_url`。它们会贯穿整个重定向过程。 | 参数 | 描述 | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | `PaymentIntent` 的唯一标识符。 | | `payment_intent_client_secret` | `PaymentIntent` 对象的[客户端私钥](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 | ## Optional: 手动处理重定向 [服务器端] 处理重定向的最好方式是使用包含 `confirmAlipayPayment` 的 Stripe.js。若要手动重定向客户: 1. 提供客户完成付款后将其重定向到的 URL。 ```curl curl https://api.stripe.com/v1/payment_intents/pi_1DRuHnHgsMRlo4MtwuIAUe6u/confirm \ -u "<>:" \ -d payment_method=pm_1EnPf7AfTbPYpBIFLxIc8SD9 \ --data-urlencode "return_url=https://shop.example.com/crtA6B28E1" ``` 1. 确认 `PaymentIntent` 的状态是 `requires_action`。`next_action` 的类型将是 `alipay_handle_redirect`。 ```json "next_action": { "type": "alipay_handle_redirect", "alipay_handle_redirect": { "url": "https://hooks.stripe.com/...", "return_url": "https://example.com/checkout/complete" } } ``` 1. 将客户重定向到 `next_action` 属性中提供的 URL。 客户完成付款后,会被跳转到 `return_url` 目的地。其中会包含 `payment_intent` 和 `payment_intent_client_secret` URL 查询参数,而且您可以通过您自己的查询参数来传递,如上所述。 ## 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)。 ### 接收事件并启动公司操作 在接收和处理公司操作方面有几个选项。 #### 手动 用 Stripe 管理平台查看您的所有 Stripe 付款,发送邮件收据,处理提现或重试失败的付款。 - [在管理平台内查看测试付款](https://dashboard.stripe.com/test/payments) #### 自定义代码 构建一个 Webhook 处理程序,侦听事件并构建自定义同步付款流程。用 Stripe CLI 在本地测试并调试您的 Webhook 集成。 - [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) #### 预构建应用 通过集成合作伙伴应用程序处理常见业务事件,例如[自动化](https://stripe.partners/?f_category=automation)或[营销和销售](https://stripe.partners/?f_category=marketing-and-sales)。 ## 支持的货币 Your account must have a bank account for one of the following currencies. You can create Alipay payments in the currencies that map to your country. The default local currency for Alipay is `cny` and customers also see their purchase amount in `cny`. | 货币 | 国家/地区 | | ----- | -------------------------------------------------------------------------------------------------------- | | `cny` | 任何国家 | | `aud` | 澳大利亚 | | `cad` | 加拿大 | | `eur` | 奥地利、比利时、保加利亚、塞浦路斯、捷克共和国、丹麦、爱沙尼亚、芬兰、法国、德国、希腊、爱尔兰、意大利、拉脱维亚、立陶宛、卢森堡、马耳他、荷兰、挪威、葡萄牙、罗马尼亚、斯洛伐克、斯洛文尼亚、西班牙、瑞典、瑞士 | | `gbp` | 英国 | | `hkd` | 香港 | | `jpy` | 日本 | | `myr` | 马来西亚 | | `nzd` | 新西兰 | | `sgd` | 新加坡 | | `usd` | 美国 | 如果您拥有以另一种货币开设的银行账户,并希望以该货币创建支付宝支付,可以[联系支持服务](https://support.stripe.com/email)。我们会根据具体情况为其他货币提供支持服务。