# Accept an Affirm payment

Learn how to accept Affirm, a buy now and pay later payment method.

> This guide helps you integrate Affirm in your online checkout flow. For in-person payments with Stripe Terminal, visit [Additional payment methods](https://docs.stripe.com/terminal/payments/additional-payment-methods.md).

# Direct API


Stripe users can use the [Payment Intents API](https://docs.stripe.com/payments/payment-intents.md)– a single integration path for creating payments using any supported method–to accept [Affirm](https://www.affirm.com/) payments from customers in the following countries:

- Canada
- United States

Accepting Affirm payments on your website consists of:

- Creating an object to track a payment
- Collecting payment method information
- Submitting the payment to Stripe for processing
- Handling the Affirm redirect and relevant webhook events

## Set up Stripe [Server-side]

First, [create a Stripe account](https://dashboard.stripe.com/register) or [sign in](https://dashboard.stripe.com/login).

Coding agents: [install the Stripe CLI](https://docs.stripe.com/cli/install) using the installation script for your operating system. Open a new terminal and run `stripe sandbox create --help` to provision an anonymous Stripe sandbox with working API keys. It doesn’t require account registration.

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

#### Ruby

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

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

## Create a PaymentIntent [Server-side]

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

First, create a `PaymentIntent` on your server and specify the amount to collect and the currency. [Enable Affirm](https://dashboard.stripe.com/settings/payment_methods) in your Dashboard. With [dynamic payment methods](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md), Stripe displays eligible payment methods to your customers automatically.

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=6000 \
  -d currency=usd \
  -d "automatic_payment_methods[enabled]=true"
```

You can also use the Payment Element and manage payment methods from the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. See [Accept a payment](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=checkout) for more details.

### 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 and submit [Client-side]

When a customer clicks to pay with Affirm, we recommend you use [Stripe.js](https://docs.stripe.com/payments/elements.md) to submit the payment to Stripe. Stripe.js 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
var stripe = Stripe(
  '<<YOUR_PUBLISHABLE_KEY>>'
);
```

Rather than sending the entire PaymentIntent object to the client, use its client secret from Step 1. 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.

**Improve payment success rates with additional details**

We recommend passing [shipping](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-shipping) and [billing](https://docs.stripe.com/api/payment_methods/create.md#create_payment_method-billing_details) details to improve conversion rates, although these aren’t required.

This integration guide suggests passing the shipping and billing information on the client after the customer selects their payment method.

If you pass these fields, the shipping address should include valid data in `line1`, `city`, `state`, `postal_code`, and `country`. Similarly, billing details must include valid data in all of `line1`, `city`, `state`, `postal_code`, and `country`.

**Confirm the PaymentIntent**

Use `stripe.confirmAffirmPayment` to handle the redirect away from your page and to complete the payment. You must also pass a [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) to this function to indicate where Stripe redirects the user after they complete the payment on the Affirm website or mobile application.

On Affirm’s payments page, the customer selects the payment options available to them. See the overview page for more details. You can’t limit or pre-select payment options on the Affirm payments page—deferring this choice to the consumer maximizes their opportunity to transact with you.

```javascript
// Redirects away from the client
stripe.confirmAffirmPayment(
  '{{PAYMENT_INTENT_CLIENT_SECRET}}',
  {
    payment_method: {
      // Billing information is optional but recommended to pass in.
      billing_details: {
        email: 'jenny@rosen.com',
        name: 'Jenny Rosen',
        address: {
          line1: '1234 Main Street',
          city: 'San Francisco',
          state: 'CA',
          country: 'US',
          postal_code: '94111',
        },
      },
    },

    // Shipping information is optional but recommended to pass in.
    shipping: {
      name: 'Jenny Rosen',
      address: {
        line1: '1234 Main Street',
        city: 'San Francisco',
        state: 'CA',
        country: 'US',
        postal_code: '94111',
      },
    },
    // Return URL where the customer should be redirected after the authorization.
    return_url: 'https://example.com/checkout/complete',
  }
).then(function(result) {
  if (result.error) {
    // Inform the customer that there was an error.
    console.log(result.error.message);
  }
});
```

When your customer submits a payment, Stripe redirects them to the `return_url` and includes the following URL query parameters. The return page can use them to get the status of the PaymentIntent so it can display the payment status to the customer.

When you specify the `return_url`, you can also append your own query parameters for use on the return page.

| Parameter                      | Description                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payment_intent`               | The unique identifier for the `PaymentIntent`.                                                                                                                                                                                                                                                                                                           |
| `payment_intent_client_secret` | The [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) of the `PaymentIntent` object. For subscription integrations, this client_secret is also exposed on the `Invoice` object through [confirmation_secret](https://docs.stripe.com/api/invoices/object.md#invoice_object-confirmation_secret) |

When the customer is redirected back to your site, you can use the `payment_intent_client_secret` to query for the PaymentIntent and display the transaction status to your customer.

## Test Affirm integration

Test your Affirm integration with your test API keys by viewing the redirect page. You can test a successful payment by authenticating the payment on the redirect page. The PaymentIntent transitions from `requires_action` to `succeeded`.

To test authentication failure, use your test API keys and view the redirect page. On the redirect page, click **X** in the top left corner. The PaymentIntent will transition from `requires_action` to `requires_payment_method`.

When redirected to the Affirm sandbox, Affirm might ask for the last four digits of your SSN. Affirm suggests using `'0000'` or `'5678'`.

## Optional: Separate authorization and capture

Affirm supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). If there’s a delay between the payment and delivering the goods to your customer, authorize the payment first and capture it later. At the point of capture, Affirm initiates the due dates on the customer’s subsequent repayments. **You must capture an authorized Affirm payment within 30 days of the authorization**. Otherwise, the authorization automatically cancels and you can no longer capture the payment. Stripe will also cancel the PaymentIntent and send a [payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) event if this happens.

> For very large order amounts, Affirm might require a down payment from the customer during authorization. If you cancel the payment or the authorization expires, Affirm refunds the down payment.

If you know that you can’t capture the payment, we recommend [canceling the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment) instead of waiting for the 30-day window to elapse. Proactively canceling the PaymentIntent immediately refunds the first installment to your customer, avoiding any confusion about charges on their statement.

### 1. Tell Stripe to authorize only

To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s Affirm account.

```bash
curl https://api.stripe.com/v1/payment_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -d "amount"=6000 \
  -d "confirm"="true" \
  -d "currency"="usd" \
  -d "capture_method"="manual" \
  // Shipping address is optional but recommended to pass in.
  -d "shipping[name]"="Jenny Rosen" \
  -d "shipping[address][line1]"="1234 Main Street" \
  -d "shipping[address][city]"="San Francisco" \
  -d "shipping[address][state]"="CA" \
  -d "shipping[address][country]"="US" \
  -d "shipping[address][postal_code]"=94111 \
  -d "payment_method_data[type]"="affirm" \
  -d "return_url"="https://www.example.com/checkout/done"
```

### 2. Capture the funds

After the authorization succeeds, the PaymentIntent [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture`. To capture the authorized funds, make a PaymentIntent [capture](https://docs.stripe.com/api/payment_intents/capture.md) request. The total authorized amount is captured by default. You can’t capture more or less than the total.

```bash
curl https://api.stripe.com/v1/payment_intents/{{PAYMENT_INTENT_ID}}/capture \
  -u <<YOUR_SECRET_KEY>>: \
```

### (Optional) Cancel the authorization

If you need to cancel an authorization, you can [cancel the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment).

## Optional: Handle the Affirm redirect manually

We recommend relying on Stripe.js to handle Affirm redirects and payments client-side with `confirmAffirmPayment`. Using Stripe.js makes it much easier to extend your integration to other payment methods. However, you can also manually redirect your customers on your server by following these steps:

- Create and confirm a [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) of type `affirm`. By specifying `payment_method_data`, we  create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent.

  You must also provide the redirect URL for your customer after they complete their payment in the `return_url` field. You can provide your own query parameters in this URL. These parameters are included in the final URL upon completing the redirect flow.

  ```bash
  curl https://api.stripe.com/v1/payment_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -d "amount"=6000 \
  -d "confirm"="true" \
  -d "currency"="usd" \
  // Shipping address is optional but recommended to pass in.
  -d "shipping[name]"="Jenny Rosen" \
  -d "shipping[address][line1]"="1234 Main Street" \
  -d "shipping[address][city]"="San Francisco" \
  -d "shipping[address][state]"="CA" \
  -d "shipping[address][country]"="US" \
  -d "shipping[address][postal_code]"=94111 \
  // Billing details are optional but recommended to pass in.
  -d "payment_method_data[billing_details][name]"="Jenny Rosen" \
  -d "payment_method_data[billing_details][email]"="jenny@example.com" \
  -d "payment_method_data[billing_details][address][line1]"="1234 Main Street" \
  -d "payment_method_data[billing_details][address][city]"="San Francisco" \
  -d "payment_method_data[billing_details][address][state]"="CA" \
  -d "payment_method_data[billing_details][address][country]"="US" \
  -d "payment_method_data[billing_details][address][postal_code]"=94111 \
  -d "payment_method_data[type]"="affirm" \
  -d "return_url"="https://example.com/checkout/complete"
  ```

  The created `PaymentIntent` has a status of `requires_action` and the type for  `next_action` is `redirect_to_url`.

  ```json
  {
    "status": "requires_action",
    "next_action": {
      "type": "redirect_to_url",
      "redirect_to_url": {
        "url": "https://hooks.stripe.com/...",
        "return_url": "https://example.com/checkout/complete"
      }
    },
    "id": "pi_xxx",
    "object": "payment_intent",
    "amount": 6000,
    "client_secret": "pi_xxx_secret_xxx",
    "confirm": "true",
    "confirmation_method": "automatic",
    "created": 1579259303,
    "currency": "usd",
    "livemode": true,
    "charges": {
      "data": [],
      "object": "list",
      "has_more": false,
      "url": "/v1/charges?payment_intent=pi_xxx"
    },
    "payment_method_types": [
      "affirm"
    ]
  }
  ```

- Redirect the customer to the URL provided in the `next_action.redirect_to_url.url` property. The code example here is approximate—the redirect method might be different in your web framework.

  When the customer finishes the payment process, they’re redirected to the `return_url` configured in step 1. The `payment_intent` and `payment_intent_client_secret` URL query parameters are included. If the `return_url` already included query parameters, they’re preserved too.

  We recommend that you [rely on webhooks](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks) to confirm the status of a payment.

## Optional: Handle post-payment events

Stripe sends a [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) event when the payment completes. Use the Dashboard, a custom *webhook* (A configurable endpoint that executes when it receives certain event notifications from an event destination), or a partner solution to receive these events and run actions, like sending an order confirmation email to your customer, logging the sale in a database, or starting a shipping workflow.

Listen for these events rather than waiting on a callback from the client. On the client, the customer could close the browser window or quit the app before the callback executes, and malicious clients could manipulate the response. Setting up your integration to listen for asynchronous events also helps you accept more payment methods in the future. Learn about the [differences between all supported payment methods](https://stripe.com/payments/payment-methods-guide).

- **Handle events manually in the Dashboard**

  Use the Dashboard to [view your payments](https://dashboard.stripe.com/payments), send email receipts, handle payouts, or retry failed payments.

- **Build a custom webhook**

  [Build a custom webhook handler](https://docs.stripe.com/events/set-up-events.md#create-event-handler) to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI.

- **Integrate a prebuilt app**

  Handle common business events, such as [automation](https://stripe.partners/?f_category=automation) or [marketing and sales](https://stripe.partners/?f_category=marketing-and-sales), by integrating a partner application.

## Optional: Display payment method messaging on your website

The [Payment Method Messaging Element](https://docs.stripe.com/js/elements_object/create_element?type=paymentMethodMessaging) is an embeddable UI component that helps your customers know which buy now, pay later payment options they have at checkout directly from your product, cart, or payment pages.

To add the Payment Method Messaging Element to your website, see [Display payment method messaging](https://docs.stripe.com/elements/payment-method-messaging.md).

## Failed payments

Affirm takes into account multiple factors when deciding to accept or decline a transaction (for example, the length of time the customer has used Affirm, the outstanding amount the customer has to repay, and the value of the current order).

Always present additional payment options such as `card` in your checkout flow, as Affirm payments have a higher rate of decline than many payment methods. In these cases, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`.

Other than a payment being declined, for an Affirm [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) with a status of `requires_action`, customers are expected to complete the payment within 12 hours after they’re redirected to the Affirm site. If no action is taken after 12 hours, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`.

In these cases, inform your customer to try again with a different payment option presented in your checkout flow.

## Error codes

These are the common error codes and corresponding recommended actions:

| Error code                               | Recommended action                                                                                                                                                                                                                 |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payment_intent_payment_attempt_failed`  | A generic failure indicating the Affirm checkout failed. Additional information might be available in the charge outcome reason.                                                                                                   |
| `payment_method_provider_decline`        | Affirm declined the customer’s payment. As a next step, the customer needs to contact Affirm for more information.                                                                                                                 |
| `payment_intent_payment_attempt_expired` | The customer never completed the payment on Affirm’s checkout page, and the payment session has expired. Stripe automatically expires PaymentIntents that aren’t successfully authorized 12 hours after initial checkout creation. |
| `payment_method_not_available`           | Affirm experienced a service related error and is unable to complete the request. Retry at a later time.                                                                                                                           |
| `amount_too_small`                       | Enter an amount within Affirm’s [default transactions limits](https://docs.stripe.com/payments/affirm.md#payment-options).                                                                                                         |
| `amount_too_large`                       | Enter an amount within Affirm’s [default transactions limits](https://docs.stripe.com/payments/affirm.md#payment-options).                                                                                                         |

Some errors might have additional insight included in the charge outcome reason:

| Outcome Reason             | What this means                                                                                                                                                                                                                                                                                                                       |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `generic_decline`          | The default outcome reason for a payment error. This usually indicates that the partner declined the payment (for example, because of insufficient funds), the bank issuer declined the charge, the transaction included a high-risk purchase, or a similar reason. Stripe might not always receive a decline reason for these cases. |
| `affirm_checkout_canceled` | Either the customer has explicitly canceled the Affirm checkout or Affirm has rejected the customer’s loan eligibility. Stripe can’t distinguish the difference between these two types of events.                                                                                                                                    |

