---
updatedAt: 2025-11-13T14:24:22.000Z
agentTools:
  siteIndex: https://docs.affirm.com/llms.txt
  projectIndex: https://docs.affirm.com/payments/llms.txt
---

# Web (Charges)

Learn how to collect customer details on the Web.

<HTMLBlock>{`
<style>
  .dropdown-menu {
    font-family: Arial, sans-serif;
    max-width: 250px;
    margin-left: auto; /* Align to the right */
  	margin-right: 0; /* Ensure it's flush to the right */
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 10px;
    background: #4A4AF4;
    overflow: hidden; /* Ensure the container grows with content */
  }

  .dropdown-item {
    margin-bottom: 10px;
  }

  .dropdown-toggle {
    display: block;
    width: 100%;
    text-align: left;
    padding: 10px;
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
  }

  .dropdown-toggle:hover {
    background: #f0f0f0;
  }

  .dropdown-content {
    display: none;
    margin-top: 5px;
    padding: 10px;
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .dropdown-item.open .dropdown-content {
    display: block;
  }

  .flag-icon {
    width: 20px;
    height: 20px;
    margin-right: 10px;
  }

  .product-item {
    margin-bottom: 5px;
    color: black;
  }

  .product-icon {
    width: 20px;
    height: 20px;
    margin-right: 10px;
  }
  
  .country-title {
    font-family: Arial, sans-serif;
    font-size:20px;
    text-align: center;
    font-weight: bold;
    color: #ffffff;
  } 

</style>
  <div class="dropdown-menu">
    <p class="country-title" alt="Countries where this product is available">Country Availability</p>

    <div class="dropdown-item">
      <button class="dropdown-toggle" onclick="toggleDropdown(event)" alt="Drop down menu displaying the available countries for this product">
        <b>Country List</b> ⬇️
      </button>
      <div class="dropdown-content">
        <div class="product-item">
          <img src="https://files.readme.io/a4c8b3d6596d943e2b93c82cb1d432a2edaf6998667835c2e97ef4a31d460c7e-us-circle-01.png" alt="USA" class="flag-icon">
          USA
        </div>
      </div>
    </div>

  </div>
`}</HTMLBlock>

