Skip to main content

Merchant Help

 

Affirm Merchant Help

Direct API

 

Overview

Jump to the example code

This guide is for merchant developers integrating Affirm into their e-commerce site. The goal is for your business to offer Affirm as a payment option to your customers as quickly and easily as possible. After integrating Affirm, your site will:

  • Offer Affirm as payment option on the checkout page
  • Process Affirm charges in your order management system
  • Display Affirm promotional messaging

The integration steps are:

  1. Add Affirm.js
  2. Initiate a checkout
  3. Authorize the charge
  4. Create your order management functions
  5. Add Affirm promotional messaging
  6. Add the confirmation page function
  7. Test your integration
  8. Deploy to production

A front-end developer can complete step #5, adding Affirm promotional messaging, in parallel with the previous steps.

Before you begin

Before beginning integration work, you should review:

Before adding Affirm promotional messaging, your design team needs to finalize messaging placements and Affirm must approve any custom messaging.

Sandbox development

You should have received an email inviting you to create an Affirm account. Click here for information about accessing your account.

Develop and test the Affirm integration in your development environment connected to our sandbox. To use our sandbox:

After development and testing, you'll need to update your integration to use your live API keys, which you can find at https://affirm.com/dashboard/#/apikeys, and your API call link.

1. Add Affirm.js

Add the Affirm.js embed code to the head of your global page template.

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

Be sure to use your public API key from the sandbox merchant dashboard for public_api_key and a session ID variable for the optional session_id to take advantage of additional analytics.

Your global page template is the only place where you need this embed code.

2. Initiate a checkout

After adding the Affirm.js embed code, you’ll use these commands for checkout:

  • affirm.checkout({ }) creates and stores the checkout object
  • affirm.checkout.open() sends the checkout object to our Checkout API

Create a checkout object

The checkout object contains all the information about the customer order. Create the checkout object using affirm.checkout({ }).

Checkout object

The checkout object is the data payload that gets POSTed to the Affirm API to initialize checkout. 

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"
          // You can include the full name instead
          // "full" : "John 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": {
          //webhook_session_id:
          //user defined key/value pairs
          "platform_type": "your-platform-name",
          "shipping_type": "UPS Ground"
      },

      "order_id":               "JKLMO4321",

      "shipping_amount":        1000,
      "tax_amount":             500,
      "total":                  5997
  });
 
merchant
required object. Define the URLs for the two results of a checkout attempt and an optional external name.
shipping
required object. Customer contact information.
billing
optional object. Customer contact information.
items
required list. A list of item objects.
discounts
optional hash. A hash of coupon codes to discount objects. If discounts are passed, they must have a name and positive integer dollar amount.
metadata
optional object. A hash of keys to values for any metadata to be passed into checkout and stored. 'entity_name' is a protected key, and will show up in your settlement reporting.
order_id
optional string. Your internal order id. This is stored for your own future reference.
shipping_amount
required integer. The total shipping amount; Defaults to 0.
tax_amount
required integer. The total tax amount computed after all discounts have been applied; Defaults to 0.
total
required integer. The total amount of the checkout. This determines the total amount charged to the user.
Note: We only use this value for the loan total; we do not calculate the total from the checkout object line items.

Merchant object 

The merchant object contains the user_confirmation_url and user_cancel_url. The customer goes to the user_confirmation_url if the user is approved and confirms their loan. The user goes to the user_cancel_url in all other cases, such as voluntary cancel, credit decline, identity verification issue, etc. 

"merchant": {
    "user_confirmation_url":    "https://merchantsite.com/confirm",
    "user_cancel_url":          "https://merchantsite.com/cancel",
    "user_confirmation_url_action": "POST", // or "GET"
    "name":          "External Company Name"
     },
