# Accept an ACH Direct Debit payment

Build a custom payment form or use Stripe Checkout to accept payments with ACH Direct Debit.

# Webview


> #### Use the Accounts v2 API to represent customers
> 
> The Accounts v2 API is generally available for Connect users, and in public preview for other Stripe users. If you’re part of the Accounts v2 preview, you need to specify a [preview version](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) in your code.
> 
> To join the Accounts v2 preview, go to [Account previews and features](https://dashboard.stripe.com/settings/previews) in your Dashboard and enable **Reusable payment methods for Global Payouts**.
> 
> For most use cases, we recommend [modeling your customers as customer-configured Account objects](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md) instead of using [Customer](https://docs.stripe.com/api/customers.md) objects.

Before you continue, review the recommended integration path for this platform.

> We recommend that you follow the [Accept a payment](https://docs.stripe.com/payments/accept-a-payment.md) guide unless you need to use manual server-side confirmation, or your integration requires presenting payment methods separately. If you’ve already integrated with Elements, see the [Payment Element migration guide](https://docs.stripe.com/payments/payment-element/migration.md).

Accepting ACH Direct Debit payments in your app’s webview consists of:

- Creating an object to track a payment
- Handling potential OAuth redirects from the webview
- Collecting payment method information
- Submitting the payment to Stripe for processing
- Verifying your customer’s bank account

> ACH Direct Debit is a [delayed notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification) payment method, which means that funds aren’t immediately available after payment. A payment typically takes 4 business days to arrive in your account.

Stripe uses the payment object, the [Payment Intent](https://docs.stripe.com/payments/payment-intents.md), to track and handle all the states of the payment until the payment completes.

Before beginning, make sure that you have access to the ACH Direct Debit payment method beta. If you haven’t already been gated into the beta, reach out to your account manager to request access.

## Overview [Client-side]

To embed Financial Connections within a WebView, begin with one of our example WebView applications:

- [Android Webview](https://github.com/stripe/stripe-android/blob/master/financial-connections-example/src/main/java/com/stripe/android/financialconnections/example/FinancialConnectionsWebviewExampleActivity.kt)
- [iOS WKWebview](https://github.com/stripe/stripe-ios/blob/master/Example/FinancialConnections%20Example/FinancialConnections%20Example/WebViewViewController.swift)

These sample applications are fully functional (on both simulators and physical devices) and contain all necessary code to set up Financial Connections and handle events delivered to your application through HTTP redirect urls.

## Set up Stripe [Server-side]

First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register).

Use our official libraries for access to the Stripe API from your application:

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

## Create or retrieve a customer [Recommended] [Server-side]

> #### Use the Accounts v2 API to represent customers
> 
> The Accounts v2 API is generally available for Connect users, and in public preview for other Stripe users. If you’re part of the Accounts v2 preview, you need to specify a [preview version](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) in your code.
> 
> To join the Accounts v2 preview, go to [Account previews and features](https://dashboard.stripe.com/settings/previews) in your Dashboard and enable **Reusable payment methods for Global Payouts**.
> 
> For most use cases, we recommend [modeling your customers as customer-configured Account objects](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md) instead of using [Customer](https://docs.stripe.com/api/customers.md) objects.

#### Accounts v2

Create a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md#v2_account_object-configuration-customer) object when your user creates an account with your business, or retrieve an existing `Account` associated with this user. Associating the ID of the `Account` object with your own internal representation of a customer enables you to retrieve and use the stored payment method details later. Include an email address on the `Account` to enable Financial Connections’ [return user optimization](https://docs.stripe.com/financial-connections/fundamentals.md#return-user-optimization).

```curl
curl -X POST https://api.stripe.com/v2/core/accounts \
  -H "Authorization: Bearer <<YOUR_SECRET_KEY>>" \
  -H "Stripe-Version: 2026-11-18.preview" \
  --json '{
    "contact_email": "{{CUSTOMER_EMAIL}}"
  }'
```

#### Customers v1

Create a *Customer* (Customer objects and some v2 Account objects represent customers of your business. They let you reuse payment methods and track multiple payments) object when your user creates an account with your business, or retrieve an existing `Customer` associated with this user. Associating the ID of the `Customer` object with your own internal representation of a customer enables you to retrieve and use the stored payment method details later. Include an email address on the `Customer` to enable Financial Connections’ [return user optimization](https://docs.stripe.com/financial-connections/fundamentals.md#return-user-optimization).

```curl
curl https://api.stripe.com/v1/customers \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d email={{CUSTOMER_EMAIL}}
```

## Create a PaymentIntent [Server-side]

A [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage.

Create a PaymentIntent on your server:

1. Specify the amount to collect and `usd` as the currency.
2. [Enable ACH Direct Debit](https://dashboard.stripe.com/settings/payment_methods) in your Dashboard. Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow.
3. Specify the [ID](https://docs.stripe.com/api/customers/object.md#customer_object-id) of the Customer.
4. Set the data [permissions](https://docs.stripe.com/financial-connections/fundamentals.md#data-permissions) parameter to include `payment_method`, as well as any other permissions required to fulfill your use case.
5. Set a `return_url` parameter, which you can use to redirect your customer back to your native app if they log into their bank with OAuth in the native browser.
| iOS                                                 | Android                                               |
| --------------------------------------------------- | ----------------------------------------------------- |
| The return_url needs to be an https universal link. | The return_url needs to be an https Android App Link. |
6. If you want to reuse the payment method in the future, provide the [setup_future_usage](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-setup_future_usage) parameter with the value of `off_session`.

The following code example demonstrates how to create a WebView-optimized [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) including the `payment_method` permission request:

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d setup_future_usage=off_session \
  -d "customer={{CUSTOMER_ID}}" \
  -d "automatic_payment_methods[enabled]=true" \
  -d "payment_method_options[us_bank_account][financial_connections][permissions][]=payment_method" \
  --data-urlencode "payment_method_options[us_bank_account][financial_connections][return_url]=https://stripe.com"
```

### Retrieve the client secret

The PaymentIntent includes a *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) that the client side uses to securely complete the payment process. You can use different approaches to pass the client secret to the client side.

#### Single-page application

Retrieve the client secret from an endpoint on your server, using the browser’s `fetch` function. This approach is best if your client side is a single-page application, particularly one built with a modern front-end framework like React. Create the server endpoint that serves the client secret:

#### Ruby

```ruby
get '/secret' do
  intent = # ... Create or retrieve the PaymentIntent
  {client_secret: intent.client_secret}.to_json
end
```

And then fetch the client secret with JavaScript on the client side:

```javascript
(async () => {
  const response = await fetch('/secret');
  const {client_secret: clientSecret} = await response.json();
  // Render the form using the clientSecret
})();
```

#### Server-side rendering

Pass the client secret to the client from your server. This approach works best if your application generates static content on the server before sending it to the browser.

Add the [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) in your checkout form. In your server-side code, retrieve the client secret from the PaymentIntent:

#### Ruby

```erb
<form id="payment-form" data-secret="<%= @intent.client_secret %>">
  <button id="submit">Submit</button>
</form>
```

```ruby
get '/checkout' do
  @intent = # ... Fetch or create the PaymentIntent
  erb :checkout
end
```

## Collect payment method details [Client-side]

When a customer clicks to pay with ACH Direct Debit, we recommend you use Stripe.js to submit the payment to Stripe. [Stripe.js](https://docs.stripe.com/payments/elements.md) is our foundational JavaScript library for building payment flows. It will automatically handle integration complexities, and enables you to easily extend your integration to other payment methods in the future.

Include the Stripe.js script on your checkout page by adding it to the `head` of your HTML file.

```html
<head>
  <title>Checkout</title>
  <script src="https://js.stripe.com/endive/stripe.js"></script>
</head>
```

Create an instance of Stripe.js with the following JavaScript on your checkout page.

```javascript
// Set your publishable key. Remember to change this to your live publishable key in production!
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = Stripe('<<YOUR_PUBLISHABLE_KEY>>');
```

Rather than sending the entire PaymentIntent object to the client, use its *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) from the previous step. This is different from your API keys that authenticate Stripe API requests.

Handle the client secret carefully because it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer.

Use [stripe.collectBankAccountForPayment](https://docs.stripe.com/js/payment_intents/collect_bank_account_for_payment)  to collect bank account details with [Financial Connections](https://docs.stripe.com/financial-connections.md), create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs), and attach that PaymentMethod to the PaymentIntent. Including the account holder’s name in the `billing_details` parameter is required to create an ACH Direct Debit PaymentMethod.

If the *merchant of record* (The legal entity responsible for facilitating the sale of products to a customer that handles any applicable regulations and liabilities, including sales taxes. In a Connect integration, it can be the platform or a connected account) is outside the US, include a complete [payment_method_data.billing_details.address](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-billing_details-address).

```javascript
// Use the form that already exists on the web page.
const paymentMethodForm = document.getElementById('payment-method-form');
const confirmationForm = document.getElementById('confirmation-form');

paymentMethodForm.addEventListener('submit', (ev) => {
  ev.preventDefault();
  const accountHolderNameField = document.getElementById('account-holder-name-field');
  const emailField = document.getElementById('email-field');

  // Calling this method will open the instant verification dialog.
  stripe.collectBankAccountForPayment({
    clientSecret: clientSecret,
    params: {
      payment_method_type: 'us_bank_account',
      payment_method_data: {
        billing_details: {
          name: accountHolderNameField.value,
          email: emailField.value,
          // Required if the merchant of record is outside the US.
          address: {
            line1: '123 Main Street',
            city: 'San Francisco',
            state: 'CA',
            postal_code: '94111',
            country: 'US',
          },
        },
      },
    },
    expand: ['payment_method'],
  })
  .then(({paymentIntent, error}) => {
    if (error) {
      console.error(error.message);
      // PaymentMethod collection failed for some reason.
    } else if (paymentIntent.status === 'requires_payment_method') {
      // Customer canceled the hosted verification modal. Present them with other
      // payment method type options.
    } else if (paymentIntent.status === 'requires_confirmation') {
      // We collected an account - possibly instantly verified, but possibly
      // manually-entered. Display payment method details and mandate text
      // to the customer and confirm the intent once they accept
      // the mandate.
      confirmationForm.show();
    }
  });
});
```

The [Financial Connections authentication flow](https://docs.stripe.com/financial-connections/fundamentals.md#authentication-flow) automatically handles bank account details collection and verification. When your customer completes the authentication flow, the *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) automatically attaches to the PaymentIntent, and creates a [Financial Connections Account](https://docs.stripe.com/api/financial_connections/accounts.md).

> Bank accounts that your customers link through manual entry and microdeposits won’t have access to additional bank account data like balances, ownership, and transactions.



To provide the best user experience on all devices, set the viewport `minimum-scale` for your page to 1 using the viewport `meta` tag.

```html
<meta name="viewport" content="width=device-width, minimum-scale=1" />
```

### Handle OAuth redirects on your mobile app

In addition to including Stripe.js on your webview-embedded page, your app might need to handle redirecting your customer to their native mobile browser for OAuth login.

> Beginning January 1, 2024, all webview-based integrations need to properly handle secure institution authentication and app redirects, or it will impact your Financial Connections authorization flow. Refer to the iOS or Android instructions above.

#### Android

On Android your app must register an [intent filter](https://developer.android.com/guide/components/intents-filters) for the previously set `return_url` in your manifest.

Read more about [handling links on Android](https://developer.android.com/training/app-links).

```xml
<activity
    android:name="...">

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <!-- Data structure to listen for "https://stripe.com" URL -->
        <data android:scheme="http" />
        <data android:scheme="https" />

        <data android:host="stripe.com" />
    </intent-filter>
</activity>
```

Register a [WebViewClient](https://developer.android.com/reference/android/webkit/WebViewClient) on your WebView. You can override `shouldOverrideUrlLoading` to open OAuth login pages on a Custom Tab / secure browser instance:

```kotlin
val webViewClient = object : WebViewClient() {
  override fun shouldOverrideUrlLoading(
      view: WebView,
      webResourceRequest: WebResourceRequest
  ): Boolean {
      val url = webResourceRequest.url.toString()
      CustomTabsIntent.Builder().build().launchUrl(view.context, Uri.parse(url))
      return true
  }
}
// ...

// register the web view client on your WebView
myWebView.webViewClient = webViewClient
```

#### iOS

On iOS, your app must be equipped to handle the WebView’s attempt to open an OAuth window. This process involves attempting to open the URL in a bank app or, if unsupported, in a secure browser instance.

When the `WKWebView` intercepts a new window request, first attempt to open the URL as a universal link. Universal links allow banking apps installed on the user’s device to directly handle their associated URLs to simplify the authentication process. This method enhances user security and convenience by leveraging the existing, trusted apps already on the device.

If opening the URL as a universal link isn’t successful—either because no supporting bank app is installed or the link isn’t recognized—the app needs to fall back to using `ASWebAuthenticationSession`. This session facilitates the authentication flow within a secure, in-app browser that ensures the safe handling of sensitive information. `ASWebAuthenticationSession` mimics the native browser, allowing users to authenticate without leaving the app.

```swift
class ViewController: UIViewController {
  private var webAuthenticationSession: ASWebAuthenticationSession?

  override func viewDidLoad() {
      super.viewDidLoad()

      // Initialize and configure your WKWebView
      let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())

      // Load your website URL
      webView.load(URLRequest(url: URL(string: "https://yourwebsite.com")!))

      // Add the web view to the view
      view.addSubview(webView)

      // Important: Assign a `uiDelegate` to handle redirects
      webView.uiDelegate = self
  }
}

extension ViewController: WKUIDelegate {
  func webView(
      _ webView: WKWebView,
      createWebViewWith configuration: WKWebViewConfiguration,
      for navigationAction: WKNavigationAction,
      windowFeatures: WKWindowFeatures
  ) -> WKWebView? {
      // Check if the link is attempting to open in a new window.
      // This is typically the case for a banking partner's authentication flow.
      let isAttemptingToOpenLinkInNewWindow = navigationAction.targetFrame?.isMainFrame != true

      if isAttemptingToOpenLinkInNewWindow, let url = navigationAction.request.url {
          // Attempt to open the URL as a universal link.
          // Universal links allow apps on the device to handle specific URLs directly.
          UIApplication.shared.open(
              url,
              options: [.universalLinksOnly: true],
              completionHandler: { [weak self] success in
                  guard let self else { return }
                  if success {
                      // App-to-app flow:
                      // The URL was successfully opened in a banking application that supports universal links.
                      print("Successfully opened the authentication URL in a bank app: \(url)")
                  } else {
                      // Fallback for when no compatible bank app is found:
                      // Create an `ASWebAuthenticationSession` to handle the authentication in a secure in-app browser
                      self.launchInSecureBrowser(url: url)
                  }
              })
      }
      return nil
  }

  private func launchInSecureBrowser(url: URL) {
    let redirectURL = URL(string: "https://yourwebsite.com")!
    let webAuthenticationSession = ASWebAuthenticationSession(
        url: url,
        callbackURLScheme: redirectURL.scheme,
        completionHandler: { redirectURL, error in
            if let error {
                if
                    (error as NSError).domain == ASWebAuthenticationSessionErrorDomain,
                    (error as NSError).code == ASWebAuthenticationSessionError.canceledLogin.rawValue
                {
                    print("User manually closed the browser by pressing 'Cancel' at the top-left corner.")
                } else {
                    print("Received an error from ASWebAuthenticationSession: \(error)")
                }
            } else {
                // IMPORTANT NOTE:
                // The browser will automatically close when
                // the `callbackURLScheme` is called.
                print("Received a redirect URL: \(redirectURL?.absoluteString ?? "null")")
            }
        }
    )
    // Store the session reference to prevent premature deallocation
    self.webAuthenticationSession = webAuthenticationSession

    // Set the presentation context provider to handle the browser's UI presentation
    webAuthenticationSession.presentationContextProvider = self

    // Use an ephemeral session to enhance privacy
    // This also disables the initial Apple alert about signing in to another app
    webAuthenticationSession.prefersEphemeralWebBrowserSession = true

    // Initiate the authentication session
    webAuthenticationSession.start()
  }
}
```

After your customer logs into their institution and authorizes access to their accounts, Stripe redirects to the `return_url` to return to your app. After returning to the app, your customer can resume and complete the bank account detail collection process.

## Collect mandate acknowledgement and submit the payment [Client-side]

Before you can initiate the payment, you must obtain authorization from your customer by displaying mandate terms for them to accept.

To be compliant with Nacha rules, you must obtain authorization from your customer before you can initiate payment by displaying mandate terms for them to accept. For more information on mandates, see [Mandates](https://docs.stripe.com/payments/ach-direct-debit.md#mandates).

When the customer accepts the mandate terms, you must confirm the PaymentIntent. Use [stripe.confirmUsBankAccountPayment](https://docs.stripe.com/js/payment_intents/confirm_us_bank_account_payment) to complete the payment when the customer submits the form.

```javascript
confirmationForm.addEventListener('submit', (ev) => {
  ev.preventDefault();
  stripe.confirmUsBankAccountPayment(clientSecret)
  .then(({paymentIntent, error}) => {
    if (error) {
      console.error(error.message);
      // The payment failed for some reason.
    } else if (paymentIntent.status === "requires_payment_method") {
      // Confirmation failed. Attempt again with a different payment method.
    } else if (paymentIntent.status === "processing") {
      // Confirmation succeeded! The account will be debited.
      // Display a message to customer.
    } else if (paymentIntent.next_action?.type === "verify_with_microdeposits") {
      // The account needs to be verified through microdeposits.
      // Display a message to consumer with next steps (consumer waits for
      // microdeposits, then enters a statement descriptor code on a page sent to them through email).
    }
  });
});
```

> [stripe.confirmUsBankAccountPayment](https://docs.stripe.com/js/payment_intents/confirm_us_bank_account_payment) might take several seconds to complete. During that time, disable resubmittals of your form and show a waiting indicator (for example, a spinner). If you receive an error, show it to the customer, re-enable the form, and hide the waiting indicator.

If successful, Stripe returns a PaymentIntent object, with one of the following possible statuses:

| Status            | Description                                                              | Next Steps                                                                                                                                                                                   |
| ----------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requires_action` | Further action is needed to complete bank account verification.          | Step 6: [Verifying bank accounts with microdeposits](https://docs.stripe.com/payments/ach-direct-debit/accept-a-payment.md?payment-ui=direct-api&platform=web#web-verify-with-microdeposits) |
| `processing`      | The bank account was instantly verified or verification isn’t necessary. | Step 7: [Confirm the PaymentIntent succeeded](https://docs.stripe.com/payments/ach-direct-debit/accept-a-payment.md?payment-ui=direct-api&platform=web#web-confirm-paymentintent-succeeded)  |

After successfully confirming the PaymentIntent, an email confirmation of the mandate and collected bank account details must be sent to your customer. Stripe handles these by default, but you can choose to [send custom notifications](https://docs.stripe.com/payments/ach-direct-debit.md#mandate-and-microdeposit-emails) if you prefer.

## Verify bank account with microdeposits [Client-side]

Not all customers can verify the bank account instantly. This step only applies if your customer has elected to opt out of the instant verification flow in the previous step.

In these cases, Stripe sends a `descriptor_code` microdeposit and might fall back to an `amount` microdeposit if any further issues arise with verifying the bank account. These deposits take 1-2 business days to appear on the customer’s online statement.

- **Descriptor code**. Stripe sends a single, 0.01 USD microdeposit to the customer’s bank account with a unique, 6-digit `descriptor_code` that starts with SM. Your customer uses this string to verify their bank account.
- **Amount**. Stripe sends two, non-unique microdeposits to the customer’s bank account, with a statement descriptor that reads `ACCTVERIFY`. Your customer uses the deposit amounts to verify their bank account.

The result of the [stripe.confirmUsBankAccountPayment](https://docs.stripe.com/js/payment_intents/confirm_us_bank_account_payment) method call in the previous step is a PaymentIntent in the `requires_action` state. The PaymentIntent contains a `next_action` field that contains some useful information for completing the verification.

```javascript
next_action: {
  type: "verify_with_microdeposits",
  verify_with_microdeposits: {
    arrival_date: 1647586800,
    hosted_verification_url: "https://payments.stripe.com/…",
    microdeposit_type: "descriptor_code"
  }
}
```

If you supplied a [billing email](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-billing_details-email), Stripe notifies your customer through this email when the deposits are expected to arrive. The email includes a link to a Stripe-hosted verification page where they can confirm the amounts of the deposits and complete verification.

> Verification attempts have a limit of ten failures for descriptor-based microdeposits and three for amount-based ones. If you exceed this limit, we can no longer verify the bank account. In addition, microdeposit verifications have a timeout of 10 days. If you can’t verify microdeposits in that time, the PaymentIntent reverts to requiring new payment method details. Clear messaging about what these microdeposits are and how you use them can help your customers avoid verification issues.

### Optional: Send custom email notifications

Optionally, you can send [custom email notifications](https://docs.stripe.com/payments/ach-direct-debit.md#mandate-and-microdeposit-emails) to your customer. After you set up custom emails, you need to specify how the customer responds to the verification email. To do so, choose *one* of the following:

- Use the Stripe-hosted verification page. To do this, use the `verify_with_microdeposits[hosted_verification_url]` URL in the [next_action](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-verify_with_microdeposits-hosted_verification_url) object to direct your customer to complete the verification process.

- If you prefer not to use the Stripe-hosted verification page, create a form on your site. Your customers then use this form to relay microdeposit amounts to you and verify the bank account using [Stripe.js](https://docs.stripe.com/js/payment_intents/verify_microdeposits_for_payment).

  - At minimum, set up the form to handle the `descriptor code` parameter, which is a 6-digit string for verification purposes.
  - Stripe also recommends that you set your form to handle the `amounts` parameter, as some banks your customers use might require it.

  Integrations only pass in the `descriptor_code` *or* `amounts`. To determine which one your integration uses, check the value for `verify_with_microdeposits[microdeposit_type]` in the `next_action` object.

```javascript
stripe.verifyMicrodepositsForPayment(clientSecret, {
  // Provide either a descriptor_code OR amounts, not both
  descriptor_code: 'SMT86W',
  amounts: [32, 45],
});
```

When the bank account is successfully verified, Stripe returns the PaymentIntent object with a `status` of `processing`, and sends a [payment_intent.processing](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.processing) *webhook* (A configurable endpoint that executes when it receives certain event notifications from an event destination) event.

Verification can fail for several reasons. The failure might happen synchronously as a direct error response, or asynchronously through a [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.failed) webhook event (shown in the following examples).

#### Synchronous Error

```json
{
  "error": {
    "code": "payment_method_microdeposit_verification_amounts_mismatch",
    "message": "The amounts provided do not match the amounts that were sent to the bank account. You have {attempts_remaining} verification attempts remaining.",
    "type": "invalid_request_error"
  }
}
```

#### Webhook Event

```javascript
{
  "object": {
    "id": "pi_1234",
    "object": "payment_intent",
    "customer": "cus_0246",
    ...
    "last_payment_error": {
      "code": "payment_method_microdeposit_verification_attempts_exceeded",
      "message": "You have exceeded the number of allowed verification attempts.",
    },
    ...
    "status": "requires_payment_method"
  }
}
```

| Error Code                                                   | Synchronous or Asynchronous                            | Message                                                                                                                                         | Status change                                                           |
| ------------------------------------------------------------ | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `payment_method_microdeposit_failed`                         | Synchronously, or asynchronously through webhook event | Microdeposits failed. Please check the account, institution and transit numbers provided                                                        | `status` is `requires_payment_method`, and `last_payment_error` is set. |
| `payment_method_microdeposit_verification_amounts_mismatch`  | Synchronously                                          | The amounts provided don’t match the amounts that were sent to the bank account. You have {attempts_remaining} verification attempts remaining. | Unchanged                                                               |
| `payment_method_microdeposit_verification_attempts_exceeded` | Synchronously, or asynchronously through webhook event | Exceeded number of allowed verification attempts                                                                                                | `status` is `requires_payment_method`, and `last_payment_error` is set. |
| `payment_method_microdeposit_verification_timeout`           | Asynchronously through webhook event                   | Microdeposit timeout. Customer hasn’t verified their bank account within the required 10 day period.                                            | `status` is `requires_payment_method`, and `last_payment_error` is set. |

## Confirm the PaymentIntent succeeded [Server-side]

ACH Direct Debit is a [delayed notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification) payment method. This means that it can take up to four business days to receive notification of the success or failure of a payment after you initiate a debit from your customer’s account.

The PaymentIntent you create initially has a status of `processing`. After the payment has succeeded, the PaymentIntent status is updated from `processing` to `succeeded`.

We recommend using [webhooks](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks) to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the charge has succeeded and to notify the customer that the payment is complete. You can also view events on the [Stripe Dashboard](https://dashboard.stripe.com/events).

#### PaymentIntent events

The following events are sent when the PaymentIntent status is updated:

| Event                           | Description                                                                                     | Next Step                                                                                                                                                                                                                                                                                     |
| ------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payment_intent.processing`     | The customer’s payment was submitted to Stripe successfully.                                    | Wait for the initiated payment to succeed or fail.                                                                                                                                                                                                                                            |
| `payment_intent.succeeded`      | The customer’s payment succeeded.                                                               | Fulfill the goods or services that were purchased.                                                                                                                                                                                                                                            |
| `payment_intent.payment_failed` | The customer’s payment was declined. This can also apply to a failed microdeposit verification. | Contact the customer through email or push notification and request another payment method. If the webhook was sent due to a failed microdeposit verification, the user needs to enter in their bank account details again and a new set of microdeposits will be deposited in their account. |

#### Charge events

You can also use additional Charge webhooks to track the payment’s status. Upon receiving the `charge.updated` webhook, the payment is no longer cancellable.

The following events are sent when the Charge status is updated:

| Event              | Description                                                                                                                                     | Next Step                                                                         |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `charge.pending`   | The customer’s payment was created successfully.                                                                                                | Wait for the initiated payment to be processed.                                   |
| `charge.updated`   | The customer’s payment was updated. It can be emitted when a new balance transaction was created, a charge description or metadata got updated. | Wait for the initiated payment to succeed or fail.                                |
| `charge.succeeded` | The customer’s payment succeeded and the funds are available in your balance.                                                                   | Fulfill the goods or services that were purchased.                                |
| `charge.failed`    | The customer’s payment failed.                                                                                                                  | Check the charge’s failure_code and failure_message to determine further actions. |

## Test your integration

Learn how to test scenarios with instant verifications using [Financial Connections](https://docs.stripe.com/financial-connections/testing.md#web-how-to-use-test-accounts).

### Send transaction emails in a sandbox

After you collect the bank account details and accept a mandate, send the mandate confirmation and microdeposit verification emails in a *sandbox* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes).

If your domain is **{domain}** and your username is **{username}**, use the following email format to send test transaction emails: **{username}+test\_email@{domain}**.

For example, if your domain is **example.com** and your username is **info**, use the format **info+test\_email@example.com** for testing ACH Direct Debit payments. This format ensures that emails route correctly. If you don’t include the **+test\_email** suffix, Stripe won’t send the email.

> You must [set up your Stripe account](https://docs.stripe.com/get-started/account/set-up.md) before you can trigger these emails while testing.

### Test account numbers

Stripe provides several test account numbers and corresponding tokens you can use to make sure your integration for manually-entered bank accounts is ready for production.

| Account number | Token                                  | Routing number | Behavior                                                                                                                                              |
| -------------- | -------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `000123456789` | `pm_usBankAccount_success`             | `110000000`    | The payment succeeds.                                                                                                                                 |
| `000111111113` | `pm_usBankAccount_accountClosed`       | `110000000`    | The payment fails because the account is closed.                                                                                                      |
| `000000004954` | `pm_usBankAccount_riskLevelHighest`    | `110000000`    | The payment is blocked by Radar due to a [high risk of fraud](https://docs.stripe.com/radar/transaction-risk-prevention.md#high-risk).                |
| `000111111116` | `pm_usBankAccount_noAccount`           | `110000000`    | The payment fails because no account is found.                                                                                                        |
| `000222222227` | `pm_usBankAccount_insufficientFunds`   | `110000000`    | The payment fails due to insufficient funds.                                                                                                          |
| `000333333335` | `pm_usBankAccount_debitNotAuthorized`  | `110000000`    | The payment fails because debits aren’t authorized.                                                                                                   |
| `000444444440` | `pm_usBankAccount_invalidCurrency`     | `110000000`    | The payment fails due to invalid currency.                                                                                                            |
| `000666666661` | `pm_usBankAccount_failMicrodeposits`   | `110000000`    | The payment fails to send microdeposits.                                                                                                              |
| `000555555559` | `pm_usBankAccount_dispute`             | `110000000`    | The payment triggers a dispute.                                                                                                                       |
| `000000000009` | `pm_usBankAccount_processing`          | `110000000`    | The payment stays in processing indefinitely. Useful for testing [PaymentIntent cancellation](https://docs.stripe.com/api/payment_intents/cancel.md). |
| `000777777771` | `pm_usBankAccount_weeklyLimitExceeded` | `110000000`    | The payment fails due to payment amount causing the account to exceed its weekly payment volume limit.                                                |
| `000888888885` |                                        | `110000000`    | The payment fails because of a deactivated [tokenized account number](https://docs.stripe.com/financial-connections/tokenized-account-numbers.md).    |

Before test transactions can complete, you need to verify all test accounts that automatically succeed or fail the payment. To do so, use the test microdeposit amounts or descriptor codes in the following table.

### Test microdeposit amounts and descriptor codes

To mimic different scenarios, use these microdeposit amounts or 0.01 descriptor code values.

| Microdeposit values | 0.01 descriptor code values | Scenario                                                         |
| ------------------- | --------------------------- | ---------------------------------------------------------------- |
| `32` and `45`       | SM11AA                      | Simulates verifying the account.                                 |
| `10` and `11`       | SM33CC                      | Simulates exceeding the number of allowed verification attempts. |
| `40` and `41`       | SM44DD                      | Simulates a microdeposit timeout.                                |

### Test settlement behavior

Test transactions settle instantly and are added to your available test balance. This behavior differs from live mode, where transactions can take [multiple days](https://docs.stripe.com/payments/ach-direct-debit.md#timing) to settle in your available balance.

## Optional: Instant only verification [Server-side]

By default, US bank account payments allows your customers to use instant bank account verification or microdeposits. You can optionally require instant bank account verification only, using the [verification_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-us_bank_account-verification_method) parameter when you create the PaymentIntent.

#### Accounts v2

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d setup_future_usage=off_session \
  -d "customer_account={{CUSTOMER_ACCOUNT_ID}}" \
  -d "automatic_payment_methods[enabled]=true" \
  -d "payment_method_options[us_bank_account][verification_method]=instant" \
  -d "payment_method_options[us_bank_account][financial_connections][permissions][]=payment_method" \
  -d "payment_method_options[us_bank_account][financial_connections][permissions][]=balances"
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d setup_future_usage=off_session \
  -d "customer={{CUSTOMER_ID}}" \
  -d "automatic_payment_methods[enabled]=true" \
  -d "payment_method_options[us_bank_account][verification_method]=instant" \
  -d "payment_method_options[us_bank_account][financial_connections][permissions][]=payment_method" \
  -d "payment_method_options[us_bank_account][financial_connections][permissions][]=balances"
```

This ensures that you don’t need to handle microdeposit verification. However, if instant verification fails, the PaymentIntent’s status is `requires_payment_method`, indicating a failure to instantly verify a bank account for your customer.

## Optional: Microdeposit only verification [Server-side]

By default, US bank account payments allow your customers to use instant bank account verification or microdeposits. You can optionally require microdeposit verification only using the [verification_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-us_bank_account-verification_method) parameter when you create the PaymentIntent.

> If using a custom payment form, you must build your own UI to collect bank account details. If you disable Stripe microdeposit emails, you must build your own UI for your customer to confirm the microdeposit code or amount.

#### Accounts v2

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d setup_future_usage=off_session \
  -d "customer_account={{CUSTOMER_ACCOUNT_ID}}" \
  -d "automatic_payment_methods[enabled]=true" \
  -d "payment_method_options[us_bank_account][verification_method]=microdeposits"
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d setup_future_usage=off_session \
  -d "customer={{CUSTOMER_ID}}" \
  -d "automatic_payment_methods[enabled]=true" \
  -d "payment_method_options[us_bank_account][verification_method]=microdeposits"
```

You must then collect your customer’s bank account with your own form and call [stripe.confirmUsBankAccountPayment](https://docs.stripe.com/js/payment_intents/confirm_us_bank_account_payment) with those details to complete the PaymentIntent.

```javascript
var form = document.getElementById('payment-form');
var accountholderName = document.getElementById('accountholder-name');
var email = document.getElementById('email');
var accountNumber = document.getElementById('account-number');
var routingNumber = document.getElementById('routing-number');
var accountHolderType= document.getElementById('account-holder-type');

var submitButton = document.getElementById('submit-button');
var clientSecret = submitButton.dataset.secret;

form.addEventListener('submit', function(event) {
  event.preventDefault();

  stripe.confirmUsBankAccountPayment(clientSecret, {
    payment_method: {
      billing_details: {
        name: accountholderName.value,
        email: email.value,
      },
      us_bank_account: {
        account_number: accountNumber.value,
        routing_number: routingNumber.value,
        account_holder_type: accountHolderType.value, // 'individual' or 'company'
      },
    },
  })
  .then(({paymentIntent, error}) => {
    if (error) {
      // Inform the customer that there was an error.
      console.log(error.message);
    } else {
      // Handle next step based on the intent's status.
      console.log("PaymentIntent ID: " + paymentIntent.id);
      console.log("PaymentIntent status: " + paymentIntent.status);
    }
  });
});
```

## Optional: Retrieve balance information on a Financial Connections bank account

To help prevent payment failures due to insufficient funds, we recommend that you check a customer’s balance before initiating a payment. With your user’s permission, you can use Financial Connections to [access account balances](https://docs.stripe.com/financial-connections/balances.md).

## Optional: Payment Reference

The payment reference number is a bank-generated value that allows the bank account owner to use their bank to locate funds. When the payment succeeds, Stripe provides the payment reference number in the Dashboard and inside the [Charge object](https://docs.stripe.com/api/charges/object.md).

| Charge State | Payment Reference Value                  |
| ------------ | ---------------------------------------- |
| Pending      | Unavailable                              |
| Failed       | Unavailable                              |
| Succeeded    | Available (for example, 091000015001234) |

In addition, when you receive the `charge.succeeded` webhook, view the content of `payment_method_details` to locate the [payment_reference](https://docs.stripe.com/api/charges/object.md#charge_object-payment_method_details-us_bank_account-payment_reference).

The following example event shows the rendering of a successful ACH payment with a payment reference number.

#### charge-succeeded

```json
{
  "id": "{{EVENT_ID}}",
  "object": "event",
  // omitted some fields in the example
  "type": "charge.succeeded",
  "data": {
    "object": {
      "id": "{{PAYMENT_ID}}",
      "object": "charge",
      //...
    "paid": true,
    "payment_intent": "{{PAYMENT_INTENT_ID}}",
    "payment_method": "{{PAYMENT_METHOD_ID}}",
    "payment_method_details": {
      "type": "us_bank_account",
      "us_bank_account": {
        "account_holder_type": "individual",
        "account_type": "checking",
        "bank_name": "TEST BANK",
        "fingerprint": "Ih3foEnRvLXShyfB",
        "last4": "1000",
        "payment_reference": "091000015001234",
        "routing_number": "110000000"
        }
      }
      // ...
    }
  }
}
```

View the contents of the `destination_details` to locate the [refund reference](https://docs.stripe.com/api/refunds/object.md#refund_object-destination_details-us_bank_transfer-reference) associated with the refunded ACH payments.

The following example event shows the rendering of a successful ACH refund with a refund reference number. Learn more about [refunds](https://docs.stripe.com/refunds.md).

#### charge-refund-updated

```json
{
  "id": "{{EVENT_ID}}",
  "object": "event",
  "type": "charge.refund.updated",
  "data": {
    "object": {
      "id": "{{REFUND_ID}}",
      "object": "refund",
      //...
    "payment_intent": "{{PAYMENT_INTENT_ID}}",
    "destination_details": {
      "type": "us_bank_transfer",
      "us_bank_transfer": {
        "reference": "091000015001111",
        "reference_status": "available"
        }
      }
      // ...
    }
  }
}
```

## See also

- [Save ACH Direct Debit pre-authorized debit details for future payments](https://docs.stripe.com/payments/ach-direct-debit/set-up-payment.md)

