# /pre-orders

### [Authentication](#authentication)

As well as including your store's public API key as an `api_key` query parameter in all requests, this endpoint requires a few other parameters:&#x20;

<table><thead><tr><th width="200.48046875">Query param</th><th>Where to find it</th></tr></thead><tbody><tr><td><code>api_key</code></td><td>This is available on the <a href="https://www.purpledotprice.com/merchant-portal/integration">integration</a> page on your merchant portal under 'Public API Key'</td></tr><tr><td><code>email</code></td><td>This is the email of the shopper you're looking up the info for</td></tr><tr><td><code>timestamp</code></td><td>This is the browser timestamp in the epoch format</td></tr><tr><td><code>token</code></td><td>This is the security signature that Purple Dot uses to verify the authenticity of the request. This is generated by hashing the <code>email</code> and the <code>timestamp</code> against the 'Shared secret' found on the <a href="https://www.purpledotprice.com/merchant-portal/integration">integration</a> page. More on how to generate this token <a href="#how-to-generate-the-token">below</a>.</td></tr></tbody></table>

#### How to generate the `token`

Purple Dot expects a SHA-256 hash of the `email` and the `timestamp` in the following format:

&#x20;`<email>:<timestamp>`

This allows us to verify the integrity and authenticity of the request by having it securely assigned using a shared secret. The generated token will only be valid for 10 seconds within the timestamp; to make the same API call for updated data, a new token must be generated.

You can generate the token within a Shopify theme in a `.liquid` file as shown below:

```liquid
{% assign timestamp = 'now' | date: '%s' %}
{% assign token_value = customer.email | append: ':' | append: timestamp %}
{% assign token = token_value | hmac_sha256: 'YOUR_SHARED_SECRET' %}

<script>
  window.PurpleDotAPICredentials = {
    timestamp: "{{ timestamp }}",
    email: "{{ customer.email }}",
    token: "{{ token }}"
  }
</script>
```

To generate the token using Javascipt and the native [browser `crypto` APIs](https://developer.mozilla.org/en-US/docs/Web/API/Crypto), you can add the following `<script>` to an HTML file:

```javascript
<script>
  async function generateHmacSha256(secret, data) {
    const encoder = new TextEncoder();

    const key = await crypto.subtle.importKey(
      "raw",
      encoder.encode(secret),
      { name: "HMAC", hash: "SHA-256" },
      false,
      ["sign"]
    );

    const signature = await crypto.subtle.sign(
      "HMAC",
      key,
      encoder.encode(data)
    );

    const hexString = Array.from(new Uint8Array(signature), (byte) =>
      byte.toString(16).padStart(2, "0")
    ).join("");

    return hexString;
  }

  async function fetchPreordersForEmail(email) {
    const apiKey = 'YOUR_API_KEY';
    const sharedSecret = 'YOUR_SHARED_SECRET';

    const timestamp = Math.floor(Date.now() / 1000); // convert milliseconds to seconds
    const tokenData = `${email}:${timestamp}`;
    const token = await generateHmacSha256(sharedSecret, tokenData);

    const url = new URL("https://www.purpledotprice.com/api/v1/pre-orders");
    url.searchParams.append("api_key", apiKey);
    url.searchParams.append("email", email);
    url.searchParams.append("timestamp", timestamp);
    url.searchParams.append("token", token);

    const response = await fetch(url.toString(), {
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (response.ok) {
      return response.json();
    }
  }

  fetchPreordersForEmail("customer@example.com").then((preorders) => {
    console.log(preorders);
  });
</script>
```

If testing this in an API tool like Postman, you can generate the token using a pre-request script. Within Postman, you can import the `crypto-js` library, which simplifies some of the token generation&#x20;

```javascript
const crypto = require('crypto-js');

const API_KEY = 'YOUR_API_KEY';
const SHARED_SECRET = 'YOUR_SHARED_SECRET';

const email = 'customer@example.com';
const timestampInSeconds = Math.floor(Date.now() / 1000);
const tokenValue = `${email}:${timestampInSeconds}`;

const hash = crypto.HmacSHA256(tokenValue, SHARED_SECRET);
const token = crypto.enc.Hex.stringify(hash);

pm.request.addQueryParams(`api_key=${API_KEY}&token=${token}&timestamp=${timestampInSeconds}&email=${email}`);
```

#### [`GET /pre-orders`](#get-pre-orders)

Get all pre-orders for a given shopper email address.

Request:

* `limit` (number) - Optional. The number of pre-orders to retrieve. Set to 10 by default but can be set up to 100
* `starting_after` (UUID) - Optional. Paginate pre-orders after the given pre-order ID

Response:

* `orders` - An array containing all the pre-orders
  * `id` - The Purple Dot ID of the pre-order
  * `reference` - The Purple Dot reference number of the pre-order
  * `created_at` - ISO8610 timestamp of when the pre-order was placed
  * `total_amount` - The pre-order total
  * `currency` - The presentment currency of the pre-order
  * `line_items` - Array of line items
    * `id` - The Purple Dot ID of the line item
    * `estimated_ship_dates` - The estimated ship dates of the line item
    * `product_id` - The Shopify ID of the line item's product
    * `variant_id` - The Shopify ID of the line item's product variant
    * `order_id` - The Shopify order ID in  (this will be `null` if the preorder/line-item is not exported to Shopify)
    * `cancelled` - Whether the line item is cancelled
  * `shipping_address`
    * `first_name`
    * `last_name`
    * `address1`
    * `address2`
    * `city`
    * `postal_code`
    * `province_code` - The ISO3166 code of the second level administrative subdivision
    * `country_code` - The ISO3166 code of the country
    * `phone`
* `has_more` - Indicates whether there are more pre-orders available to page through
* `starting_after` - The ID of the last pre-order in the list which can then be used in the next request

Examples:

{% code overflow="wrap" %}

```bash
curl --request GET \
  --url 'https://www.purpledotprice.com/api/v1/pre-orders?api_key=<<enter-api-key>>&email=<<enter-email>>&timestamp=<<enter-timestamp>>&token=<<enter-generated-token>>'
```

{% endcode %}

```json
{
  "meta": {
    "result": "success"
  },
  "data": {
    "pre_orders": [
      {
        "id": "03cda1e6-0827-4092-ae97-5a4746bac0b3",
        "reference": "#PD404821",
        "created_at": "2023-12-07T10:59:24.248Z",
        "total_amount": 54.72,
        "currency": "USD",
        "line_items": [
          {
            "id": "628f7e83-c56f-4e16-9959-43e011f77e8f",
            "estimated_ship_dates": "Mar 1 – 2",
            "product_id": "9f32f1f6-42bc-49f3-8a55-d28362444ccf",
            "variant_id": "9c1206a0-7efa-43af-bbfa-52498f6af6aa",
            "order_id": null,
            "canceled": false
          }
        ],
        "shipping_address": {
          "first_name": "John",
          "last_name": "Smith",
          "address1": "8 York Road",
          "address2": null,
          "city": "London",
          "postal_code": "SW49 5LT",
          "province_code": null,
          "country_code": "GB",
          "phone": "+441974616161"
        }
      }
    ],
    "has_more": true,
    "starting_after": "2174855e-0f3c-482d-9cf0-f2b5cb6213cf"
  }
}
```