user_confirmation_url
required url. URL that the customer is sent to if they successfully complete the Affirm checkout flow. 
A checkout_token will be sent to this URL in the POST request, and that checkout_token should be used to authorize the charge before the user is redirected to the order confirmation page.
Analytics tags are other query string parameters can be persisted here as well. Read more here.
user_cancel_url
required url. URL that the customer is sent to if the customer exits the Affirm checkout flow.
This is the same if the user voluntarily cancels or closes the window before completion, or if the user is denied. You should setup the cancel_url to be the checkout payment page, and you can also append analytics tags to the URL to help you identify who you may want to reach out to about alternative payment methods or reapplying. 
Analytics tags are other query string parameters can be persisted here as well. Read more here.
user_confirmation_url_action
optional string. Accepted values are: 'GET', 'POST'. Defaults to 'POST'. Read more here.
name
optional string. If you have multiple sites operating under a single Affirm account, you can override the external company/brand name that the customer sees. This affects all references to your company name in the Affirm UI.

Contact object

The Contact object includes the shipping object, which is is required, and the billing object, which is optionalBoth objects have the same format. It also includes the Address and Name objects.

"shipping":{
        "name":{
          "first":"John",
          "last":"Doe"
          // You can include the full name instead
          // "full" : "John Doe"
        },
        "address":{
          "line1":"325 Pacific Ave",
          "city":"San Francisco",
          "state":"CA",
          "zipcode":"94112",
          "country":"USA"
        }
        "phone_number": "4151234567",
        "email": "johndoe@gmail.com"
      }
 "billing":{
        "name":{
          "first":"John",
          "last":"Doe"
          // You can include the full name instead
          // "full" : "John Doe"
        },
        "address":{
          "line1":"325 Pacific Ave",
          "city":"San Francisco",
          "state":"CA",
          "zipcode":"94112",
          "country":"USA"
        }
        "phone_number": "4151234567",
        "email": "johndoe@gmail.com"
      }
(object key name)
required string. Either 'shipping' or 'billing'. Only the 'shipping' object is required, 'billing' object is optional.
name
required object. First and last, or full name. Used to pre-populate the account sign-up form.
address
required object. Address information. Validated against public address service APIs.
phone_number
optional string. The user's phone number. Validated against the Affirm checkout API. Must be a valid, U.S.-based, mobile phone number. 
email
optional string. The user's email address.

"address":{
   "line1":"633 Folsom St",
   "city":"San Francisco",
   "state":"CA",
   "zipcode":"94107",
   "country":"USA"
}
line 1
required string. Valid U.S. street address, verified by public address service APIs.
line 2
optional string. Apartment, suite, floor, etc. 
city
required string. City name, verified by public address service APIs.
state
required string. 2-letter ISO code or full name, verified by public address service APIs.
zipcode
required string. Must match other provided address information, verified by public address service APIs.
country
optional string. If provided, must be 'US' or 'USA' (3-letter ISO code). Affirm is only available to U.S. residents.

"name":{
   "first": "John",
   "last": "Doe",
   "full": "John Doe"
}
first
required string. Can contain multiple words (for middle names).
last
required string.
full
optional string. Required if 'first' and 'last' keys are missing. String must contain at two words.

Item object

Build the Item object array dynamically based on the current cart contents. 

"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": [
            ["Apparel", "Pants"],
            ["Mens", "Apparel", "Pants"]
        ]
      },
      {
        "display_name":         "Best Drone",
        "sku":                  "DEF-456",
        "unit_price":           5999,
        "qty":                  1,
        "item_image_url":       "http://merchantsite.com/images/best-drone.jpg",
        "item_url":             "http://merchantsite.com/products/best-drone.html",
        "categories": [
            ["Electronics", "Drones"],
            ["Drones", "Best Drones"]
        ]
      }]
display_name
required object. The display name of the product.
sku
required string. The product SKU.
unit_price
required integer. The item price expressed as integer USD cents ("$100" = 10000).
qty
required integer. The item quantity expressed as an integer.
item_image_url
required string. The item's product image URL.
item_url
required string. The item's product description page URL.
categories
optional array. An array of lists that indicate the various categories that apply to this product, and the hierarchy of those category definitions. Each list in the array contains one or more comma-separated strings, with the first string being the highest-level (widest) category.

 

