# Webhook Subscriptions

## Headers
Your webhook subscriptions will include several special headers:

Header|Description
-|-
`X-Barchart-Subscription-Id`|The global ID of the webhook subscription.
`X-Barchart-Subscription-Delivery`|A unique ID for this specific delivery.
`X-Barchart-Subscription-Topic`|The type of event delivered. Example: `CONTRACT_CREATED`
`X-Barchart-Subscription-Signature`|The HMAC hex digest of the request body, using the SHA-256 hash function with the submitted `secret` as the HMAC key.

## Validating Payloads
You should always confirm that we actually sent you the request. You can do this by using the HMAC algorithm with SHA-256 digest mode of the request body and your submitted `secret` as the key. You can then compare this to the `X-Barchart-Subscription-Signature` header that we sent.

<!-- tabs:start -->

#### **Shell**
```bash
echo -n "REQUEST_BODY" | openssl dgst -sha256 -hmac "YOUR_SECRET"
```

#### **PHP**
```php
hash_hmac('sha256', $requestBody, $yourSecret);
```

#### **Java**
```java
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(yourSecret.getBytes(), "HmacSHA256");
sha256HMAC.init(secretKey);
String computedHash = bytesToHex(sha256HMAC.doFinal(requestBody));
```

#### **Python**
```python
import hashlib, hmac
hmac.new(your_secret, request_body, hashlib.sha256).hexdigest()
```

#### **Ruby**
```ruby
require 'openssl'
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha256'), your_secret, request_body)
```

#### **NodeJS**
```javascript
const crypto = require('crypto');

const hash = crypto.createHmac('sha256', yourSecret).update(requestBody).digest('hex').toString();
```

<!-- tabs:end -->

## Failed Attempts
If we cannot reach your defined callback URL, or it returns something other than a 2xx response code, we will retry the request up to 8 times. Below is an outline of the retry attempts:

Attempt|Delay after Previous
-|-
1|5 minutes
2|10 minutes
3|20 minutes
4|40 minutes
5|1 hour 20 minutes
6|2 hours 40 minutes
7|5 hours 20 minutes
8|10 hours 40 minutes

After all retry attempts have been exhausted, we will cancel the request.

### Request Timeouts
All requests will timeout after 5 seconds. If we do not receive a 2xx response within this time, we will assume your URL is not reachable. To always ensure you send back a timely response, make sure any heavy logic happens in the background.

## Updating Subscriptions
Subscribing again with the same callback URL will update the current subscription for that specific topic and callback.

## Unsubscribing
There are a couple of different methods to "unsubscribe":
1. Return a `410` response code from your defined callback. This will immediately remove the subscription.
2. Use the [`deleteWebhookSubscription`](/mutations?id=deletewebhooksubscription) mutation.

## Example
### Subscribing
```graphql
subscription ContractEvent($callback: String!, $secret: String!) {
  contractCreated(callback: $callback, secret: $secret) {
    id
    displayId
    amountBushels
    amountDelivered
    amountRemaining
    commodity {
      name
    }
    location {
      name
    }
  }
}
```
Variables:
```json
{
    "callback": "https://example.com/callback",
    "secret": "85c06175ce49070b4388d327d107df76b2322b7db8dec0992019fdf320debbf4"
}
```
Response:
```json
{
    "data": {
        "contractCreated": null
    },
    "extensions": {
        "subscription": {
            "id": "MDE6V2ViaG9va1N1YnNjcmlwdGlvbjotMQ"
        }
    }
}
```

### Event Callback
When a contract is created, you will get the following:
```http
POST /callback HTTP/1.1
Content-Type: application/json
Host: example.com
User-Agent: Barchart-Subscription/1.0
X-Barchart-Subscription-Id: MDE6V2ViaG9va1N1YnNjcmlwdGlvbjotMQ
X-Barchart-Subscription-Delivery: 95496531-688f-4c2a-bc3f-935cd9d9c46e
X-Barchart-Subscription-Topic: CONTRACT_CREATED
X-Barchart-Subscription-Signature: f164541fb224e61a5cf134497c24a53151059d498a3abf1b5ff94d44caec0deb

{
    "data":{
        "contractCreated":{
            "id":"MDE6Q29udHJhY3Q6LTE6MDAwMQ",
            "displayId":"0001",
            "amountBushels":1000,
            "amountDelivered":0,
            "amountRemaining":1000,
            "commodity":{
                "name":"Corn (#2 Yellow)"
            },
            "location":{
                "name":"Chicago"
            }
        }
    }
}
```