# Report the Button Attribution Token

Once the user has placed an order in your app, include the Button Attribution Token _before_ sending the user’s checkout request to your checkout API. The Button Attribution Token can be retrieved by calling the `attributionToken` method from the Button Merchant Library.

Let’s say your user has successfully made a purchase for a pair of jeans on your client application. Before sending that purchase request to your checkout API, retrieve the Button Attribution Token using `ButtonMerchant.attributionToken` (iOS) or `ButtonMerchant.getAttributionToken` (Android).

## Code Examples

### Kotlin
```kotlin
// Obtain Attribution Token
val btnRef = ButtonMerchant.getAttributionToken(context)
```

### Java
```java
// Obtain Attribution Token
final String btnRef = ButtonMerchant.getAttributionToken(context);
```

### Swift
```swift
// Obtain Attribution Token
if let token = ButtonMerchant.attributionToken {
	// referred token is present - add to order
}
```

### Objective-C
```objectivec
NSString *token = ButtonMerchant.attributionToken;
if (token) {
  // referred token is present - add to order
}
```

Once the Button Attribution Token has been retrieved, include it when sending the user’s order request to your checkout API.

### Code Examples

### Kotlin
```kotlin
val url = URL("https://checkout-api.yourbrand.com")
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.doOutput = true

val json = JSONObject()
json.put("btn_ref", btnRef)
json.put("price", 34.90)
json.put("location", "New York")

val out = BufferedOutputStream(urlConnection.getOutputStream())
writeStream(out, json)
```

### Java
```java
URL url = new URL("https://checkout-api.yourbrand.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);

JSONObject json = new JSONObject();
json.put("btn_ref", btnRef);
json.put("price", 34.90);
json.put("location", "New York");

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out, json);
```

### Swift
```swift
// Set parameters for POST, including Attribution Token
let parameters: Parameters = [
  "token": token, // Attribution Token from previous section
  "price": 50.00,
  "location": "New York",
  "items": "Jeans"
]

// Perform POST request to your Checkout API (server)
Alamofire.request("checkout-api.yourbrand.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))
```

### Objective-C
```objectivec
NSDictionary *params = @{ "token": token, // Attribution token above
                         "price": @50.00,
                         "location": @"New York",
                         "items": @"Jeans" };

// Perform POST request to your Checkout API (server)
[AFHTTPSessionManager.manager POST:@"checkout-api.yourbrand.com"\
                               parameters:params\
                               progress:nil\
                               success:successHandler\
                               failure:errorHandler];
```

# Report a New Order

Brands should report all successful orders to the Button Order API before reporting back to the end user, and after fulfilling that order in your own inventory system. Order reporting at this time guarantees both that the order was successfully acknowledged, and that any promotions from other applications involved in this purchase are carried out.

The Button Attribution Token should have been passed to your checkout API above. In the call to Button's Order API, you can pass this value as `btn_ref`.

### cURL Example
```curl
curl https://api.usebutton.com/v1/order \ 
  -X POST \ 
  -u YOUR_API_KEY: \ 
  -H "Content-Type: application/json" \ 
  -d '{
    "total": 7000,
    "currency": "USD",
    "order_id": "1994",
    "purchase_date": "2017-07-25T08:23:52Z",
    "finalization_date": "2017-08-02T19:26:08Z",
    "btn_ref": "srctok-XXX",
    "customer": {
      "id": "mycustomer-1234",
      "email_sha256": "'`echo -n "user@example.com" | openssl dgst -sha256`'",
      "device_id": "XXXX-XXXXXX-XXX-XXXXXX",
      "is_new": true
    },
    "customer_order_id": "abcdef-123456",
    "line_items": [
            {
                "identifier": "sku-1234",
                "total": 4000,
                "amount": 2000,
                "quantity":2,
                "sku": "sku-1234",
                "upc": "400000000001",
                "category": ["Clothes"],
                "description": "T-shirts",
                "attributes":{
                    "size": "M"
                }
            },{
                "identifier": "sku-4567",
                "total": 3000,
                "amount": 3000,
                "quantity":1,
                "sku": "sku-4567",
                "upc": "400000000002",
                "category": ["Clothes"],
                "description": "Pants",
                "attributes":{
                    "size": "L"
                }
            }
    ]
  }'
```

## Order Object

All fields below, with the exception of `customer`, are required when reporting orders to Button:

| Request Parameter | Description |
| --- | --- |
| `total` | Total value of the order. Includes any discounts, if applicable. Must exclude VAT, all other taxes, surcharges and any additional costs such as delivery. This value represents the commissionable total. Must be an integer >= 0. Example: 1234 for $12.34. |
| `currency` | Three-letter ISO currency code as specified in [ISO 4217](http://www.xe.com/iso4217.php). |
| `order_id` | The Order ID unique to this order. Treated as an ASCII string. 255 character maximum. |
| `purchase_date` | ISO-8601 string representing the time the purchase was made by the user. |
| `btn_ref` | The Button Attribution Token. A URL safe string up to 255 characters. This field is optional to create an order, but is required for attribution. When testing your integration, you should send dummy Attribution Tokens to Button, in the following format: `^fakesrctok-[a-f0-9]{16}$` (e.g. `fakesrctok-abcdef0123456789`). _Note: even though this is marked as_`*optional*` _, you must provide a valid Button Attribution Token when reporting orders driven by a Button Publisher_. |
| `customer` | Information regarding the [Customer Object](https://developer.usebutton.com/guides/brands/order-api-implementation#customer-object). |
| `line_items` | An array of the [line item details](https://developer.usebutton.com/guides/brands/order-api-implementation#line-items-object) that comprise the order. |

## Customer Object

| Key | Description |
| --- | --- |
| `id` | The ID for the transacting customer in your system. |
| `email_sha256` | The SHA-256 hash of the transacting customer's _lowercase_ email, as a 64-character hex string. _Note: The value of the e-mail address must be converted to lowercase before computing the hash. The hash itself may use uppercase or lowercase hex characters_. |
| `is_new` | A Boolean value indicating whether or not the customer has previously made a purchase. Pass `true` if this is their first purchase, otherwise pass `false`. |

### Line Items Object

| Key | Description |
| --- | --- |
| `identifier` | The unique identifier for this line item, within the scope of this order. This must be unique across all line-items within the order. We suggest using the SKU or UPC of the product. |
| `sku` | The Stock Keeping Unit of the line item. A Brand-specific identifier for the line item. String with a maximum length of 255. |
| `upc` | The Universal Product Code of the line item. Also referred to as UPC-A and GTIN-12. UPC-E (8-digit) codes should be converted to 12-digit codes. String with 12 numeric digits. For industries not regularly utilizing `upc` this can be your industry’s unique product identifier. |
| `quantity` | The number of unique units represented by this line item. Must be an integer > 0. Defaults to 1. |
| `total` | The total cost of all items in this line item expressed as an integer in pennies (e.g. if 3 bananas were purchased for $3.00 each, `total` would be `900`). Must be net of any discounts or taxes and represent the value a Brand expects to commission on. |
| `category` | The category of the line item. An ordered list of strings, starting with the topmost (or most general) category. The total number of subcategories is capped at 7. Example: `['Electronics', 'Computers', 'Laptops', 'Accessories', 'Bags']`. |
| `description` | Text describing the line item. |
| `attributes` | A key/value store for strings to specify additional information about a line item. Examples of attributes are: top level / meta category identifier with a `category`; secondary category identifier with a `subcategory`; primary manufacturer of the product with a `brand`. |

# Update an Order

Accurate billing relies on accurate order reporting. In cases where initial orders are modified, it is vital to update them via the Button Orders API.

Because of this, Brands must also report all successful order updates to the Button Orders API whenever the order’s value, content, or status changes in your e-commerce backend. Similar to reporting a new order, updating orders is done via `POST` request containing the order’s updated information.

When you report an order adjustment to Button, the body should contain the **most recent / current** version of the order. To illustrate this, if an order was initially posted with two line items, and then one line item was returned, the order adjustment posted to Button should only contain one line item.

### cURL Example
```curl
curl https://api.usebutton.com/v1/order/ord-xxx \ 
  -X POST \ 
  -u my-api-key: \ 
  -H "Content-Type: application/json" \ 
  -d '{
    "total": 4000,
    "line_items": [
            {
                "identifier": "sku-1234",
                "total": 4000,
                "amount": 2000,
                "quantity":2,
                "sku": "sku-1234",
                "upc": "400000000001",
                "category": ["Clothes"],
                "description": "T-shirts",
                "attributes":{
                    "size": "M"
                }
            }
    ]
  }'
```

# Cancel an Order

Lastly, for all orders that are cancelled within your Brand’s Order Management System, you must report this to the Button Order API to avoid improper billing or commissioning to your Brand or other parties involved in the transaction. Cancellations are reported via http `DELETE` request, and are only valid for entire order cancellations. Partial order cancellations are considered an order update. Once a cancellation is made, it cannot be reversed.

### cURL Example
```curl
curl https://api.usebutton.com/v1/order/<brand-order-id> \ 
       -X DELETE \ 
       -u YOUR_API_KEY:
```

## Receiving a Response

A successful response body from the Offers API will return a `meta.status` of `ok` for all transmissions, differing only under the `object` field to reflect either the new order being registered, updated, or cancelled.

### JSON Example
```json
// Sample response:
{
  "meta": {
    "status": "ok"
  },
  "object": {
    "id": "f00b4r",
    "active": true
  }
}
```