Metadata object

 "metadata": {
        "shipping_type":        "UPS Ground",
        "entity_name":          "internal-sub_brand-name",
        "platform_type":        "your-platform-name",
        "webhook_session_id":        "A1b2C3"
      },
shipping_type
required string. Customer contact information.
entity_name
optional string. Internal sub-brand name. 
platform_type
optional string. Name of your platform Ex: Magento.
webhook_session_id
optional string. Customer or session specific ID that's used to reconcile incoming webhooks.
mode
optional string. Value can be 'modal'. Enables modal checkout. See implementation details and restrictions here.

 

Send the checkout object

After creating the checkout object, call affirm.checkout.open();

This does the following:

  1. Sends the checkout object to our checkout API
  2. Redirects the customer to the Affirm checkout process on the affirm.com domain or shows them an Affirm modal
  3. Validates the required data in the checkout object

Error handling

A pop-up window will display any errors generated by the checkout process. For example, if there's an invalid phone number error, the customer sees this message.

You can define a callback function when the pop-up window closes. However, the callback function won’t relay any event data about the error message.

Here is an example of a callback function.

affirm.ui.ready(
    function() {
        affirm.ui.error.on("close", function(){
            console.log("Affirm modal closed");
        });
    }
);

3. Authorize the charge

After initiating the checkout, you’ll authorize the charge based on a checkout token sent to you. Refer to the customer flow to see the authorization process.

Receive the checkout token

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. Click here for more information on choosing a method.

To receive the checkout token, you’ll need to add server-side scripting that reads the HTTP request on your page. You can use any scripting language, such as PHP, ASP, Perl, Ruby, etc. For help, please contact mts@affirm.com.

While developing and testing in our sandbox, step through the checkout process in your browser to trigger the HTTP request with the checkout token.

NOTE: When testing the checkout process, enter 1234 as your verification code as we don’t send text messages from our sandbox.

Follow these steps to receive the checkout token:

  1. Initiate checkout to access the Affirm account creation screen
  2. If you have an existing account, click Sign In
  3. If you don’t have an existing account, create one with the following:
  • Any first and last name
  • An email address with a valid format
  • A valid US cell phone number (you do not need access to this number) that you will use in all subsequent checkout attempts
  • A birth date older than 18 years old
  • Any four digits
  1. Enter 1234 for the verification code and click VERIFY CODE
  2. Complete checkout flow and click CONFIRM LOAN

Authorize the charge

After completing the checkout flow and receiving the checkout token, authorize the charge. Authorizing generates a charge ID that you’ll use to reference the charge moving forward. You must authorize a charge to fully create it. A charge is not visible in the Read response, nor in the merchant dashboard until you authorize it.

After authorizing the charge and receiving a success (200) response with the authorized amount, your page (at user_confirmation_url) should:

  1. Validate that authorized amount equals the order total
  2. Redirect the customer to the order confirmation page or display an order confirmation message
  3. Store the charge ID
  4. Mark the order payment as pending

If there is an error (non-200) response when authorizing the charge or the authorized amount does not equal the order total:

  1. Notify the customer that the payment failed
  2. Redirect the customer to the payment method selection screen

Authorization request

curl https://sandbox.affirm.com/api/v2/charges
     -X POST
     -u "<public_api_key>:<private_api_key>"
     -H "Content-Type: application/json"
     -d '{"checkout_token": "<checkout_token>","order_id": "JKLM4321"}'
Options
  • Type: POST
  • Authorization: Basic
  • Content type: application/JSON
  • Data: JSON string
Data
checkout_token
required string. Unique token used to authorize a charge. Received to the user_confirmation_url
order_id
optional string. Identifies the order within the merchant's order management system that this charge corresponds to. Only returned in the response if included in the request.

Authorization response

