NAV
curl

Afterpay Online US API v1

Document Version 3.1 | Last updated: Friday, 27 April, 2018

API Endpoint

Production

https://api.afterpay.com/v1/

Sandbox

https://api.us-sandbox.afterpay.com/v1/

Direct Payment Flow

Merchant Integration Sequence

  1. Merchant calls the /v1/configuration/ endpoint to refresh Afterpay configuration.
  2. Merchant determines if the checkout should display Afterpay as a payment option.
  3. Merchant calls the /v1/orders/ endpoint to initiate the Afterpay payment process.
  4. The order token to return and stored by the merchant.
  5. Merchant executes the AfterPay.display({token: YOUR_TOKEN}); JavaScript function within the page to display the Afterpay login window.
  6. The consumer’s order is preapproved for a subsequent payment request.
  7. On the successful completion of the Afterpay pre-approval process, Afterpay will redirect back to the provided redirectConfirmUrl appending the token and a status of ‘SUCCESS’, 'CANCELLED’, 'FAILURE’ as a HTTP query parameter.
  8. If the merchant is able to fulfill the order, the merchant calls the /v1/payments endpoint to capture the payment.
  9. Afterpay finalises the consumers payment and responds with a success or failure.
  10. If the Afterpay payment was successful the merchant displays an Order success page.
  11. Should the Afterpay payment request fail, this may occur if the consumers card is declined, the merchant displays an Order failure page including failure details.

REST

The Afterpay Online API is organized around REST. The API attempts to use predictable, resource-oriented URLs and to use HTTP response codes to indicate errors.

HTTPS

The Afterpay Online API requires all communications to be secured using TLS 1.2 or greater.

Request Headers

Clients must send appropriate headers with all requests.

HTTP Headers

Field Name
Requirement
Description
Authorization required See Authentication.
Content-Type required All POST and PUT requests must declare the content-type as application/json
User-Agent recommended

All requests must include information about the Afterpay Merchant and its E-Commerce platform.

For example: AfterpayModule/1.0.0 (E-Commerce Platform/1.0.0; PHP/7.0.0; Merchant/32000) https://shop.afterpay.com

