# 错误处理

捕获并响应卡组织拒付、无效数据、卡组织问题等。

Stripe 提供很多种错误。可能会反映外部事件（如付款被拒绝和卡组织中断），也可能会反映代码问题（如 API 调用无效）。

## 解析错误数据

当 Stripe 向您的 API 请求返回错误时，您会收到有关该错误的详细信息，这些信息有助于您理解如何运用本指南中的处理建议。如有需要，这些详细信息还能帮您向 Stripe 支持人员提供重要信息。

| 属性                | 描述                                                                        |
| ----------------- | ------------------------------------------------------------------------- |
| `code`            | 错误代码。                                                                     |
| `doc_url`         | 指向 Stripe 文档中特定错误代码的链接。                                                   |
| `message`         | 错误原因的说明。                                                                  |
| `param`           | 导致错误的请求参数。                                                                |
| `request_log_url` | 链接至 Stripe 管理平台，您可在其中查看有关原始请求和错误的详细日志。                                    |
| 请求 ID             | 出错的原始请求的唯一标识符。错误响应头中包含此值（以`req`开头的字符串），不过您也可以在请求中指定打印输出，具体操作可参考本指南中的代码示例。 |
| `type`            | 此错误所属错误类别的参考。                                                             |

处理错误时，可以使用下表中的部分或全部方法。无论用哪个方法，您都可以遵从我们[为各类错误推荐的响应方式](https://docs.stripe.com/error-handling.md#error-types)。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [捕获异常](https://docs.stripe.com/error-handling.md#catch-exceptions)              | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 捕获异常

对于此库，您不需要检查非 200 HTTP 的响应情况。此库会将它们转换为异常。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

如果立即发生问题，妨碍某个 API 调用继续，则 Stripe Ruby 库会引发一个异常。最佳做法是捕获并处理异常。

要捕获某个异常，使用 Ruby 的 `rescue` 关键词。捕获 `Stripe::StripeError` 或它的子类，以仅处理特定的 Stripe 异常。每个子类代表一种不同的异常。捕获某个异常时，您可以[用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [捕获异常](https://docs.stripe.com/error-handling.md#catch-exceptions)              | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 捕获异常

对于此库，您不需要检查非 200 HTTP 的响应情况。此库会将它们转换为异常。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

如果立即发生问题，妨碍某个 API 调用继续，则 Stripe Python 库会引发一个异常。最佳做法是捕获并处理异常。

要捕获异常情况，请使用 Python 的 `try`/`except` 语句。抓住 `stripe.StripeError` 或其子类以仅处理 Stripe 特定的异常。每个子类代表不同类型的异常。捕获异常时，您可以[使用其类来选择响应](https://docs.stripe.com/error-handling.md#error-types)。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [捕获异常](https://docs.stripe.com/error-handling.md#catch-exceptions)              | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 捕获异常

对于此库，您不需要检查非 200 HTTP 的响应情况。此库会将它们转换为异常。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

如果立即发生问题，妨碍某个 API 调用继续，则 Stripe PHP 库会引发一个异常。最佳做法是捕获并处理异常。

要捕获一个异常情况，使用 PHP 的 `try`/`catch` 语句。Stripe 提供了您可以捕获的多个异常类别。每个都代表一种不同的错误。捕获某个异常时，您可以[用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [捕获异常](https://docs.stripe.com/error-handling.md#catch-exceptions)              | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 捕获异常

对于此库，您不需要检查非 200 HTTP 的响应情况。此库会将它们转换为异常。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

如果立即发生问题，妨碍某个 API 调用继续，则 Stripe Java 库会引发一个异常。最佳做法是捕获并处理异常。

要捕获一个异常情况，使用 Java 的 `try`/`catch` 语句。捕获 `StripeException` 或它的子类，以仅处理特定的 Stripe 异常。每个子类代表一种不同的异常。捕获某个异常时，您可以[用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [捕获异常](https://docs.stripe.com/error-handling.md#catch-exceptions)              | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 捕获异常

对于此库，您不需要检查非 200 HTTP 的响应情况。此库会将它们转换为异常。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

如果立即发生问题，妨碍某个 API 调用继续，则 Stripe Node.js 库会引发一个异常。最佳做法是捕获并处理异常。要启用异常发生并捕获异常，请按以下步骤操作：

- 如果您在一个函数中进行 API 调用，在函数定义前加上 `async` 关键词。
- 在 API 调用本身前面加上 `await` 关键词。
- 将 API 调用包在 `try`/`catch` 块中。

捕获一个异常时，您可以[用它的类型属性来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [使用错误值](https://docs.stripe.com/error-handling.md#catch-exceptions)             | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 使用错误值

对于此库，您不需要检查非 200 HTTP 的响应情况。此库将它们转换为错误值。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

Stripe Go 库中的 API 调用会同时返回一个结果值和一个错误值。使用多个任务捕获两个。如果错误值不是 `nil`，则说明有非直接的问题妨碍了 API 调用继续。

如果错误值与 Stripe 相关，则可以将它转换为一个 `stripe.Error` 对象，它的字段会对问题进行描述。[用 Type 字段选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。某些情况下，您可以用额外的信息强制将 `Err` 属性变成更为具体的错误类型。

| 方法                                                                              | 目的               | 需要时 |
| ------------------------------------------------------------------------------- | ---------------- | --- |
| [捕获异常](https://docs.stripe.com/error-handling.md#catch-exceptions)              | API 调用不能继续时恢复    | 总是  |
| [监测 Webhook](https://docs.stripe.com/error-handling.md#monitor-webhooks)        | 从 Stripe 对通知做出反应 | 有时候 |
| [获取存储的故障相关信息](https://docs.stripe.com/error-handling.md#use-stored-information) | 调查过往问题并支持其他方法    | 有时候 |

## 捕获异常

对于此库，您不需要检查非 200 HTTP 的响应情况。此库会将它们转换为异常。

极少情况下您会需要 HTTP 详情，查看[低级别异常处理](https://docs.stripe.com/error-low-level.md)和[错误](https://docs.stripe.com/api/errors.md)对象。

如果立即发生问题，妨碍某个 API 调用继续，则 Stripe .NET 库会引发一个异常。最佳做法是捕获并处理异常。

要捕获一个异常情况，使用 .NET 的 `try`/`catch` 语句。捕获一个 `StripeException`，然后[用它的类型属性来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

#### Ruby

```ruby
require 'stripe'

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

def example_function(params)
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    puts "A payment error occurred: #{e.error.message} (request id: #{e.request_id})"
  rescue Stripe::InvalidRequestError => e
    puts "An invalid request occurred. (request id: #{e.request_id})"
  # Add additional catch cases for other Stripe exception types as needed.
  # See all exception types at https://docs.stripe.com/api/errors/handling?lang=ruby
  rescue Stripe::StripeError => e
    # All other Stripe errors
    puts "Status: #{e.http_status}, Code: #{e.code}, Message: #{e.message}, Request ID: #{e.request_id}"
  else
    puts "No error."
  end
end
```

设置完异常处理措施后，使用包括[测试卡](https://docs.stripe.com/testing.md)在内的多种数据进行测试，来模拟不同的支付结果。

#### 触发的错误 - 请求无效

#### Ruby

```ruby
example_function(
  # The required parameter currency is missing,
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa', # 这是一个测试卡，在测试环境下使用时总会成功。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
An invalid request occurred.
```

#### 触发的错误 - 银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedFraudulent', # 这是一个测试卡，始终会引发一个欺诈性收款支付错误。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
A payment error occurred: Your card was declined.
```

#### 触发的错误 - 无错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa', # 这是一个测试卡，在测试环境下使用时总会成功。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
No error.
```

## 监测 Webhook

Stripe 会用 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 通知您很多中问题。包括那些在 API 调用后不会立即发生的问题。例如：

- 您输掉了一个争议。
- 经常性付款在成功几个月后仍可能会失败。
- 您的前端*确认* (Confirming a PaymentIntent indicates that the customer intends to pay with the current or provided payment method. Upon confirmation, the PaymentIntent attempts to initiate a payment)一笔付款，然后在发现付款失败之前就会离线。（后端仍会收到 Webhook 通知，即使不是发出 API 调用的那一个。）

您不需要处理每个 Webhook 事件类型。事实上，有些集成一个都不会处理。

在您的 Webhook 处理程序中，从 [Webhook 构建器](https://docs.stripe.com/webhooks/quickstart.md)的基本步骤开始：获取一个事件对象，用事件类型查看到底发生了什么情况。然后，如果事件类型指示有错误，执行以下步骤：

1. 访问 [event.data.object](https://docs.stripe.com/api/events/object.md#event_object-data-object)，以检索受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

1. 访问 [event[‘data’][‘object’]](https://docs.stripe.com/api/events/object.md#event_object-data-object)，以检索受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

1. 访问 [event->data->object](https://docs.stripe.com/api/events/object.md#event_object-data-object)，以检索受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

1. 使用一个 `EventDataObjectDeserializer` 并将它的结果转换为适当类型来获取受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

1. 访问 [event.data.object](https://docs.stripe.com/api/events/object.md#event_object-data-object)，以检索受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

1. 通过从 `event.Data.Raw` 解组数据来获取受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

1. 通过将 [stripeEvent.Data.Object](https://docs.stripe.com/api/events/object.md#event_object-data-object) 转换为适当的类型来获取受影响的对象。
1. [使用存储的受影响对象信息](https://docs.stripe.com/error-handling.md#use-stored-information)来获取上下文，包括错误对象。
1. [用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

#### Ruby

```ruby
require 'stripe'
require 'sinatra'

client = Stripe::StripeClient.new(ENV.fetch('STRIPE_API_KEY'))
post '/webhook' do
  payload = request.body.read
  data = JSON.parse(payload, symbolize_names: true)

  # Get the event object
  event = Stripe::Event.construct_from(data)

  # Use the event type to find out what happened
  case event.type
  when 'payment_intent.payment_failed'

    # Get the object affected
    payment_intent = event.data.object

    # Use stored information to get an error object
    e = payment_intent.last_payment_error

    # Use its type to choose a response
    case e.type
    when 'card_error'
      puts "A payment error occurred: #{e.message}"
    when 'invalid_request'
      puts "An invalid request occurred."
    else
      puts "Another problem occurred, maybe unrelated to Stripe."
    end
  end

  content_type 'application/json'
  {
    status: 'success'
  }.to_json
end
```

要测试您的集成对 Webhook 事件的响应情况，您可以[在本地触发 Webhook 事件](https://docs.stripe.com/webhooks.md#test-webhook)。完成此链接的设置步骤后，触发一个失败的付款，看引发的错误消息是什么。

```bash
stripe trigger payment_intent.payment_failed
```

```bash
A payment error occurred: Your card was declined.
```

## 获取存储的故障相关信息

很多对象存储着有关故障的信息。这就是说，如果已经发生了错误，则您可以检索对象进行检查，了解更多信息。很多情况下，存储的信息采用的是错误对象的形式，您可以[用它的类型来选择一个响应方式](https://docs.stripe.com/error-handling.md#error-types)。

例如：

1. 检索特定的支付意图。
1. 通过确定 [last_payment_error](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error) 是否为空，检查它是否遇到了支付错误。
1. 如果为空，则记录错误，包括其类型和受影响的对象。

#### Ruby

```ruby
require 'stripe'
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

payment_intent = client.v1.payment_intents.retrieve({{PAYMENT_INTENT_ID}})
e = payment_intent.last_payment_error
if !e.nil?
  puts "PaymentIntent #{payment_intent.id} experienced a #{e.type}."
end
```

这是一些存储了故障信息的常见对象。

| 对象                                                     | 属性                        | 值                                                                                    |
| ------------------------------------------------------ | ------------------------- | ------------------------------------------------------------------------------------ |
| [付款意图](https://docs.stripe.com/api/payment_intents.md) | `last_payment_error`      | [错误对象](https://docs.stripe.com/error-handling.md#parse-error-data)                   |
| [设置意图](https://docs.stripe.com/api/setup_intents.md)   | `last_setup_error`        | [错误对象](https://docs.stripe.com/error-handling.md#parse-error-data)                   |
| [账单](https://docs.stripe.com/api/invoices.md)          | `last_finalization_error` | [错误对象](https://docs.stripe.com/error-handling.md#parse-error-data)                   |
| [设置尝试](https://docs.stripe.com/api/setup_attempts.md)  | `setup_error`             | [错误对象](https://docs.stripe.com/error-handling.md#parse-error-data)                   |
| [提现](https://docs.stripe.com/api/payouts.md)           | `failure_code`            | [提现失败代码](https://docs.stripe.com/api/payouts/failures.md)                            |
| [退款](https://docs.stripe.com/api/refunds.md)           | `failure_reason`          | [退款失败代码](https://docs.stripe.com/api/refunds/object.md#refund_object-failure_reason) |

要测试使用了存储的故障信息的代码，通常需要模拟失败的交易。一般可以用[测试卡](https://docs.stripe.com/testing.md)或测试银行账号进行。例如：

- [模拟被拒绝的付款](https://docs.stripe.com/testing.md#declined-payments)，以创建失败的 Charge、PaymentIntent、SetupIntent，等等。
- [模拟失败的提现](https://docs.stripe.com/connect/testing.md#account-numbers).
- [模拟失败的退款](https://docs.stripe.com/testing.md#refunds).

## 错误类型及解决方案

在 Stripe Ruby 库中，错误对象属于 `stripe.error.StripeError` 及其子类别。用各类别的文档，查看相应的解决建议。

| 名称     | 等级                                                                                                            | 描述                                                                                                                                                                                                                                                            |
| ------ | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 支付错误   | [Stripe::CardError](https://docs.stripe.com/error-handling.md#payment-errors)                                 | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。 |
| 无效请求错误 | [Stripe::InvalidRequestError](https://docs.stripe.com/error-handling.md#invalid-request-errors)               | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                                                        |
| 连接错误   | [Stripe::APIConnectionError](https://docs.stripe.com/error-handling.md#connection-errors)                     | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                      |
| API 错误 | [Stripe::APIError](https://docs.stripe.com/error-handling.md#api-errors)                                      | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                     |
| 验证错误   | [Stripe::AuthenticationError](https://docs.stripe.com/error-handling.md#authentication-errors)                | Stripe 无法用您提供的信息对您进行验证。                                                                                                                                                                                                                                       |
| 幂等性错误  | [Stripe::IdempotencyError](https://docs.stripe.com/error-handling.md#idempotency-errors)                      | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                         |
| 权限错误   | [Stripe::PermissionError](https://docs.stripe.com/error-handling.md#permission-errors)                        | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                                                                                        |
| 速率限制错误 | [Stripe::RateLimitError](https://docs.stripe.com/error-handling.md#rate-limit-errors)                         | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                                                            |
| 签名验证错误 | [Stripe::SignatureVerificationError](https://docs.stripe.com/error-handling.md#signature-verification-errors) | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                |

## 支付错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [Stripe::CardError](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 付款因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `Stripe::CardError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **代码**                                                                                                                                                                                                       | ```ruby
  
  # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
  # Find your keys at https://dashboard.stripe.com/apikeys.
  client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
  charge.outcome.type == 'blocked'
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | **代码** | `e.error.payment_intent.charges.data[0].outcome.type == 'blocked'` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 付款被发卡行拒绝

|  |
|  |
| **类型**   | `Stripe::CardError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **代码**   | `e.error.code == "card_declined"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `Stripe::CardError`                                                                                  |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

|  |
|  |
| **类型**   | `Stripe::InvalidRequestError`                                                                                                                                                |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                       |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照  的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用  来确定具体是哪一个。 |

## 连接错误

|  |
|  |
| **类型**   | `Stripe::APIConnectionError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| **问题**   | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  要知道是否成功，您可以：

  - 从 Stripe 检索相关对象并检查其状态。
  - 侦听操作成功或失败的 Webhook 通知。

  为应对连接错误，您可以：

  - 创建或更新某个对象时，使用一个 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md)。然后，如果出现连接错误，可以安全地重复请求，不会有创建第二个对象或执行两次更新的风险。用相同的等幂性密钥重复请求，直到收到明确的成功或失败信息。有关此策略的高级建议，请参阅[低级错误处理](https://docs.stripe.com/error-low-level.md#idempotency)。
  - 开启[自动重试](https://github.com/stripe/stripe-java?tab=readme-ov-file#configuring-automatic-retries)。此后，Stripe 会为您生成幂等键，并在安全时为您重复请求。

  该错误可能会掩盖其他错误。可能会发生这种情况，即解决掉连接错误后，会出现其他一些错误。检查所有方案中的错误，与您在原始请求中的操作一样。 |

## API 错误

|  |
|  |
| **类型**   | `Stripe::APIError`                                                                                                                                                                                                                                                                                                               |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 验证错误

|  |
|  |
| **类型**   | `Stripe::AuthenticationError`                                                                                               |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

## 幂等性错误

|  |
|  |
| **类型**   | `Stripe::IdempotencyError`                                                                            |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

## 权限错误

|  |
|  |
| **类型**   | `Stripe::PermissionError`                                                                                                                                                              |
| **问题**   | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                 |
| **解决方案** | - 确保您没有将[受限 API 密钥](https://docs.stripe.com/keys-best-practices.md#limit-access)用于它无法访问的服务。
  - 请勿以权限不足的[用户角色](https://docs.stripe.com/get-started/account/teams/roles.md)登入管理平台来执行操作。 |

## 速率限制错误

|  |
|  |
| **类型**   | `Stripe::RateLimitError`                                                                                                                                                                                                     |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

## 签名验证错误

|  |
|  |
| **类型**   | `Stripe::SignatureVerificationError`                                                                                                                                                                                                                                                       |
| **问题**   | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                                             |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。如果您使用的是 Webhook 签名验证，则当有第三方尝试给您发送虚假或恶意的 Webhook 时，就会发生验证失败问题，进而引发此错误。捕获它，并用 `400 Bad Request` 状态码响应。

  如果意外收到该错误（例如，用 Webhook 检测到来自于 Stripe 的错误），那么请查看[检查 Webhook 签名](https://docs.stripe.com/webhooks.md#verify-events)文档，获取更多建议。尤其要确保您使用的是正确的端点私钥。它不同于您的 API 密钥。 |

在 Stripe Python 库中，错误对象属于 `stripe.StripeError` 及其子类。使用每个类的文档获取关于如何响应的建议。

| 名称     | 等级                                                                                                           | 描述                                                                                                                                                                                                                                                            |
| ------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 支付错误   | [stripe.CardError](https://docs.stripe.com/error-handling.md#payment-errors)                                 | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。 |
| 无效请求错误 | [stripe.InvalidRequestError](https://docs.stripe.com/error-handling.md#invalid-request-errors)               | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                                                        |
| 连接错误   | [stripe.APIConnectionError](https://docs.stripe.com/error-handling.md#connection-errors)                     | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                      |
| API 错误 | [stripe.APIError](https://docs.stripe.com/error-handling.md#api-errors)                                      | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                     |
| 验证错误   | [stripe.AuthenticationError](https://docs.stripe.com/error-handling.md#authentication-errors)                | Stripe 无法用您提供的信息对您进行验证。                                                                                                                                                                                                                                       |
| 幂等性错误  | [stripe.IdempotencyError](https://docs.stripe.com/error-handling.md#idempotency-errors)                      | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                         |
| 权限错误   | [stripe.PermissionError](https://docs.stripe.com/error-handling.md#permission-errors)                        | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                                                                                        |
| 速率限制错误 | [stripe.RateLimitError](https://docs.stripe.com/error-handling.md#rate-limit-errors)                         | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                                                            |
| 签名验证错误 | [stripe.SignatureVerificationError](https://docs.stripe.com/error-handling.md#signature-verification-errors) | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                |

## 支付错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [stripe.CardError](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 付款因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `stripe.CardError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **代码**                                                                                                                                                                                                       | ```python
  charge = stripe.Charge.retrieve(e.error.payment_intent.latest_charge)
  charge.outcome.type == 'blocked'
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | **代码** | `e.error.payment_intent.charges.data[0].outcome.type == 'blocked'` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 付款被发卡行拒绝

|  |
|  |
| **类型**   | `stripe.CardError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| **代码**   | `e.code == "card_declined"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `stripe.CardError`                                                                                   |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

|  |
|  |
| **类型**   | `stripe.InvalidRequestError`                                                                                                                                                                     |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                           |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照 `e.doc_url` 的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用 `e.param` 来确定具体是哪一个。 |

## 连接错误

|  |
|  |
| **类型**   | `stripe.APIConnectionError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **问题**   | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  要知道是否成功，您可以：

  - 从 Stripe 检索相关对象并检查其状态。
  - 侦听操作成功或失败的 Webhook 通知。

  为应对连接错误，您可以：

  - 创建或更新某个对象时，使用一个 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md)。然后，如果出现连接错误，可以安全地重复请求，不会有创建第二个对象或执行两次更新的风险。用相同的等幂性密钥重复请求，直到收到明确的成功或失败信息。有关此策略的高级建议，请参阅[低级错误处理](https://docs.stripe.com/error-low-level.md#idempotency)。
  - 开启[自动重试](https://github.com/stripe/stripe-java?tab=readme-ov-file#configuring-automatic-retries)。此后，Stripe 会为您生成幂等键，并在安全时为您重复请求。

  该错误可能会掩盖其他错误。可能会发生这种情况，即解决掉连接错误后，会出现其他一些错误。检查所有方案中的错误，与您在原始请求中的操作一样。 |

## API 错误

|  |
|  |
| **类型**   | `stripe.APIError`                                                                                                                                                                                                                                                                                                                |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 验证错误

|  |
|  |
| **类型**   | `stripe.AuthenticationError`                                                                                                |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

## 幂等性错误

|  |
|  |
| **类型**   | `stripe.IdempotencyError`                                                                             |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

## 权限错误

|  |
|  |
| **类型**   | `stripe.PermissionError`                                                                                                                                                               |
| **问题**   | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                 |
| **解决方案** | - 确保您没有将[受限 API 密钥](https://docs.stripe.com/keys-best-practices.md#limit-access)用于它无法访问的服务。
  - 请勿以权限不足的[用户角色](https://docs.stripe.com/get-started/account/teams/roles.md)登入管理平台来执行操作。 |

## 速率限制错误

|  |
|  |
| **类型**   | `stripe.RateLimitError`                                                                                                                                                                                                      |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

## 签名验证错误

|  |
|  |
| **类型**   | `stripe.SignatureVerificationError`                                                                                                                                                                                                                                                        |
| **问题**   | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                                             |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。如果您使用的是 Webhook 签名验证，则当有第三方尝试给您发送虚假或恶意的 Webhook 时，就会发生验证失败问题，进而引发此错误。捕获它，并用 `400 Bad Request` 状态码响应。

  如果意外收到该错误（例如，用 Webhook 检测到来自于 Stripe 的错误），那么请查看[检查 Webhook 签名](https://docs.stripe.com/webhooks.md#verify-events)文档，获取更多建议。尤其要确保您使用的是正确的端点私钥。它不同于您的 API 密钥。 |

在 Stripe PHP 库中，每个错误类型都属于其自己的类别。用各类别的文档，查看相应的解决建议。

| 名称     | 等级                                                                                                                         | 描述                                                                                                                                                                                                                                                            |
| ------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 支付错误   | [Stripe\Exception\CardException](https://docs.stripe.com/error-handling.md#payment-errors)                                 | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。 |
| 无效请求错误 | [Stripe\Exception\InvalidRequestException](https://docs.stripe.com/error-handling.md#invalid-request-errors)               | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                                                        |
| 连接错误   | [Stripe\Exception\ApiConnectionException](https://docs.stripe.com/error-handling.md#connection-errors)                     | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                      |
| API 错误 | [Stripe\Exception\ApiErrorException](https://docs.stripe.com/error-handling.md#api-errors)                                 | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                     |
| 验证错误   | [Stripe\Exception\AuthenticationException](https://docs.stripe.com/error-handling.md#authentication-errors)                | Stripe 无法用您提供的信息对您进行验证。                                                                                                                                                                                                                                       |
| 幂等性错误  | [Stripe\Exception\IdempotencyException](https://docs.stripe.com/error-handling.md#idempotency-errors)                      | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                         |
| 权限错误   | [Stripe\Exception\PermissionException](https://docs.stripe.com/error-handling.md#permission-errors)                        | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                                                                                        |
| 速率限制错误 | [Stripe\Exception\RateLimitException](https://docs.stripe.com/error-handling.md#rate-limit-errors)                         | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                                                            |
| 签名验证错误 | [Stripe\Exception\SignatureVerificationException](https://docs.stripe.com/error-handling.md#signature-verification-errors) | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                |

## 支付错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [Stripe\Exception\CardException](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 付款因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `Stripe\Exception\CardException`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| **代码**                                                                                                                                                                                                       | ```php
  $charge = $stripe->charge->retrieve($e->getError()->payment_intent->latest_charge);
  $charge->outcome->type == 'blocked'
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | **代码** | `$e->getError()->payment_intent->charges->data[0]->outcome->type == 'blocked'` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 付款被发卡行拒绝

|  |
|  |
| **类型**   | `Stripe\Exception\CardException`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **代码**   | `$e->getError()->code == "card_declined"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `Stripe\Exception\CardException`                                                                     |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

|  |
|  |
| **类型**   | `Stripe\Exception\InvalidRequestException`                                                                                                                                                                                 |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                     |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照 `e->getError()->doc_url` 的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用 `e->getError()->param` 来确定具体是哪一个。 |

## 连接错误

|  |
|  |
| **类型**   | `Stripe\Exception\ApiConnectionException`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| **问题**   | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  要知道是否成功，您可以：

  - 从 Stripe 检索相关对象并检查其状态。
  - 侦听操作成功或失败的 Webhook 通知。

  为应对连接错误，您可以：

  - 创建或更新某个对象时，使用一个 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md)。然后，如果出现连接错误，可以安全地重复请求，不会有创建第二个对象或执行两次更新的风险。用相同的等幂性密钥重复请求，直到收到明确的成功或失败信息。有关此策略的高级建议，请参阅[低级错误处理](https://docs.stripe.com/error-low-level.md#idempotency)。
  - 开启[自动重试](https://github.com/stripe/stripe-java?tab=readme-ov-file#configuring-automatic-retries)。此后，Stripe 会为您生成幂等键，并在安全时为您重复请求。

  该错误可能会掩盖其他错误。可能会发生这种情况，即解决掉连接错误后，会出现其他一些错误。检查所有方案中的错误，与您在原始请求中的操作一样。 |

## API 错误

|  |
|  |
| **类型**   | `Stripe\Exception\APIException`                                                                                                                                                                                                                                                                                                  |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 验证错误

|  |
|  |
| **类型**   | `Stripe\Exception\AuthenticationException`                                                                                  |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

## 幂等性错误

|  |
|  |
| **类型**   | `Stripe\Exception\IdempotencyException`                                                               |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

## 权限错误

|  |
|  |
| **类型**   | `Stripe\Exception\PermissionException`                                                                                                                                                 |
| **问题**   | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                 |
| **解决方案** | - 确保您没有将[受限 API 密钥](https://docs.stripe.com/keys-best-practices.md#limit-access)用于它无法访问的服务。
  - 请勿以权限不足的[用户角色](https://docs.stripe.com/get-started/account/teams/roles.md)登入管理平台来执行操作。 |

## 速率限制错误

|  |
|  |
| **类型**   | `Stripe\Exception\RateLimitException`                                                                                                                                                                                        |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

## 签名验证错误

|  |
|  |
| **类型**   | `Stripe\Exception\SignatureVerificationException`                                                                                                                                                                                                                                          |
| **问题**   | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                                             |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。如果您使用的是 Webhook 签名验证，则当有第三方尝试给您发送虚假或恶意的 Webhook 时，就会发生验证失败问题，进而引发此错误。捕获它，并用 `400 Bad Request` 状态码响应。

  如果意外收到该错误（例如，用 Webhook 检测到来自于 Stripe 的错误），那么请查看[检查 Webhook 签名](https://docs.stripe.com/webhooks.md#verify-events)文档，获取更多建议。尤其要确保您使用的是正确的端点私钥。它不同于您的 API 密钥。 |

在 Stripe Java 库中，每个错误类型都属于其自己的类别。用各类别的文档，查看相应的解决建议。

| 名称     | 等级                                                                                                        | 描述                                                                                                                                                                                                                                                            |
| ------ | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 支付错误   | [CardException](https://docs.stripe.com/error-handling.md#payment-errors)                                 | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。 |
| 无效请求错误 | [InvalidRequestException](https://docs.stripe.com/error-handling.md#invalid-request-errors)               | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                                                        |
| 连接错误   | [ApiConnectionException](https://docs.stripe.com/error-handling.md#connection-errors)                     | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                      |
| API 错误 | [APIException](https://docs.stripe.com/error-handling.md#api-errors)                                      | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                     |
| 验证错误   | [AuthenticationException](https://docs.stripe.com/error-handling.md#authentication-errors)                | Stripe 无法用您提供的信息对您进行验证。                                                                                                                                                                                                                                       |
| 幂等性错误  | [IdempotencyException](https://docs.stripe.com/error-handling.md#idempotency-errors)                      | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                         |
| 权限错误   | [PermissionException](https://docs.stripe.com/error-handling.md#permission-errors)                        | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                                                                                        |
| 速率限制错误 | [RateLimitException](https://docs.stripe.com/error-handling.md#rate-limit-errors)                         | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                                                            |
| 签名验证错误 | [SignatureVerificationException](https://docs.stripe.com/error-handling.md#signature-verification-errors) | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                |

## 支付错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [CardException](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 付款因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `CardException`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **代码**                                                                                                                                                                                                       | ```java
  
  // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
  // Find your keys at https://dashboard.stripe.com/apikeys.
  StripeClient stripeClient = new StripeClient("<<YOUR_SECRET_KEY>>");
  Charge charge = stripeClient.v1().charges().retrieve(ex.getStripeError()
               .getPaymentIntent()
               .getLatestCharge());
  charge.getOutcome().getType() == "blocked"
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                    | **代码** | `ex.getStripeError().getPaymentIntent().getCharges().getData().get(0).getOutcome().getType() == "blocked"` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 付款被发卡行拒绝

|  |
|  |
| **类型**   | `CardException`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **代码**   | `e.getCode() == "card_declined"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `CardException`                                                                                      |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

|  |
|  |
| **类型**   | `InvalidRequestException`                                                                                                                                                                                 |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                    |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照 `e.getDocUrl()` 的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用 `e.getParam()` 来确定具体是哪一个。 |

## 连接错误

|  |
|  |
| **类型**   | `APIConnectionException`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **问题**   | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  要知道是否成功，您可以：

  - 从 Stripe 检索相关对象并检查其状态。
  - 侦听操作成功或失败的 Webhook 通知。

  为应对连接错误，您可以：

  - 创建或更新某个对象时，使用一个 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md)。然后，如果出现连接错误，可以安全地重复请求，不会有创建第二个对象或执行两次更新的风险。用相同的等幂性密钥重复请求，直到收到明确的成功或失败信息。有关此策略的高级建议，请参阅[低级错误处理](https://docs.stripe.com/error-low-level.md#idempotency)。
  - 开启[自动重试](https://github.com/stripe/stripe-java?tab=readme-ov-file#configuring-automatic-retries)。此后，Stripe 会为您生成幂等键，并在安全时为您重复请求。

  该错误可能会掩盖其他错误。可能会发生这种情况，即解决掉连接错误后，会出现其他一些错误。检查所有方案中的错误，与您在原始请求中的操作一样。 |

## API 错误

|  |
|  |
| **类型**   | `APIException`                                                                                                                                                                                                                                                                                                                   |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 验证错误

|  |
|  |
| **类型**   | `AuthenticationException`                                                                                                   |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

## 幂等性错误

|  |
|  |
| **类型**   | `IdempotencyException`                                                                                |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

## 权限错误

|  |
|  |
| **类型**   | `PermissionException`                                                                                                                                                                  |
| **问题**   | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                 |
| **解决方案** | - 确保您没有将[受限 API 密钥](https://docs.stripe.com/keys-best-practices.md#limit-access)用于它无法访问的服务。
  - 请勿以权限不足的[用户角色](https://docs.stripe.com/get-started/account/teams/roles.md)登入管理平台来执行操作。 |

## 速率限制错误

|  |
|  |
| **类型**   | `RateLimitException`                                                                                                                                                                                                         |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

## 签名验证错误

|  |
|  |
| **类型**   | `SignatureVerificationException`                                                                                                                                                                                                                                                           |
| **问题**   | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                                             |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。如果您使用的是 Webhook 签名验证，则当有第三方尝试给您发送虚假或恶意的 Webhook 时，就会发生验证失败问题，进而引发此错误。捕获它，并用 `400 Bad Request` 状态码响应。

  如果意外收到该错误（例如，用 Webhook 检测到来自于 Stripe 的错误），那么请查看[检查 Webhook 签名](https://docs.stripe.com/webhooks.md#verify-events)文档，获取更多建议。尤其要确保您使用的是正确的端点私钥。它不同于您的 API 密钥。 |

在 Stripe Node.js 库中，每个错误对象都有一个 `type` 属性。用各类别的文档，查看相应的解决建议。

| 名称     | 类型                                                                                                          | 描述                                                                                                                                                                                                                                                            |
| ------ | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 支付错误   | [StripeCardError](https://docs.stripe.com/error-handling.md#payment-errors)                                 | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。 |
| 无效请求错误 | [StripeInvalidRequestError](https://docs.stripe.com/error-handling.md#invalid-request-errors)               | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                                                        |
| 连接错误   | [StripeConnectionError](https://docs.stripe.com/error-handling.md#connection-errors)                        | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                      |
| API 错误 | [StripeAPIError](https://docs.stripe.com/error-handling.md#api-errors)                                      | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                     |
| 验证错误   | [StripeAuthenticationError](https://docs.stripe.com/error-handling.md#authentication-errors)                | Stripe 无法用您提供的信息对您进行验证。                                                                                                                                                                                                                                       |
| 幂等性错误  | [StripeIdempotencyError](https://docs.stripe.com/error-handling.md#idempotency-errors)                      | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                         |
| 权限错误   | [StripePermissionError](https://docs.stripe.com/error-handling.md#permission-errors)                        | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                                                                                        |
| 速率限制错误 | [StripeRateLimitError](https://docs.stripe.com/error-handling.md#rate-limit-errors)                         | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                                                            |
| 签名验证错误 | [StripeSignatureVerificationError](https://docs.stripe.com/error-handling.md#signature-verification-errors) | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                |

## 支付错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [StripeCardError](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 付款因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `StripeCardError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **代码**                                                                                                                                                                                                       | ```javascript
  const charge = await stripe.charges.retrieve(e.payment_intent.latest_charge)
  charge.outcome.type === 'blocked'
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | **代码** | `e.payment_intent.charges.data[0].outcome.type === 'blocked'` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 付款被发卡行拒绝

|  |
|  |
| **类型**   | `StripeCardError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **代码**   | `e.code === 'card_declined'`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `StripeCardError`                                                                                    |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

|  |
|  |
| **类型**   | `StripeInvalidRequestError`                                                                                                                                                                      |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                           |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照 `e.doc_url` 的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用 `e.param` 来确定具体是哪一个。 |

## 连接错误

|  |
|  |
| **类型**   | `StripeAPIConnectionError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **问题**   | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  要知道是否成功，您可以：

  - 从 Stripe 检索相关对象并检查其状态。
  - 侦听操作成功或失败的 Webhook 通知。

  为应对连接错误，您可以：

  - 创建或更新某个对象时，使用一个 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md)。然后，如果出现连接错误，可以安全地重复请求，不会有创建第二个对象或执行两次更新的风险。用相同的等幂性密钥重复请求，直到收到明确的成功或失败信息。有关此策略的高级建议，请参阅[低级错误处理](https://docs.stripe.com/error-low-level.md#idempotency)。
  - 开启[自动重试](https://github.com/stripe/stripe-java?tab=readme-ov-file#configuring-automatic-retries)。此后，Stripe 会为您生成幂等键，并在安全时为您重复请求。

  该错误可能会掩盖其他错误。可能会发生这种情况，即解决掉连接错误后，会出现其他一些错误。检查所有方案中的错误，与您在原始请求中的操作一样。 |

## API 错误

|  |
|  |
| **类型**   | `StripeAPIError`                                                                                                                                                                                                                                                                                                                 |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 验证错误

|  |
|  |
| **类型**   | `StripeAuthenticationError`                                                                                                 |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

## 幂等性错误

|  |
|  |
| **类型**   | `StripeIdempotencyError`                                                                              |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

## 权限错误

|  |
|  |
| **类型**   | `StripePermissionError`                                                                                                                                                                |
| **问题**   | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                 |
| **解决方案** | - 确保您没有将[受限 API 密钥](https://docs.stripe.com/keys-best-practices.md#limit-access)用于它无法访问的服务。
  - 请勿以权限不足的[用户角色](https://docs.stripe.com/get-started/account/teams/roles.md)登入管理平台来执行操作。 |

## 速率限制错误

|  |
|  |
| **类型**   | `StripeRateLimitError`                                                                                                                                                                                                       |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

## 签名验证错误

|  |
|  |
| **类型**   | `StripeSignatureVerificationError`                                                                                                                                                                                                                                                         |
| **问题**   | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                                             |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。如果您使用的是 Webhook 签名验证，则当有第三方尝试给您发送虚假或恶意的 Webhook 时，就会发生验证失败问题，进而引发此错误。捕获它，并用 `400 Bad Request` 状态码响应。

  如果意外收到该错误（例如，用 Webhook 检测到来自于 Stripe 的错误），那么请查看[检查 Webhook 签名](https://docs.stripe.com/webhooks.md#verify-events)文档，获取更多建议。尤其要确保您使用的是正确的端点私钥。它不同于您的 API 密钥。 |

在 Stripe Go 库中，每个错误对象都有一个 `Type` 属性。用各类别的文档，查看相应的解决建议。

| 名称     | 类型                                                                                                 | 描述                                                                                                                                                                                                                                                                 |
| ------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 支付错误   | [stripe.ErrorTypeCard](https://docs.stripe.com/error-handling.md#payment-errors)                   | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。      |
| 无效请求错误 | [stripe.ErrorTypeInvalidRequest](https://docs.stripe.com/error-handling.md#invalid-request-errors) | 您采用的 API 调用方式目前是无效的。这可能包括：

  - [速率限制错误](https://docs.stripe.com/error-handling.md#rate-limiting)
  - [验证错误](https://docs.stripe.com/error-handling.md#authentication-errors)
  - [无效参数或状态](https://docs.stripe.com/error-handling.md#invalid-parameters-or-state) |
| API 错误 | [stripe.ErrorTypeAPI](https://docs.stripe.com/error-handling.md#api-errors)                        | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                          |
| 幂等性错误  | [stripe.ErrorTypeIdempotency](https://docs.stripe.com/error-handling.md#idempotency-errors)        | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                              |

## 银行卡错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [stripe.ErrorTypeCard](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `stripe.ErrorTypeCard`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **代码**                                                                                                                                                                                                       | ```go
  charge = Charge.retrieve(stripeErr.PaymentIntent.LatestCharge)
  charge.Outcome.Type == "blocked"
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | **代码** | `stripeErr.PaymentIntent.Charges.Data[0].Outcome.Type == "blocked"` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 被发卡行拒绝

|  |
|  |
| **类型**   | `stripe.ErrorTypeCard`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **代码**   | `cardErr.Error.Code == stripe.ErrorCodeCardDeclined`                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `stripe.ErrorTypeCard`                                                                               |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

无效请求错误覆盖了一系列情况。最常见的一个是当 API 请求有无效的参数或您的集成的当前状态不允许时。可以用错误代码 (`stripeErr.Code`) 并查阅[错误代码文档](https://docs.stripe.com/error-codes.md)来寻找解决方案。有些错误代码需特别对待：

- `rate_limit` 和 `lock_timeout` 反映的是[速率限制错误](https://docs.stripe.com/error-handling.md#rate-limit-errors)
- `secret_key_required` 反映的是[验证错误](https://docs.stripe.com/error-handling.md#authentication-errors)
- 其他错误代码反映[无效参数或状态](https://docs.stripe.com/error-handling.md#invalid-request-errors)

### 速率限制错误

|  |
|  |
| **类型**   | `stripe.ErrorTypeInvalidRequest`                                                                                                                                                                                             |
| **代码**   | `stripeErr.Code == stripe.ErrorCodeRateLimit or stripeErr.Code == stripe.ErrorCodeLockTimeout`                                                                                                                               |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

### 验证错误

|  |
|  |
| **类型**   | `stripe.ErrorTypeInvalidRequest`                                                                                            |
| **代码**   | `stripeErr.Code == stripe.ErrorCodeSecretKeyRequired`                                                                       |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

### 无效参数或状态

|  |
|  |
| **类型**   | `stripe.ErrorTypeInvalidRequest`                                                                                                                                                                                |
| **代码**   | `stripeErr.Code != stripe.ErrorCodeRateLimit and stripeErr.Code != stripe.ErrorCodeLockTimeout and stripeErr.Code != stripe.ErrorCodeSecretKeyRequired`                                                         |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                          |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照 `stripeErr.DocURL` 的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用 `stripeErr.Param` 来确定具体是哪一个。 |

## API 错误

|  |
|  |
| **类型**   | `stripe.ErrorTypeAPI`                                                                                                                                                                                                                                                                                                            |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 幂等性错误

|  |
|  |
| **类型**   | `stripe.ErrorTypeIdempotency`                                                                         |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

在 Stripe .NET 库中，每个错误对象都有一个 `type` 属性。用各类别的文档，查看相应的解决建议。

| 名称     | 类型                                                                                                      | 描述                                                                                                                                                                                                                                                            |
| ------ | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 支付错误   | [card_error](https://docs.stripe.com/error-handling.md#payment-errors)                                  | 支付过程中发生了错误，涉及这些情况中的某一种：
  - [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
  - [发卡行拒绝了付款](https://docs.stripe.com/error-handling.md#payment-declined)。
  - [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)。 |
| 无效请求错误 | [invalid_request_error](https://docs.stripe.com/error-handling.md#invalid-request-errors)               | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                                                                                                        |
| 连接错误   | [api_connection_error](https://docs.stripe.com/error-handling.md#connection-errors)                     | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                      |
| API 错误 | [api_error](https://docs.stripe.com/error-handling.md#api-errors)                                       | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                     |
| 验证错误   | [authentication_error](https://docs.stripe.com/error-handling.md#authentication-errors)                 | Stripe 无法用您提供的信息对您进行验证。                                                                                                                                                                                                                                       |
| 幂等性错误  | [idempotency_error](https://docs.stripe.com/error-handling.md#idempotency-errors)                       | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。                                                                                                                                                         |
| 权限错误   | [permission_error](https://docs.stripe.com/error-handling.md#permission-errors)                         | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                                                                                        |
| 速率限制错误 | [rate_limit_error](https://docs.stripe.com/error-handling.md#rate-limit-errors)                         | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                                                            |
| 签名验证错误 | [signature_verification_error](https://docs.stripe.com/error-handling.md#signature-verification-errors) | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                |

## 支付错误

该部分的所有内容均适用于非银行卡付款由于历史原因，支付错误有 [card_error](https://docs.stripe.com/error-handling.md#card-error) 这个类型。但事实上，它们可以表示任何支付问题，无论是哪种支付方式。

支付错误（因历史原因，有时被称为“银行卡错误”）涵盖了很多常见的问题。它们分为三类：

- [付款因疑似欺诈被阻止](https://docs.stripe.com/error-handling.md#payment-blocked)
- [发卡行拒绝付款](https://docs.stripe.com/error-handling.md#payment-declined)
- [其他支付错误](https://docs.stripe.com/error-handling.md#other-payment-errors)

要区分这些类别或获取更多响应信息，请参阅[错误代码](https://docs.stripe.com/error-codes.md)、[拒付代码](https://docs.stripe.com/declines/codes.md)和 [charge outcome](https://docs.stripe.com/api/charges/object.md#charge_object-outcome)。

（要查看某个错误对象产生的扣款结果，先找到 [Payment Intent that’s involved](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和 [latest Charge it created](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    charge = client.v1.charges.retrieve(e.error.payment_intent.latest_charge)
    if charge.outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：

（要查看某个错误对象产生的扣款结果，先找到[涉及的 Payment Intent](https://docs.stripe.com/api/errors.md#errors-payment_intent) 和[它最近创建的 Charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-charges-data)。见下方的演示示例）。

#### Ruby

```ruby
require 'stripe'

def example_function(params)
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')
  begin
    client.v1.payment_intents.create(params)
  rescue Stripe::CardError => e
    if e.error.payment_intent.charges.data[0].outcome.type == 'blocked'
      puts 'Payment blocked for suspected fraud.'
    elsif e.code == 'card_declined'
      puts 'Payment declined by the issuer.'
    elsif e.code == 'expired_card'
      puts 'Card expired.'
    else
      puts 'Other card error.'
    end
  end
end
```

您可以用测试卡模拟一些常见类型的支付错误。可参考这些列表中的选项：

- [模拟因欺诈风险而被阻止的付款](https://docs.stripe.com/testing.md#fraud-prevention)
- [模拟被拒绝的付款及其他银行卡错误](https://docs.stripe.com/testing.md#declined-payments)

下面的测试代码演示了一些可能的情况。

#### 触发的错误 - 因疑似欺诈被阻止

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_radarBlock', # 这是一个测试卡，在沙盒中使用时总会因疑似欺诈而被阻止。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment blocked for suspected fraud.
```

#### 触发的错误 - 被发卡行拒绝

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_visa_chargeDeclined', # 这是一个测试卡，在沙盒中使用时总会被发卡行拒绝。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Payment declined by the issuer.
```

#### 触发的错误 - 卡已过期

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedExpiredCard', # 这是一个测试卡，在沙盒中使用时总会因过期而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Card expired.
```

#### 触发的错误 - 其他银行卡错误

#### Ruby

```ruby
example_function(
  currency: 'usd',
  amount: 2000,
  confirm: true,
  payment_method: 'pm_card_chargeDeclinedProcessingError', # 这是一个测试卡，在沙盒中使用时总会因处理错误而失败。用它及其他测试卡来测试您的集成的错误处理情况。在生产模式，您可以在这里使用一个真实的支付方式。
)
```

```
Other payment error.
```

### 付款因疑似欺诈被阻止

|  |
|  |
| **类型**                                                                                                                                                                                                       | `card_error`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **代码**                                                                                                                                                                                                       | ```dotnet
  var chargeService = new ChargeService();
  var options = new ChargeGetOptions();
  var charge = chargeService.Get(e.StripeError.PaymentIntent.LatestChargeId, options);
  charge.Outcome.Type == "blocked"
  ```

  API 版本 [2022-08-01](https://docs.stripe.com/upgrades.md#2022-08-01) 或更早版本的用户：                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | **代码** | `e.StripeError.PaymentIntent.Charges.Data[0].Outcome.Type == "blocked"` |
| **问题**                                                                                                                                                                                                       |
| Stripe 的欺诈预防系统 *Radar* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard) 阻止了付款 |
| **解决方案**                                                                                                                                                                                                     | 当您的集成正确运行的情况下可能会发生这种错误。捕获它，然后提示客户换一个支付方式。

  要减少阻止的合法付款，可尝试这些操作：

  - [优化 Radar 集成](https://docs.stripe.com/radar/optimize-risk-factors.md)，以收集更详细的信息。
  - 对于预构建进行了优化的表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  *Radar 风控团队版* (Radar for Fraud Teams helps you fine-tune how Radar operates, get fraud insights on suspicious charges, and assess your fraud management performance from a unified dashboard)客户还有以下额外的选项：

  - 要豁免特定的付款，将它添加到您的允许列表。(Radar 风控团队版)
  - 要更改您的风险容忍度，请调整您的[风险设置](https://docs.stripe.com/radar/risk-settings.md)。(Radar 风控团队版)
  - 要更改付款阻止标准，请使用[自定义规则](https://docs.stripe.com/radar/rules.md)。(Radar 风控团队版)

  您可以用[模拟欺诈的测试卡](https://docs.stripe.com/radar/testing.md)来测试您的集成的设置情况。如果您有自定义 Radar 规则，则遵从 [Radar 文档](https://docs.stripe.com/radar/testing.md)中的测试建议。 |

### 付款被发卡行拒绝

|  |
|  |
| **类型**   | `card_error`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| **代码**   | `e.StripeError.Code == "card_declined"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **问题**   | 发卡行拒绝了付款。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。它反映的是发卡行的行为，而且该行为可能是合法的。用拒付代码确定下一步如何合适。查看[拒付代码文档](https://docs.stripe.com/declines/codes.md)中各代码的正确响应方式。

  您还可以：

  - [按照建议减少发卡行拒付](https://docs.stripe.com/declines/card.md#reducing-bank-declines)。
  - 对于实施了这些建议的预构建表单元素，使用 [Payment Links](https://docs.stripe.com/payment-links.md)、[Checkout](https://docs.stripe.com/payments/checkout.md) 或 [Stripe Elements](https://docs.stripe.com/payments/elements.md)。

  用[模拟成功然后被拒绝的付款的测试卡](https://docs.stripe.com/radar/testing.md)测试您的集成处理银行拒付的情况。 |

### 其他支付错误

|  |
|  |
| **类型**   | `card_error`                                                                                         |
| **问题**   | 发生了另一个支付错误。                                                                                          |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。用错误代码确定下一步如何合适。查看[错误代码文档](https://docs.stripe.com/error-codes.md)中各代码的正确响应方式。 |

## 无效请求错误

|  |
|  |
| **类型**   | `invalid_request_error`                                                                                                                                                      |
| **问题**   | 您的 API 调用是用错误的参数、在错误的状态下，或以一种无效的方式发起的。                                                                                                                                       |
| **解决方案** | 多数情况下，问题是关于请求本身的。要么是它的参数无效，要么它不能在您的集成的当前状态下执行。
  - 参考[错误代码文档](https://docs.stripe.com/error-codes.md)中的问题详情。
  - 为方便操作，您可以按照  的链接来访问错误代码文档。
  - 如果错误中涉及到具体的参数，则用  来确定具体是哪一个。 |

## 连接错误

|  |
|  |
| **类型**   | `api_connection_error`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| **问题**   | 您的服务器与 Stripe 之间发生了网络问题。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  要知道是否成功，您可以：

  - 从 Stripe 检索相关对象并检查其状态。
  - 侦听操作成功或失败的 Webhook 通知。

  为应对连接错误，您可以：

  - 创建或更新某个对象时，使用一个 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md)。然后，如果出现连接错误，可以安全地重复请求，不会有创建第二个对象或执行两次更新的风险。用相同的等幂性密钥重复请求，直到收到明确的成功或失败信息。有关此策略的高级建议，请参阅[低级错误处理](https://docs.stripe.com/error-low-level.md#idempotency)。
  - 开启[自动重试](https://github.com/stripe/stripe-java?tab=readme-ov-file#configuring-automatic-retries)。此后，Stripe 会为您生成幂等键，并在安全时为您重复请求。

  该错误可能会掩盖其他错误。可能会发生这种情况，即解决掉连接错误后，会出现其他一些错误。检查所有方案中的错误，与您在原始请求中的操作一样。 |

## API 错误

|  |
|  |
| **类型**   | `api_error`                                                                                                                                                                                                                                                                                                                      |
| **问题**   | Stripe 这一端出错了。（这种情况比较少见。）                                                                                                                                                                                                                                                                                                        |
| **解决方案** | 将 API 调用的结果视为不确定的。也就是说，不要假定它成功了或失败了。

  依靠 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) 来获取结果信息。只要有可能，在我们解决掉一个问题时，Stripe 就会为我们创建的任何新对象触发 Webhook。

  要让您的集成在特殊情况能够具有稳健性，请查看[此关于服务器错误的高级讨论](https://docs.stripe.com/error-low-level.md#server-errors) |

## 验证错误

|  |
|  |
| **类型**   | `authentication_error`                                                                                                      |
| **问题**   | Stripe 无法用您提供的信息对您进行验证。                                                                                                     |
| **解决方案** | - 使用正确的 [API 密钥](https://docs.stripe.com/keys.md)。
  - 确保您使用的不是您[“轮换”或撤销](https://docs.stripe.com/keys.md#rolling-keys)的密钥。 |

## 幂等性错误

|  |
|  |
| **类型**   | `idempotency_error`                                                                                   |
| **问题**   | 您将 [idempotency key](https://docs.stripe.com/api/idempotent_requests.md) 用在了意外操作中，例如重放某个请求但传递的是不同的参数。 |
| **解决方案** | - 使用幂等性密钥时，只有在 API 调用完全相同时才能重用。
  - 使用 255 字符限制的幂等性密钥。                                                |

## 权限错误

|  |
|  |
| **类型**   | `permission_error`                                                                                                                                                                     |
| **问题**   | 该请求中使用的 API 密钥没有必需的权限。                                                                                                                                                                 |
| **解决方案** | - 确保您没有将[受限 API 密钥](https://docs.stripe.com/keys-best-practices.md#limit-access)用于它无法访问的服务。
  - 请勿以权限不足的[用户角色](https://docs.stripe.com/get-started/account/teams/roles.md)登入管理平台来执行操作。 |

## 速率限制错误

|  |
|  |
| **类型**   | `rate_limit_error`                                                                                                                                                                                                           |
| **问题**   | 您短时间内进行的 API 调用太多。                                                                                                                                                                                                           |
| **解决方案** | - 如果单个 API 调用触发了此错误，则等待一会，然后重试。
  - 要自动处理速率限制方面的延迟，可尝试在一个延迟后重试 API 调用，如果错误仍在，载以指数方式增加延迟。查看有关[速率限制](https://docs.stripe.com/rate-limits.md)的文档，获取进一步建议。
  - 如果您预计流量会激增，因而想要申请提高速率限制的话，请事先[联系支持](https://support.stripe.com/)。 |

## 签名验证错误

|  |
|  |
| **类型**   | `signature_verification_error`                                                                                                                                                                                                                                                             |
| **问题**   | 您使用的是 *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) [签名验证](https://docs.stripe.com/webhooks.md#verify-events)，无法验证该 Webhook 事件的可信性。                                                                             |
| **解决方案** | 当您的集成正确运行的情况下可能会发生这种错误。如果您使用的是 Webhook 签名验证，则当有第三方尝试给您发送虚假或恶意的 Webhook 时，就会发生验证失败问题，进而引发此错误。捕获它，并用 `400 Bad Request` 状态码响应。

  如果意外收到该错误（例如，用 Webhook 检测到来自于 Stripe 的错误），那么请查看[检查 Webhook 签名](https://docs.stripe.com/webhooks.md#verify-events)文档，获取更多建议。尤其要确保您使用的是正确的端点私钥。它不同于您的 API 密钥。 |