{
   "id:ALO4-UVGR",
   "created":"2016-03-18T19:19:04Z",
   "currency":"USD",
   "amount":6100,
   "auth_hold":6100,
   "payable":0,
   "void":false,
   "expires": "2016-04-18T19:19:04Z",
   "order_id":"JKLM4321",
   "events":[
      {
         "created":"2014-03-20T14:00:33Z",
         "currency":"USD",
         "id":"UI1ZOXSXQ44QUXQL",
         "transaction_id":"TpR3Xrx8TkvuGio0",
         "type":"auth"
      }
   ],
   "details":{
      "items":{
         "sweater-a92123":{
            "sku":"sweater-a92123",
            "display_name":"Sweater",
            "qty":1,
            "item_type":"physical",
            "item_image_url":"http://placehold.it/350x150",
            "item_url":"http://placehold.it/350x150",
            "unit_price":5000
         }
      },
      "order_id":"JKLM4321",
      "shipping_amount":400,
      "tax_amount":700,
      "shipping":{
         "name":{
            "full":"John Doe"
         },
         "address":{
            "line1":"325 Pacific Ave",
            "city":"San Francisco",
            "state":"CA",
            "zipcode":"94112",
            "country":"USA"
         }
      }
      "discounts": {
        "RETURN5": {
          "discount_amount":    500,
          "discount_display_name": "Returning customer 5% discount"
        },
        "PRESDAY10": {
          "discount_amount":    1000,
          "discount_display_name": "President's Day 10% off"
        }
      }
   }
}
  • id
  • created
  • currency
  • amount
  • auth_hold
  • payable
  • void
  • order_id
  • events
    • created
    • currency
    • id
    • transaction_id
    • type
  • details
    • items
      • product sku
        • sku
        • display_name
        • qty
        • item_type
        • item_image_url
        • item_url
        • unit_price
    • order_id
    • shipping_amount
    • tax_amount
    • shipping
      • name
        • full
      • address
        • line1
        • line2
        • city
        • state
        • zipcode
        • country
    • billing
      • name
        • full
      • address
        • line1
        • line2
        • city
        • state
        • zipcode
        • country
    • discounts
      • discount code
        • discount_amount
        • discount_display_name

 

Error handling

Error HTTP status Message to display Action to take
Authorization failed 400 "There was an issue authorizing your Affirm loan. Please check out again or use a different payment method." Redirect user back to payment method selection.
Unauthorized 401 "There was an issue authorizing your Affirm loan. Please check out again or use a different payment method." Redirect user back to payment method selection.
Checkout_token expired 401 "There was an issue authorizing your Affirm loan. Please check out again or use a different payment method." Redirect user back to payment method selection.

 

4. Create your order management functions

To manage the charge through the various charge states, integrate each of these charge actions into your order management system where you fulfill orders and process payments, refunds, and cancelations.

Click here for information on viewing your API call logs.

Read Checkout

Read the checkout data and current checkout status for a specific checkout attempt. This is also useful for updating your phone or in-store agent's UI.

Request

 

curl https://sandbox.affirm.com/api/v2/checkout/CHECKOUT_ID
     -u "public_key:private_key"
URL
checkout_id
required string. Also known as the checkout_token. This ID is returned in the direct checkout API response.

 

Response