Accept recommended All requests must accept application/json or */*

Dates

All representations of dates are strings in ISO 8601 format.

You can provide date strings that are either UTC (for example, 2015-01-01T00:00:00Z) or offset from UTC to indicate time zone (for example, 2015-01-01T00:00:00-08:00 for eight hours behind UTC).

Pagination

Example request

curl https://api.us-sandbox.afterpay.com/v1/payments \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json'

Response (200)

{
  "totalResults": 213,
  "limit": 25,
  "offset": 0,
  "results": [

  ]
}

Many GET based endpoints which return a list of resources support pagination. The default limit is 25 and maximum 250. The results are in descending order by default, newest first.

Query Parameters

Parameters Type Description
limit optional number The number of results per request. 0-250, default 20.
offset optional number The position to start the results at, starting at 0. Default is 0.
totalResults optional string The total results matching the given criteria
results optional [] The matching results.

Authentication

Example request

curl "https://api.us-sandbox.afterpay.com/v1/configuration" \
  -H 'Authorization: Basic MzI6YWJjZGVmZ2g='

The Afterpay API uses Basic Authentication.

Consider the following example.

Merchant ID Secret Key
32 abcdefgh

Merchant ID is the username and Secret Key is the password. The credentials must be Base64-encoded for use in an Authorization header.

Plain Text Base64 Encoded
32:abcdefgh MzI6YWJjZGVmZ2g=
Final Header
Authorization: Basic MzI6YWJjZGVmZ2g=

Idempotent Requests

The Afterpay API supports idempotency that allows the safe retry of requests guaranteeing the operation is only performed once.

If for example a payment request fails with a network error, the request can be retried with the same requestId.

We recommend that you use UUIDs as request IDs. The resources that include a requestId will send back the same response for requests made with the same requestId for up to 24 hours.

Timeouts

Afterpay will attempt to respond to requests as soon as possible, but often latency delays are outside of our control. Where an API call is dependant on downstream banking networks the response times can be higher. As a guideline this document provides recommended network connection open timeout and read timeout values for each API resource. Resources that are dependant on banking networks will have higher timeout values. All resources that are identified as idempotent can be safely retried before the recommended timeout periods.

Models

Money object

Example money object

{
    "amount": "29.99",
    "currency": "USD"
}

Attributes

Parameter Type Description
amount string The amount should be a string representation of a decimal number, rounded to 2 decimal places.
currency string The currency is a ISO 4217 format value. Currently only USD is supported.

Discount object

Example discount object

{
    "displayName": "Returning Customer Coupon",
    "amount": {
        "amount": "29.99",
        "currency": "USD"
    }
}

Attributes

Parameter Type Description
displayName required string A display name for the discount.
amount required Money The discount amount.

Contact object

Example contact object

{
    "name": "Joe Consumer",
    "line1": "3655 Lawton St",
    "suburb": "San Francisco",
    "state": "CA",
    "postcode": "94122",
    "countryCode": "US",
    "phoneNumber": "+14155555555"
}

Attributes

Parameter Type Description
name required string Full name of contact. Maximum length is 255 characters.
line1 required string Street address. Maximum length is 128 characters.
line2 optional string Second line of the address. Maximum length is 128 characters.
suburb recommended string City or suburb name. Maximum length is 128 characters.
state required string State. Maximum length is 128 characters.
postcode required string The postal code, which is the zip code or equivalent. See Postal code. Maximum length is 128 characters.
countryCode recommended string The two-character ISO 3166-1 country code.
phoneNumber optional string The phone number, in E.123 format. Maximum length is 32 characters.

Consumer object

Example consumer object

{
    "phoneNumber": "2120000000",
    "givenNames": "Joe",
    "surname": "Consumer",
    "email": "[email protected]"
}

Attributes

Parameter Type Description
phoneNumber optional string The consumer’s phone number.
givenNames required string The consumer’s given names.
surname required string The consumer’s surname.
email required string the consumer’s email.

Shipping Courier object

Example shipping courier object

{
    "shippedAt": "2015-01-01T00:00:00Z",
    "name": "CourierPost",
    "tracking": "AA999999999AA",
    "priority": "STANDARD"
}

Attributes

Parameter Type Description
shippedAt optional string (ISO-8601) The time at which the order was shipped (ISO 8601 UTC/Zulu time).
name optional string The name of the courier.
tracking optional string The tracking number provided by the courier.
priority optional string The shipping priority. If provided, must be either “STANDARD” or “EXPRESS”.

Item object

Example item object

{
    "name": "widget",
    "sku": "12341234",
    "quantity": 1,
    "price": {
        "amount": "10.00",
        "currency": "USD"
    }
}

Attributes

Parameter Type Description
name required string Product name
sku optional string Product SKU
quantity required number The quantity of the item.
price required Money The price of the item.

Order Details object

Example order details object

{
    "consumer": {  
        "phoneNumber": "2120000000",
        "givenNames": "Joe",
        "surname": "Consumer",
        "email": "[email protected]"
    },
    "billing": {  
        "name": "Joe Consumer",
        "line1": "75 Queen St",
        "state": "New York",
        "postcode": "10001",
        "countryCode": "US",
        "phoneNumber": "2120000000"
    },
    "shipping": {  
        "name": "Joe Consumer",
        "line1": "75 Queen St",
        "state": "New York",
        "postcode": "10001",
        "countryCode": "US",
        "phoneNumber": "2120000000"
    },
    "courier" : {
        "shippedAt" : "2015-01-01T00:00:00.000Z",
        "name" : "CourierPost",
        "tracking" : "AA999999999AA",
        "priority" : "STANDARD"
    },
    "items": [  
        {
            "name": "widget",
            "sku": "12341234",
            "quantity": 1,
            "price": {
                "amount": "10.00",
                "currency": "USD"
            }
        }
    ],
    "discounts": [
        {
            "displayName": "10% Off Subtotal",
            "amount": {
                "amount": "1.00",
                "currency": "USD"
            }
        }
    ],
    "taxAmount": {  
        "amount": "2.85",
        "currency": "USD"
    },
    "shippingAmount": {  
        "amount": "10.00",
        "currency": "USD"
    }
 }

Arguments

Parameter Type Description
consumer required Consumer The consumer requesting the order.
billing optional Contact Billing address.
shipping optional Contact Shipping address.
courier optional Courier Shipping Courier details.
items optional Item[] An array of order items.
discounts optional Discount[] An array of discounts.
taxAmount optional Money The included tax amount after applying all discounts.
shippingAmount optional Money The shipping amount.

Payment Event object

Example Payment Event object

{
    "created": "2016-06-21T10:00:11Z",
    "type":"AUTHORISE"
}

Attributes

Parameter Type Description
created string (ISO-8601) The payment event creation time (ISO 8601 UTC/Zulu time).
type string The payment event type of {‘AUTHORISE’, 'CAPTURE’, VOID’}

Refund object

Example Refund object

{
    "id": "67890123",
    "refundedAt": "2015-07-10T15:01:14.123Z",
    "merchantReference": "merchantRefundId-1234",
    "amount": {  
        "amount": "10.00",
        "currency": "USD"
    }
}

Attributes

Parameter Type Description
id string The unique refund id.
refundedAt string (ISO-8601) The refund creation time (ISO 8601 UTC/Zulu time).
merchantReference string The merchant’s refund id/reference that this refund corresponds to.
amount Money The refund amount.

Service Status

Ping

This endpoint can be used to check that the service is reachable and available.

Example Ping Request

curl "https://api.us-sandbox.afterpay.com/ping" 

Response (200)

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Configuration

Get Configuration

Example Request

curl https://api.us-sandbox.afterpay.com/v1/configuration \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json'

Response (200)

[
    { 
        "type": "PAY_BY_INSTALLMENT",
        "description": "Pay over time",
        "minimumAmount": {
             "amount": "0.00",
             "currency": "USD"
         },
        "maximumAmount": {
            "amount": "500.00",
            "currency": "USD"
        }
    }
]

Retrievals a list of payment configuration that includes payment types and valid payment ranges. A request to create an Order will be rejected if the total amount is not between (inclusive) the minimumAmount and maximumAmount.

HTTP Request

GET /v1/configuration

HTTP Headers

Parameter Description
Authorization See Authentication.
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Response

Returns the configuration response. Afterpay merchant configuration does not change frequently, for this reason the configuration response will include a Cache-Control Header directives in order to minimise network round trips when using a modern HTTP client.

Parameter Type Description
[type] string Payment product type
[description] string Payment product type description
[minimumAmount] Money Minimum order amount
[maximumAmount] Money Maximum order amount

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Orders

Create Order

Example Create Order Request

curl "https://api.us-sandbox.afterpay.com/v1/orders" \
  -X POST \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json' \
  -d '{  
         "totalAmount": {  
            "amount": "21.85",
            "currency": "USD"
         },
         "consumer": {  
            "phoneNumber": "2120000000",
            "givenNames": "Joe",
            "surname": "Consumer",
            "email": "[email protected]"
         },
        "billing": {  
            "name": "Joe Consumer",
            "line1": "75 Queen St",
            "state": "New York",
            "postcode": "10001",
            "countryCode": "US",
            "phoneNumber": "2120000000"
        },
        "shipping": {  
            "name": "Joe Consumer",
            "line1": "75 Queen St",
            "state": "New York",
            "postcode": "10001",
            "countryCode": "US",
            "phoneNumber": "2120000000"
        },
        "items":[  
             {
                 "name": "widget",
                 "sku": "12341234",
                 "quantity": 1,
                 "price": {
                     "amount": "10.00",
                     "currency": "USD"
                 }
             }
         ],
         "discounts": [
            {
                "displayName": "10% Off Subtotal",
                "amount": {
                    "amount": "1.00",
                    "currency": "USD"
                }
            }
         ],
         "merchant": {
            "redirectConfirmUrl": "https://www.merchant.com/confirm",
            "redirectCancelUrl": "https://www.merchant.com/cancel"
         },
         "merchantReference": "merchantOrder-1234",
         "taxAmount": {  
            "amount": "2.85",
            "currency": "USD"
         },
         "shippingAmount": {  
             "amount": "10.00",
             "currency": "USD"
         }
      }'

Response (201)

{ "token": "q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu",
  "expires": "2016-05-10T13:14:01Z" }

This endpoint creates an order that is used to initiate the afterpay payment process. Afterpay uses the information in the order request to assist with the consumer’s pre-approval process. If the finalised merchant order changes after making an order request to afterpay then the order/payment process should be repeated.

HTTP Request

POST /v1/orders

HTTP Headers

Parameter Description
Authorization See Authentication.
Content-Type application/json
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Arguments

Parameter Type Description
totalAmount required Money Total amount for order to be charged to consumer.
consumer required Consumer The consumer requesting the order.
billing optional Contact Billing address.
shipping optional Contact Shipping address.
courier optional Courier Shipping Courier details.
description optional string A description of the order.
items optional Item[] An array of order items.
discounts optional Discount[] An array of discounts.
merchant[redirectConfirmUrl] required string (URL) The user is redirected to this URL on confirmation.
merchant[redirectCancelUrl] required string (URL) The user to redirected to this URL if the payment process is cancelled.
paymentType optional string Supported payment types ‘PAY_BY_INSTALLMENT’. Default is 'PAY_BY_INSTALLMENT’.
merchantReference optional string The merchant’s id/reference that this order corresponds to.
taxAmount optional Money The included tax amount after applying all discounts.
shippingAmount optional Money The shipping amount.

Response

Returns a token and expiry time if successful.

Parameter Type Description
expires string (ISO-8601) A date/time when the order token will expire.
token string Order token to be used to complete payment.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Get Order

Example Get Order Request

curl "https://api.us-sandbox.afterpay.com/v1/orders/q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu" \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json'

Response (200)

{  
     "token": "q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu",
     "expires": "2016-05-10T13:14:01Z",
     "totalAmount": {  
        "amount": "21.85",
        "currency": "USD"
     },
     "consumer": {  
        "phoneNumber": "2120000000",
        "givenNames": "Joe",
        "surname": "Consumer",
        "email": "[email protected]"
     },
    "billing": {  
        "name": "Joe Consumer",
        "line1": "75 Queen St",
        "state": "New York",
        "postcode": "10001",
        "countryCode": "US",
        "phoneNumber": "2120000000"
    },
    "shipping": {  
        "name": "Joe Consumer",
        "line1": "75 Queen St",
        "state": "New York",
        "postcode": "10001",
        "countryCode": "US",
        "phoneNumber": "2120000000"
    },
    "items":[  
         {
             "name": "widget",
             "sku": "12341234",
             "quantity": 1,
             "price": {
                 "amount": "10.00",
                 "currency": "USD"
             }
         }
     ],
     "discounts": [
      {
         "displayName": "10% Off Subtotal",
         "amount": {
             "amount": "1.00",
             "currency": "USD"
         }
      }
    ],
     "merchant": {
        "redirectConfirmUrl": "https://www.merchant.com/confirm",
        "redirectCancelUrl": "https://www.merchant.com/cancel"
     },
     "merchantReference": "merchantOrder-1234",
     "taxAmount": {  
         "amount": "2.85",
         "currency": "USD"
     },
     "shippingAmount": {  
          "amount": "10.00",
          "currency": "USD"
     }
}

Retrieves an individual order by token.

HTTP Request

GET /v1/orders/{token}

HTTP Headers

Parameter Description
Authorization See Authentication.
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Path Parameters

Parameter Type Description
token required string The token of the order to be retrieved.

Response

Returns the order response. Fields that were not included in the original “Create Order” request may not be included in any corresponding “Get Order” request.

Parameter Type Description
expires string (ISO-8601) A date/time when the order token will expire.
token string order token used to complete the payment.
totalAmount Money Total amount for order to be charged to consumer.
consumer Consumer The consumer requesting the order.
billing optional Contact Billing address.
shipping optional Contact Shipping address.
courier Courier Shipping Courier details.
description string A description of the order.
items Item[] An array of order items.
discounts Discount[] An array of discounts.
merchant[redirectConfirmUrl] string (URL) The user is redirected to this URL on confirmation.
merchant[redirectCancelUrl] string (URL) The user to redirected to this URL if the payment process is cancelled.
paymentType string Supported payment types 'PAY_BY_INSTALLMENT’. Default is 'PAY_BY_INSTALLMENT’.
merchantReference string The merchant’s id/reference that this order corresponds to.
taxAmount Money The included tax amount after applying all discounts.
shippingAmount Money The shipping amount.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Payments

Capture Payment

Example Capture Payment Request

curl "https://api.us-sandbox.afterpay.com/v1/payments/capture" \
  -X POST \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json' \
  -d '{  
         "token": "q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu",
         "merchantReference": "merchantOrder-1234"
      }'

Response (201)

{
     "id": "12345678",
     "token": "q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu",
     "status": "APPROVED",
     "created": "2015-07-14T10:08:14.123Z",
     "totalAmount": {  
        "amount": "21.85",
        "currency": "USD"
     },
     "merchantReference": "merchantOrder-1234",
     "refunds": [],
     "orderDetails": {
          "consumer": {  
             "phoneNumber": "0200000000",
             "givenNames": "Joe",
             "surname": "Consumer",
             "email": "[email protected]"
          },
         "billing": {  
             "name": "Joe Consumer",
             "line1": "75 Queen St",
             "state": "New York",
             "postcode": "10001",
             "countryCode": "US",
             "phoneNumber": "2120000000"
         },
         "shipping": {  
             "name": "Joe Consumer",
             "line1": "75 Queen St",
             "state": "New York",
             "postcode": "10001",
             "countryCode": "US",
             "phoneNumber": "2120000000"
         },
         "courier": {},
         "items": [  
            {
                "name": "widget",
                "sku": "12341234",
                "quantity": 1,
                "price": {
                    "amount": "10.00",
                    "currency": "USD"
                }
            }
         ],
         "discounts": [
            {
                "displayName": "10% Off Subtotal",
                "amount": {
                    "amount": "1.00",
                    "currency": "USD"
                }
            }
         ],
         "shippingAmount": {
            "amount": "10.00",
            "currency": "USD"
         },
         "taxAmount": {
            "amount": "2.85",
            "currency": "USD"
         }
     },
     "events": []
 }

This resource performs a direct payment capture and is the equivalent of capturing a credit card.

The payment resource is idempotent based on the token. The idempotent nature of the payment resources allows for the safe retry of requests, guaranteeing the operation is only performed once.

HTTP Request

POST /v1/payments/capture

HTTP Headers

Parameter Description
Authorization See Authentication.
Content-Type application/json
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Arguments

Parameter Type Description
token required string The token returned in the order creation request.
merchantReference optional string The merchant’s order id/reference that this payment corresponds to. This will update any previously provided merchantReference that might have been included in a POST /v1/orders request.

Response

Returns the payment response, the two important fields are id and status.

Parameter Type Description
id string The unique Afterpay (merchant payment) order ID
created string (ISO-8601) The payment creation time (ISO 8601 UTC/Zulu time).
status string An order status of ‘APPROVED’ or 'DECLINED’.
totalAmount Money Total amount for the order.
merchantReference string The merchant’s order id/reference that this payment corresponds to.
events Events[] One or more payment events that have occurred against the payment.
orderDetails OrderDetail The order bound to the payment.

Errors

Can return the following specific error responses

Status Code Type Description
402 declined Payment transaction declined.
402 invalid_token Cannot complete payment, expired or invalid token.
409 conflict This is a transient error that can occur when another request for the same token is currently being processed.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 70

Update Shipping Courier

Example Update Shipping Courier Request

curl "https://api.us-sandbox.afterpay.com/v1/payments/12345678/courier" \
  -X PUT \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json' \
  -d '{
          "shippedAt": "2015-01-01T00:00:00Z",
          "name": "CourierPost",
          "tracking": "AA999999999AA",
          "priority": "STANDARD"
      }'

Response (200)

    {
     "id": "12345678",
     "token": "q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu",
     "status": "APPROVED",
     "created": "2015-07-14T10:08:14.123Z",
     "totalAmount": {  
        "amount": "21.85",
        "currency": "USD"
     },
     "merchantReference": "merchantOrder-1234",
     "refunds": [],
     "orderDetails": {
          "consumer": {  
             "phoneNumber": "0200000000",
             "givenNames": "Joe",
             "surname": "Consumer",
             "email": "[email protected]"
          },
         "billing": {  
             "name": "Joe Consumer",
             "line1": "75 Queen St",
             "state": "New York",
             "postcode": "10001",
             "countryCode": "US",
             "phoneNumber": "0200000000"
         },
         "shipping": {  
             "name": "Joe Consumer",
             "line1": "75 Queen St",
             "state": "New York",
             "postcode": "10001",
             "countryCode": "US",
             "phoneNumber": "0200000000"
         },
         "courier": {
             "shippedAt" : "2015-01-01T00:00:00.000Z",
             "name" : "CourierPost",
             "tracking" : "AA999999999AA",
             "priority" : "STANDARD"
         },
         "items": [  
            {
                "name": "widget",
                "sku": "12341234",
                "quantity": 1,
                "price": {
                    "amount": "10.00",
                    "currency": "USD"
                }
            }
         ],
         "discounts": [
            {
                "displayName": "10% Off Subtotal",
                "amount": {
                    "amount": "1.00",
                    "currency": "USD"
                }
            }
         ],
         "shippingAmount": {
            "amount": "10.00",
            "currency": "USD"
         },
         "taxAmount": {
            "amount": "2.85",
            "currency": "USD"
         }
     },
     "events": []
    }

This resource updates a payment with new shipping courier information. The Afterpay customer support team utilise the shipping courier information when enquiring on the outcome of an order.

HTTP Request

PUT /v1/payments/{paymentId}/courier

HTTP Headers

Parameter Description
Authorization See Authentication.
Content-Type application/json
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Query parameters

Parameter Type Description
paymentId string The original payment ID to update

Arguments

Parameter Type Description
shippedAt optional string (ISO-8601) The time at which the order was shipped (ISO 8601 UTC/Zulu time).
name optional string The name of the shipping courier.
tracking optional string The shipping tracking number provided by the courier.
priority optional string The shipping priority. If provided, must be either “STANDARD” or “EXPRESS”.

Response

Parameter Type Description
id string The unique Afterpay generated order ID
created string (ISO-8601) The payment creation time (ISO 8601 UTC/Zulu time).
status string The status of the order.
totalAmount Money Total amount for the order.
merchantReference string The merchant’s order id/reference that this payment corresponds to.
events Events[] One or more payment events that have occurred against the payment.
orderDetails OrderDetails The order bound to the payment.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Get Payment

Example Get Payment Request

curl https://api.us-sandbox.afterpay.com/v1/payments/12345678 \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json'

Response (200)

{
     "id": "12345678",
     "token": "q54l9qd907m6iqqqlcrm5tpbjjsnfo47vsm59gqrfnd2rqefk9hu",
     "status": "APPROVED",
     "created": "2015-07-14T10:08:14.123Z",
     "totalAmount": {  
        "amount": "21.85",
        "currency": "USD"
     },
     "merchantReference": "merchantOrder-1234",
     "refunds" : [],
     "orderDetails": {
          "consumer": {  
             "phoneNumber": "0200000000",
             "givenNames": "Joe",
             "surname": "Consumer",
             "email": "[email protected]"
          },
         "billing": {  
             "name": "Joe Consumer",
             "line1": "75 Queen St",
             "state": "New York",
             "postcode": "10001",
             "countryCode": "US",
             "phoneNumber": "0200000000"
         },
         "shipping": {  
             "name": "Joe Consumer",
             "line1": "75 Queen St",
             "state": "New York",
             "postcode": "10001",
             "countryCode": "US",
             "phoneNumber": "0200000000"
         },
         "courier": {
            "shippedAt" : "2015-01-01T00:00:00.000Z",
            "name" : "CourierPost",
            "tracking" : "AA999999999AA",
            "priority" : "STANDARD"
         },
         "items": [  
            {
                "name": "widget",
                "sku": "12341234",
                "quantity": 1,
                "price": {
                    "amount": "10.00",
                    "currency": "USD"
                }
            }
         ],
         "discounts": [
            {
                "displayName": "10% Off Subtotal",
                "amount": {
                    "amount": "1.00",
                    "currency": "USD"
                }
            }
         ],
         "shippingAmount": {
            "amount": "10.00",
            "currency": "USD"
         },
         "taxAmount": {
            "amount": "2.85",
            "currency": "USD"
         }
     },
     "events" : []
 }

Retrieves an individual payment.

HTTP Request

GET /v1/payments/{paymentId}

GET /v1/payments/token:{token}

HTTP Headers

Parameter Description
Authorization See Authentication.
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Path Parameters

Parameter Type Description
paymentId required string The paymentId of the payment to be retrieved.

Response

Returns the payment response

Parameter Type Description
id string The unique Afterpay generated order ID
created string (ISO-8601) The payment creation time (ISO 8601 UTC/Zulu time).
status string The status of the order.
totalAmount Money Total amount for the order.
merchantReference string The merchant’s order id/reference that this payment corresponds to.
refunds Refund[] Zero or many refunds applied to this payment.
orderDetails OrderDetails The payment order details bound to the payment.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

List Payments

Example Get Payments Request

curl https://api.us-sandbox.afterpay.com/v1/payments?fromCreatedDate=2016-01-01&toCreatedDate=2016-06-1&limit=100&offset=0 \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json'

Response (200)

    {
        "totalResults" : 0,
        "offset" : 0,
        "limit" : 100,
        "results" : [  ]
    } 

Get a list of payments for the merchant

HTTP Request

GET /v1/payments

HTTP Headers

Parameter Description
Authorization See Authentication.
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Query Parameters

Parameter Type Description
toCreatedDate optional string (ISO-8601) Filter orders occurring before the to date/time
fromCreatedDate optional string (ISO-8601) Filter orders occurring after the from date/time
limit optional number The number of results per request. 0-250, default 20.
offset optional number The position to start the results at, starting at 0. Default is 0.
tokens optional string[] A list of order tokens. Parameter can be used multiple times to search by multiple ids.
ids optional string[] Search by payment id. Parameter can be used multiple times to search by multiple ids.
merchantReferences optional string[] Search by merchant references. Parameter can be used multiple times to search by multiple merchant references.
statuses optional string[] Search by payment status. Parameter can be used multiple times to search by multiple statuses. Valid values {APPROVED, DECLINED}
orderBy optional string The field to order the results by. Supported values are createdAt, id, amount, merchantReference, email. Default is createdAt.
ascending optional string The direction to sort the results in. Default is false.

Response

Returns the matching payments enclosed in a pagination object.

Parameter Type Description
limit number The number of results per request. 0-250, default 20.
offset number The position to start the results at, starting at 0. Default is 0.
totalResults string The total results matching the given criteria
results[payment] [] A list of matching payments.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Create Refund

This resource performs a full or partial refund.

The resource is idempotent if a unique requestId is provided.

Example Request

curl https://api.us-sandbox.afterpay.com/v1/payments/89453759874/refund \
  -X POST \
  -H 'Authorization: Basic <Base64EncodedString>' \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: <pluginOrModuleOrClientLibrary>/<pluginVersion> (<platform>/<platformVersion>; Merchant/<merchantId>)' \
  -H 'Accept: application/json' \
  -d '{
         "requestId": "61cdad2d-8e10-42ec-a97b-8712dd7a8ca9",
         "amount" : {
             "amount" : "10.00",
             "currency" : "USD"
         },
         "merchantReference" : "RF127261AD22"
     }'

Response (201)

{
     "requestId":"61cdad2d-8e10-42ec-a97b-8712dd7a8ca9",
     "amount" : {
         "amount" : "10.00",
         "currency" : "USD"
     },
     "merchantReference" : "RF127261AD22",
     "refundId": "56785678",
     "refundedAt": "2015-07-10T15:01:14.123Z"
 }

HTTP Request

POST /v1/payments/{paymentId}/refund

HTTP Headers

Parameter Description
Authorization See Authentication.
Content-Type application/json
User-Agent {pluginOrModuleOrClientLibrary}/{pluginVersion} ({platform}/{platformVersion}; Merchant/{merchantId})
Accept application/json

Query parameters

Parameter Type Description
paymentId string The original payment ID to apply the refund to

Arguments

Parameter Type Description
requestId optional string A client created unique request ID required for safe retries. It is recommended that the client generate a GUID as this ID must be globally unique to the merchant.
amount required Money The refund amount. The refund amount can not exceed the associated order.
merchantReference optional string Your internal merchant refund reference.

Response

Returns the refund response. In addition to the fields in the original request, the response includes the following:

Parameter Type Description
refundId string The refund ID is a unique numerical ID suitable for inclusion on a customer invoice.
refundedAt string (ISO-8601) A timestamp of the completed refund transaction.

Errors

Can return the following specific error responses

Status Code Error code Description
409 conflict This is a transient error that can occur when another request for the same request id is currently being processed.
412 precondition_failed The paymentId was not found or was not eligible for a refund.
422 invalid_amount The sum of all refunds for the given payment, including the new refund, exceed the initial payment amount.

Connection timeouts

Timeout Time (seconds)
Open 10
Read 20

Javascript afterpay.js

afterpay.js will load the modal for the user to make their payment with. The modal won’t show unless you supply it with the token provided by your backend.

To install afterpay.js add the following in either the head or the body. It doesn’t matter where you include it, because it’s just one line of code, which bootstraps the loading of afterpay-async.js, so it shouldn’t affect page performance.

<script src="https://portal.afterpay.com/afterpay.js" async></script>

Or this for sandbox.

<script src="https://portal.us-sandbox.afterpay.com/afterpay.js" async></script>

Then initialize the AfterPay object, passing an object containing the country code associated with the Merchant account. This will show a loading spinner until you call either display() or redirect(). You can use this time to make an ajax call to retrieve the token from your backend or just immediately call display() or redirect() if you already have the token.

AfterPay.initialize({countryCode: "US"});

Then display the modal, once you have the token.

AfterPay.display({token: YOUR_TOKEN});

Alternatively, redirect the customer in the browser. If the customer is on a mobile device, they will always be redirected, even if display() is called, for browser compatibility reasons.

AfterPay.redirect({token: YOUR_TOKEN});

A complete example for sandbox:

<html>
<head>
    <script src="https://portal.us-sandbox.afterpay.com/afterpay.js" async></script>
</head>
<body>
    Your HTML here
    <script>
    window.onload = function() {
        AfterPay.initialize({countryCode: "US"});
        AfterPay.display({token: "123456"});
    };
    </script>
</body>
</html>

JSFiddle example using sandbox: https://jsfiddle.net/wdsqvf2z/167/

Errors

Example Invalid Create Purchase Request

curl "https://example.afterpay.com/v1/example" \
  -X POST \
  -d '{
          "amount": {
              "amount": "-250.15",
              "currency": "USD"
          }
      },'

If the given parameters are incorrect, you will receive a HTTP 400 response

HTTP/1.1 400 Bad Request
Cache-Control: must-revalidate,no-cache,no-store
Content-length: 1327
Content-Type: text/html;charset=ISO-8859-1
Date: Thu, 24 Apr 2014 15:15:11 GMT
Connection: keep-alive

The above command returns JSON structured like so:

{
  "errorCode" : "invalid_object",
  "errorId" : "cf5907fbf8fbc417",
  "message" : "[totalAmount must be greater than 0.00 (was USD -250.15)]",
  "httpStatusCode" : 422
}

The Afterpay API uses conventional HTTP response codes to indicate success or failure of an API request.

In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that resulted from the provided information (e.g. a required parameter was missing), and codes in the 5xx range indicate an error with the Afterpay servers.

Response

Returns a JSON response and appropriate HTTP status code

Attributes description
httpStatusCode The HTTP status code
errorId A unique error ID.
errorCode The type of error returned. For example, invalid_object, transaction_error, or server_error.
message A human-readable message giving more details about the error. For card errors, these messages can be shown to your users.

Some examples of status codes that might be returned by the Afterpay API are below. This list is not exhaustive, and other status codes may be encountered specific to the resource.

HTTP Status Code HTTP Status Name Meaning
400 Bad Request Your request is a little wrong.
401 Unauthorized Your API key is wrong or access token is invalid.
402 Payment Required Generally returned in cases where payments are declined.
404 Not Found The specified resource could not be found.
405 Method Not Allowed You tried to access a resource with an invalid method.
406 Not Acceptable You requested a format that isn’t json.
409 Conflict You tried to perform an operation that conflicts with another operation.
410 Gone The resource requested has been removed from our servers.
412 Precondition Failed A prerequisite step that was required before calling the resource had not been performed.
422 Unprocessable Entity The request format was valid, however one or more values were incorrect.
429 Too Many Requests Too many requests may occur if an abnormal number of requests occur.
500 Internal Server Error We had a problem with our server. Try again later.
503 Service Unavailable We’re temporarially offline for maintanance. Please try again later.