> 🚧 Switching to the Transactions API
>
> Affirm has moved to the new [Transactions API](https://docs.affirm.com/payments/docs/transactions-web). While we will continue to support Charges API, we recommend using Transactions API. You can find more information [here](https://docs.affirm.com/developers/changelog/transaction-api).

Starting a payment with Affirm on the web consists of creating a checkout form, tokenizing customer information securely, and using that `checkout_token` to initiate a charge.

This guide shows you how to include `affirm.js` and Affirm Checkout on your web page.

## 1. Set up Affirm.js

Include the following script in the head section on every page on your site. That script should always be loaded directly from the Affirm domain.

> 🚧
>
> Use only your [sandbox API keys](https://businesshub.affirm.com/hc/en-us/articles/10851385123476-Building-a-Direct-API-Integration-Step-1-Retrieving-Your-API-Keys) and domain for testing and development. This ensures that you don't accidentally modify your live transactions.

```javascript
<script>
 _affirm_config = {
   public_api_key:  "YOUR_PUBLIC_KEY",
   script:          "https://cdn1-sandbox.affirm.com/js/v2/affirm.js"
 };
(function(m,g,n,d,a,e,h,c){var b=m[n]||{},k=document.createElement(e),p=document.getElementsByTagName(e)[0],l=function(a,b,c){return function(){a[b]._.push([c,arguments])}};b[d]=l(b,d,"set");var f=b[d];b[a]={};b[a]._=[];f._=[];b._=[];b[a][h]=l(b,a,h);b[c]=function(){b._.push([h,arguments])};a=0;for(c="set add save post open empty reset on off trigger ready setProduct".split(" ");a<c.length;a++)f[c[a]]=l(b,d,c[a]);a=0;for(c=["get","token","url","items"];a<c.length;a++)f[c[a]]=function(){};k.async=
!0;k.src=g[e];p.parentNode.insertBefore(k,p);delete g[e];f(g);m[n]=b})(window,_affirm_config,"affirm","checkout","ui","script","ready","jsReady");
</script>
```

## 2. Initialize Affirm

Once you included the script above, a defined instance of **Affirm** will be created on your client. You will gain access to methods that are within the Affirm object to trigger multiples actions.

## 3. Render Affirm checkout

Checkout creation is the process in which a customer uses Affirm to pay for a purchase in your app. You can create a checkout object and launch the Affirm checkout using `affirm.checkout(checkoutObject)` and `affirm.checkout.open()` functions, which triggers our standard flow when the customer clicks on a *Complete payment* button after selecting Affirm as a payment option.

```javascript
affirm.checkout({
 
      "merchant": {
        "user_confirmation_url":    "https://merchantsite.com/confirm",
        "user_cancel_url":          "https://merchantsite.com/cancel",
        "user_confirmation_url_action": "POST",
        "name": "Your Customer-Facing Merchant Name"
      },
      "shipping":{
        "name":{
          "first":"Joe",
          "last":"Doe"
        },
        "address":{
          "line1":"633 Folsom St",
          "line2":"Floor 7",
          "city":"San Francisco",
          "state":"CA",
          "zipcode":"94107",
          "country":"USA"
        },
        "phone_number": "4153334567",
        "email": "joedoe@123fakestreet.com"
      },
      "billing":{
        "name":{
          "first":"Joe",
          "last":"Doe"
        },
        "address":{
          "line1":"633 Folsom St",
          "line2":"Floor 7",
          "city":"San Francisco",
          "state":"CA",
          "zipcode":"94107",
          "country":"USA"
        },
        "phone_number": "4153334567",
        "email": "joedoe@123fakestreet.com"
      },
      "items": [{
        "display_name":         "Awesome Pants",
        "sku":                  "ABC-123",
        "unit_price":           1999,
        "qty":                  3,
        "item_image_url":       "http://merchantsite.com/images/awesome-pants.jpg",
        "item_url":             "http://merchantsite.com/products/awesome-pants.html",
        "categories": [
            ["Home", "Bedroom"],
            ["Home", "Furniture", "Bed"]
        ]
      }
   ],
      "discounts":{
         "RETURN5":{
            "discount_amount":500,
            "discount_display_name":"Returning customer 5% discount"
        },
        "PRESDAY10":{
            "discount_amount":1000,
            "discount_display_name":"President's Day 10% off"
      }
   },
   "metadata":{
      "shipping_type":"UPS Ground",
      "mode":"modal"
   },
   "order_id":"JKLMO4321",
   "currency":"USD",  
   "financing_program":"flyus_3z6r12r",
   "shipping_amount":1000,
   "tax_amount":500,
   "total":100000
})

affirm.checkout.open()
```

> 📘 Checkout Functions and Object
>
> The above checkout functions do the following:
>
> * Sends the checkout object.
> * Redirects the customer to the Affirm checkout process on the affirm.com domain or shows them an Affirm modal.
> * Validates the required data in the checkout object.
>
> You can find more information on how to [create a checkout object](https://docs.affirm.com/payments/docs/create-a-checkout-object) via our Affirm Javascript library.

## 4. Handle callbacks

After you initiate a checkout and the customer confirms their Affirm loan, we send an HTTP request with the `checkout_token` to the URL you defined in the checkout object (user\_confirmation\_url). By default, Affirm sends this request via POST. However, you can configure the checkout object to have Affirm send this request via GET.

You choose how we send the `checkout_token` by setting the user\_confirmation\_url\_action parameter in the checkout object.

* Setting it to POST sends the `checkout_token` in the body of the HTTP request (default setting).
* Setting it to GET sends the `checkout_token` in the query string of the HTTP request.

> 🚧
>
> You can also retrieve the `checkout_id` from a javascript callback if you set the metadata `mode` to `modal`. Learn more about [modal checkout](https://docs.affirm.com/payments/docs/modal-vs-redirect-checkout).

## 5. Create a Charge

When a customer successfully completes a checkout, it is recorded as a new purchase attempt. This needs to be handled on your server-side to be fulfilled via our [Charges API](https://docs.affirm.com/payments/docs/create-a-charge).

## Error Handling

Errors generated by the checkout request are presented on the page where checkout is initiated, in the form of a pop-up modal window. Specific messaging about the source of the error is presented in this modal (e.g., "Invalid phone number").

You may define a callback function when this error modal is closed, but currently that callback does not relay any event data specific to the error message that's displayed in the modal.

Here's an example of how this event callback would be defined:

```javascript
affirm.ui.ready(
    function() {
        affirm.ui.error.on("close", function(){
            alert("Please check your contact information for accuracy.");
        });
    }
);
```