{
   "status": "opened",
   "created":"2016-03-18T19:19:04Z",
   "currency":"USD",
   "total":6100,
   "details":{
      "items":{
         "sweater-a92123":{
            "sku":"sweater-a92123",
            "display_name":"Sweater",
            "qty":1,
            "item_type":"physical",
            "item_image_url":"http://placehold.it/350x150",
            "item_url":"http://placehold.it/350x150",
            "unit_price":5000
         }
      },
      "order_id":"JKLM4321",
      "shipping_amount":400,
      "tax_amount":700,
      "shipping":{
         "name":{
            "full":"John Doe"
         },
         "address":{
            "line1":"633 Folsom St",
            "line2":"Floor 7",
            "city":"San Francisco",
            "state":"CA",
            "zipcode":"94112",
            "country":"USA"
         }
      }
      "discounts": {
        "RETURN5": {
          "discount_amount":    500,
          "discount_display_name": "Returning customer 5% discount"
        },
        "PRESDAY10": {
          "discount_amount":    1000,
          "discount_display_name": "President's Day 10% off"
        }
      }
   }
}
  • status
  • created
  • currency
  • total
  • details
    • items
      • product sku
        • sku
        • display_name
        • qty
        • item_type
        • item_image_url
        • item_url
        • unit_price
    • order_id
    • shipping_amount
    • tax_amount
    • shipping
      • name
        • full
      • address
        • line1
        • line2
        • city
        • state
        • zipcode
        • country
    • billing
      • name
        • full
      • address
        • line1
        • line2
        • city
        • state
        • zipcode
        • country
    • discounts
      • discount code
        • discount_amount
        • discount_display_name

Read Charge

Read a charge to retrieve all checkout data and the charge status associated with a specific charge. Reading charge information is useful for updating your records or order management system with the current state of a charge before performing any actions on it. It can also keep your system in sync with Affirm if your staff is manually managing loans in the merchant dashboard.

Request

Read a single charge: 

curl https://sandbox.affirm.com/api/v2/charges/CHARGE_ID
     -X GET
     -u "public_key:private_key"

 

Read multiple charges: 

curl https://sandbox.affirm.com/api/v2/charges/?limit=5&before=1234-ABCD
     -X GET
     -u "public_key:private_key"

 

URL

 

If no <charge_id> is specified,  a list of charges will be returned, and you can define how the results are paginated using the query string parameters below:

Query String
limit
optional integer. Number of charges to be included in the response
before
optional string. Returns a list of charges that were created before the given charge ID.
after
optional string. Returns a list of charges that were created after the given charge ID.

Response

{
   "id:ALO4-UVGR",
   "status": "auth",
   "created":"2016-03-18T19:19:04Z",
   "currency":"USD",
   "amount":6100,
   "auth_hold":6100,
   "payable":0,
   "void":false,
   "expires": "2016-04-18T19:19:04Z",
   "order_id":"JKLM4321",
   "events":[
      {
         "created":"2014-03-20T14:00:33Z",
         "currency":"USD",
         "id":"UI1ZOXSXQ44QUXQL",
         "transaction_id":"TpR3Xrx8TkvuGio0",
         "type":"auth"
      }
   ],
   "details":{
      "items":{
         "sweater-a92123":{
            "sku":"sweater-a92123",
            "display_name":"Sweater",
            "qty":1,
            "item_type":"physical",
            "item_image_url":"http://placehold.it/350x150",
            "item_url":"http://placehold.it/350x150",
            "unit_price":5000
         }
      },
      "order_id":"JKLM4321",
      "shipping_amount":400,
      "tax_amount":700,
      "shipping":{
         "name":{
            "full":"John Doe"
         },
         "address":{
            "line1":"633 Folsom St",
            "line2":"Floor 7",
            "city":"San Francisco",
            "state":"CA",
            "zipcode":"94112",
            "country":"USA"
         }
      }
      "discounts": {
        "RETURN5": {
          "discount_amount":    500,
          "discount_display_name": "Returning customer 5% discount"
        },
        "PRESDAY10": {
          "discount_amount":    1000,
          "discount_display_name": "President's Day 10% off"
        }
      }
   }
}
  • id
  • status
  • created
  • currency
  • amount
  • auth_hold
  • payable
  • void
  • order_id
  • events
    • created
    • currency
    • id
    • transaction_id
    • type
  • details
    • items
      • product sku
        • sku
        • display_name
        • qty
        • item_type
        • item_image_url
        • item_url
        • unit_price
    • order_id
    • shipping_amount
    • tax_amount
    • shipping
      • name
        • full
      • address
        • line1
        • line2
        • city
        • state
        • zipcode
        • country
    • billing
      • name
        • full
      • address
        • line1
        • line2
        • city
        • state
        • zipcode
        • country
    • discounts
      • discount code
        • discount_amount
        • discount_display_name

