# 3. Notification Subscription

When an event occurs, subscriptions containing a matching event type send an HTTP POST
request to their respective URLs. The POST request contains the data associated with the
event.

You must tell RapidSOS what URL to send these webhooks to. The following diagram provides
a visual representation of this process.

![image.png](/services/api/attachments/665b7d0e-0bf6-4006-81ec-9805b8dcdabb)

## 3.1 Authentication

This interface is authenticated via TWO-LEGGED OAUTH2 using your client credentials. More details on obtaining an access token can be found in the [Authentication documentation](https://rapidsos.portal.swaggerhub.com/sp-admin/products/alerts/edit/content/f1fdbc24-fff6-414b-ad47-7b9784813021)

## 3.2 Register a Webhook subscription
After you have received your authentication token, you can now begin to register Webhook Subscriptions for events. 

Below is an example request.


```http
POST /v1/webhooks/subscriptions HTTP/1.1
Host: api-sandbox.rapidsos.com
Content-Type: application/json; charset=utf-8
Authorization: Bearer YOUR-ACCESS-TOKEN
{
  "event_types": [
    "alert.new",
    "alert.chat",
    "alert.status_update",
    "alert.disposition_update",
    "alert.location_update",
    "alert.milestone",
    "alert.multi_trip_signal"
  ],
  "url": "https://myapi.com/webhook-receiver"
}
```
Example response below.

```http
{
    "created_time": 1674147882447,
    "event_types": [
        "alert.new",
        "alert.chat",
        "alert.status_update",
        "alert.disposition_update",
        "alert.milestone",
        "alert.multi_trip_signal"
    ],
    "id": 149,
    "last_updated_time": 1674147882447,
    "url": "https://myapi.com/webhook-receiver"
}
```

> Additional details can be found [here](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/get_subscriptions)

Once a Webhook subscription is established, you will begin receiving event notifications. The following section describes the notifications you will receive and the recommended action to take upon receipt.

## 3.3 Retrieve Existing Webhook Subscriptions
You can retrieve a list of all existing webhook subscription by making a [GET request](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/get_subscriptions).

Below is a sample request. 
```http
GET /v1/webhooks/subscriptions HTTP/1.1
Host: api-sandbox.rapidsos.com
Content-Type: application/json; charset=utf-8
Authorization: Bearer YOUR-ACCESS-TOKEN

```
A json response will be returned with an array of webhook subscription records. Below is a sample response.

```json lineNumber
[
    {
        "created_time": 1674584391853,
        "event_types": [
            "alert.new",
            "alert.status_update",
            "alert.chat",
            "alert.disposition_update",
            "alert.milestone",
            "alert.multi_trip_signal"
        ],
        "id": 108862,
        "last_updated_time": 1674584391853,
        "url": "https://myapi.com/webhook-receiver"
    },
    {
        "created_time": 1663952501211,
        "event_types": [
            "alert.new",
            "alert.status_update",
            "alert.chat",
            "alert.disposition_update",
            "alert.milestone",
            "alert.multi_trip_signal"
        ],
        "id": 29860,
        "last_updated_time": 1663952501211,
        "url": "https://myapi.com/webhook-receiver-2"
    }
]
```

> To view full documentation for this API request, try it out, or obtain code examples, check out our [Interactive API Explorer](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/get_subscriptions). 

## 3.4 Update Registered Webhook URL
To make updates to any registered webhook URLs or events for a subscription, you can make a [PATCH request](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/patch_subscriptions__subscription_id_). 

Below is a sample request that updates the registered webhook event type to only include `alert.new`. The `subscription_id` is returned when intially registering a webhook or retrieving existing webhook subscriptions.
```http
PATCH /v1/webhooks/subscriptions/{subscription_id} HTTP/1.1
Host: api-sandbox.rapidsos.com
Content-Type: application/json; charset=utf-8
Authorization: Bearer YOUR-ACCESS-TOKEN
{
  "event_types": [
    "alert.new"
  ],
  "url": "https://myapi.com/webhook-receiver"
}
```
Sample response
```json lineNumbers
{
    "created_time": 1674584391853,
    "event_types": [
        "alert.new"
    ],
    "id": 108862,
    "last_updated_time": 1674584391853,
    "url": "https://webhook.site/43e28f58-c507-407a-a761-fce6f69e9d26"
}
```

>To view full documentation for this API request, try it out, or obtain code examples, check out our Interactive API Explorer [here](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/patch_subscriptions__subscription_id_). 


## 3.5 Delete Registered Webhook
To remove a registered webhook subscription you can make a [DELETE](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/delete_subscriptions__subscription_id_) request to the Webhook Subscrption API. 

Sample request.
```http
DELETE /v1/webhooks/subscriptions/{subscription_id} HTTP/1.1
Host: api-sandbox.rapidsos.com
Content-Type: application/json; charset=utf-8
Authorization: Bearer YOUR-ACCESS-TOKEN
```
A `204` response will be returned if successful. 


> To view full documentation for this API request, try it out, or obtain code examples, check out our [Interactive API Explorer](https://rapidsos.portal.swaggerhub.com/alerts/default/webhooks-subscription-api-v-1-1-0#/default/delete_subscriptions__subscription_id_).


## 3.6 Event Notifications

### 3.6.1 Validate Webhook Signatures

To verify the sender of a webhook payload received by your endpoint, you should always validate the signature value in the `X-RapidSOS-Signature` HTTP header. The signature value is generated using the HMAC-SHA1 hash of the payload, using the client secret of your client credentials as the secret key.

Here is a Python-based example of signature verification:

```python
import hashlib
import hmac

received_signature = headers["X-RapidSOS-Signature"]
expected_signature = hmac.new(YOUR_CLIENT_SECRET, PAYLOAD, hashlib.sha1).hexdigest()

assert received_signature == expected_signature
```

In addition to validating the signature, you should also validate the freshness of the `"timestamp"` attribute in the payload. To properly allow for differences in server time, it is recommended to check that the `"timestamp"` value is no older than 60 seconds. `"timestamp"` is a millisecond-precise UNIX timestamp.

### 3.6.2 Webhook Event Body

All notifications are received in a common [EventNotification](https://rapidsos.portal.swaggerhub.com/alerts/default/websocket-events-api-v-1-1-1) format.

```json lineNumbers
{
  "event_type": "alert.new",
  "timestamp": 1671736239735,
  "body": {...}
}
```
The following table summarizes each supported event type, and the recommended action to take upon receipt. 

Each Event Type links to a schema for the notification `body` of the event.

> For several events, it is recommended to query the RAD-E API for additional data because event notifications follow a common format that may not include all available data from different alert service providers. 
>
>See the [EventNotification](https://rapidsos.portal.swaggerhub.com/alerts/default/websocket-events-api-v-1-1-1) schema for more details.

|Event Type|Description|Recommended Action|
|-|-|-|
|**alert.new**|An `alert.new` event indicates that a new alert has become available to your agency.|Query the affected alert's latest additional data.|
|**alert.multi_trip_signal**|An `alert.multi_trip_signal` event is one which would normally trigger an `alert.new` incident independently, but instead has been aggregated into an existing event. For instance, a burglary could be detected by multiple devices, such as a home alarm first going off then a motion sensor triggered second. In this case, the home alarm is described in the initial `alert.new` event, while the triggering of the second alert from the motion sensor is denoted by a `alert.multi_trip_signal` event.|Query the affected alert's latest additional data.|
|**alert.status_update**|An `alert.status_update` event indicates that the status of an alert within your agency has been updated.|Query the affected alert's latest additional data.|
|**alert.disposition_update**|An `alert.disposition_update` event indicates that the disposition of an alert within your agency has been updated.|Query the affected alert's latest additional data.|
|**alert.location_update**|An `alert.location_update` event indicates that the location of an alert within your agency has been updated.|None|
|**alert.chat**|An `alert.chat` event indicates that a new chat messages has been sent for an alert within your agency.|None|
|**alert.milestone**|An `alert.milestone` event is a flexible way to note updates to an alert event without updating the event status or disposition. |None|

> Because `alert.chat` and `alert.location_update` notifications may occur frequently, your application **SHOULD NOT** make API requests to the Alerts Management API in response to those notifications.