Capture

Capture the funds of an authorized charge, similar to capturing a credit card transaction. After capturing the loan:

  • We notify the customer that the loan has been captured and that their first payment is due to Affirm in 30 days
  • Affirm pays the merchant within 2-3 business days
  • Affirm can only process full or partial refunds within 120 days

Request

curl https://sandbox.affirm.com/api/v2/charges/CHARGE_ID/capture
     -X POST
     -u "(public_api_key):(private_api_key)"
     -H "Content-Type: application/json"
     -d '{"order_id": "JKLM4321", "shipping_carrier": "USPS", "shipping_confirmation": "1Z23223"}'
URL
Data
order_id
optional string. Your internal order id. This is stored for your own future reference.
shipping_carrier
optional string. The shipping carrier used to ship the items in the charge.
shipping_confirmation
optional string. The tracking number for the shipment.

Response

{
    "fee": 600,
    "created": "2016-03-18T00:03:44Z",
    "order_id": "JKLM4321",
    "currency": "USD",
    "amount": 6100,
    "type": "capture",
    "id": "O5DZHKL942503649",
    "transaction_id": "6dH0LrrgUaMD7Llc"
}
fee
integer. Portion of the captured amount that represents the merchant fee.
created
string. Timestamp for this event.
order_id
string. The order ID in your order management system.
amount
integer. Amount captured, including any fees.
type
string. Will always be "capture".
id
string. The ID for this API event.
transaction_id
string. The ID for the charge transaction.

 

Void

Void a charge to cancel an authorized charge. For example, void a charge when a customer decides to cancel their order before you fulfilled it. After voiding a charge:

  • We permanently cancel the loan, and no one can re-authorize it
  • We notify the customer about the cancelation

Request

curl https://sandbox.affirm.com/api/v2/charges/CHARGE_ID/void
     -X POST
     -u "(public_api_key):(private_api_key)"
URL

Response

{
  "type": "void",
  "id": "N5E9OXSIDJ8TKZZ9",
  "transaction_id": "G9TqohxBlRPWTGB2",
  "created": "2014-03-17T22:52:16Z",
  "order_id": "JLKM4321"
}
type
string. Always 'void'.
id
string. ID for this API event.
transaction_id
string. Transaction ID for this charge event.
created
string. Timestamp for this event.
order_id
optional string. Your internal order ID.

 

Refund

Refund a charge based on the original purchase, similar to refunding a credit card transaction. Affirm automatically calculates all interest and fees corresponding to the refunded amount. For partial refunds, you can apply any amount of refunds so long as there is a positive balance on the loan. Once a loan has been fully refunded, it can’t be reinstated.

Request

curl https://sandbox.affirm.com/api/v2/charges/CHARGE_ID/refund \
     -X POST
     -u "(public_api_key):(private_api_key)"
     -H "Content-Type: application/json"
     -d '{"amount": 50000}'
URL
Data
amount
optional integer. The amount to be refunded in USD cents ($500 = 50000). If this parameter is missing or null, then by default the entire remaining loan balance will be refunded (full refund).

Response

{
  "created": "2014-03-18T19:20:30Z",
  "fee_refunded": 1500,
  "amount": 50000,
  "type": "refund",
  "id": "OWA49MWUCA29SBVQ",
  "transaction_id": "r86zdkHONPcaiVJJ"
}
created
string. Timestamp for this event.
fee_refunded
integer. Portion of the refunded amount that is subtracted from the merchant fee.
amount
integer. Amount refunded, including any fees.
type
string. Will always be "refund".
id
string. ID for this API event.
transaction_id
string. ID for this charge event.

 

Update

Update a charge with new fulfillment or order information, such as shipment tracking number, shipping carrier, or order ID. Settlement reports associate your internal order IDs with specific Affirm charges.

Request

curl https://sandbox.affirm.com/api/v2/charges/CHARGE_ID/update
     -X POST
     -u "(public_api_key):(private_api_key)"
     -H "Content-Type: application/json"
     -d '{"order_id": "JLKM4321", "shipping_carrier": "USPS", "shipping_confirmation": "1Z23223", "shipping": {"name":{ "full": "John Doe"},"address": {"line1": "325 Pacific Ave", "state": "CA", "city": "San Francisco", "zipcode": "94111", "country": "USA"}}}'
URL
Data
order_id
optional string. Your internal order ID
shipping_carrier
optional string. The shipment carrier (e.g., "UPS").
shipping_confirmation
optional string. The shipment tracking number.
shipping
optional object. Customer shipping information.
 

Response

{  
   "created":"2016-11-30T21:07:47Z",
   "order_id":"JLKM4321",
   "shipping_confirmation":"1Z23223",
   "shipping":{  
      "name":{  
         "full":"John Doe"
      },
      "address":{  
         "city":"San Francisco",
         "state":"CA",
         "zipcode":"94111",
         "line1":"325 Pacific Ave",
         "country":"USA"
      }
   },
   "shipping_carrier":"USPS",
   "type":"update",
   "id":"EILMLQLZPGC742HO"
}
created
string. Timestamp for this event.
id
string. ID for this API event.
order_id
optional string. Your internal order ID.
shipping_carrier
optional string. Shipment carrier (e..g, 'UPS').
shipping_confirmation
optional string. Shipment tracking number. 
shipping
optional object. Customer shipping address information.
 

5. Add Affirm promotional messaging

Affirm promotional messaging components—monthly payment messaging and educational modals—show customers how they can use Affirm to finance their purchases. Properly placed promotional messaging helps drive increased AOV and conversion.

As noted earlier, a front-end developer can complete this step in parallel with the rest of the integration process. Adding Affirm promotional messaging is a required integration step, and you should complete it before testing your integration. Click here for information about adding Affirm promotional messaging.

6. Add the confirmation page function

When a customer completes their purchase, you can send their order and product information to Affirm for A/B testing, which will help you optimize your site. Send this information by adding the Confirmation Page function to your payment confirmation page. We only require orderId, total, productId, and quantity for A/B testing.

Click here for all the Confirmation Page function parameters.

affirm.analytics.trackOrderConfirmed({
    "orderId": "T12345",
    "total": 3739
}, [{
    "productId": "SKU-1234",
    "quantity": 1
}, {
    "productId": "SKU-5678",
    "quantity": 1
}]);

Required function parameters

Order object

Parameter Type Description
orderId string Your internal unique identifier representing the order. Maximum 500 characters.
total integer The total amount of the transaction, including tax and shipping, stated in USD cents (e.g., $100 = 10000).

Product object

Parameter Type Description
productId string Your internal unique identifier representing the product, such as the SKU or an internal database identifier. Maximum 500 characters.
quantity integer The quantity of the purchased product.

7. Test your integration

After completing your integration, do a thorough testing of both your front-end and back-end integration in our sandbox to ensure that both the user experience and your order management system work as expected. Click here for our recommended test plan with a downloadable checklist. However, you’ll need to tailor your testing plan to your specific systems, processes, and integration.

8. Deploy to production

Coordinate testing with Affirm

Before deploying the Affirm integration to your production site, Affirm will need to test it in your development or staging environment connected to our live environment. Contact your Client Success Manager to coordinate this test.

Connect to the live Affirm environment

  1. Retrieve your public and private API keys at https://affirm.com/dashboard/#/apikeys
  2. Update the script parameter in the Affirm.js embed code to point to our live environment at https://cdn1.affirm.com
  3. Replace the public_api_key parameter in the Affirm.js embed code with the public API key you just retrieved
  4. Update all your API calls to use the base URL, https://api.affirm.com, and to use the public and private API keys you just retrieved

Deploy to production

After you’ve connected to our live environment and we’ve tested your integration, you’re ready to deploy to your production environment and offer Affirm as a payment option to your customers.