# Create an event subscription

Create an event subscription by sending a POST request to the event-subscriptions endpoint to receive webhook notifications when specified events occur.

**Prerequisites:** [Authentication](/api/authentication)

To add event notifications to your integration, use our API to create an event subscription and handle the notification that we send by webhook when an event occurs.

**Important:** To receive notifications, your server must be able to handle POST requests.

To create an event subscription, send the following information in your request:

- **Event type** - The event that you want to subscribe to. You can subscribe to more than one event within the same request.
- **URI** - The endpoint that we send notifications to. The endpoint must be publicly available.
- **Secret** - A secret that we return in the header of webhook requests to verify that it is a genuine request.
- **Event status** - The status of the event subscription.
- **Email address** - An email address that we contact if we can't communicate with the endpoint that you provided.

**Note:** For a complete list of events that you can subscribe to, go to [Events list](/knowledge/events).

<a id="integration-steps"></a>
## Integration steps

**Step 1.** Create an event subscription  
**Step 2.** Send a 200 response code  
**Step 3.** Handle the notification content

<a id="before-you-begin"></a>
## Before you begin

[Authenticate your requests](/api/authentication) before making API calls. If your request fails, see [Errors](/api/errors).

<a id="step-1-create-an-event-subscription"></a>
## Step 1. Create an event subscription

To create an event subscription, send a POST request to our event subscriptions endpoint.

| Environment | URL |
| --- | --- |
| Test | [https://api.uat.payroc.com/v1/event-subscriptions](https://api.uat.payroc.com/v1/event-subscriptions) |
| Production | [https://api.payroc.com/v1/event-subscriptions](https://api.payroc.com/v1/event-subscriptions) |

<a id="request-parameters"></a>
### Request parameters

To create the body of your request, use the following parameters:

<a id="schema-requestbody"></a>
### Schema (`request.body`)

[Request body schema for `POST /event-subscriptions`](/api/create-event-subscription)

<a id="example-request"></a>
### Example request

<a id="request"></a>
### Request

POST [https://api.payroc.com/v1/event-subscriptions](https://api.payroc.com/v1/event-subscriptions)

**`Create event subscription`**

```curl
curl -X POST https://api.payroc.com/v1/event-subscriptions \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "enabled": true,
  "eventTypes": [
    "processingAccount.status.changed"
  ],
  "notifications": [
    {
      "type": "webhook",
      "secret": "aBcD1234eFgH5678iJkL9012mNoP3456",
      "supportEmailAddress": "jane.doe@example.com",
      "uri": "https://my-server/notification/endpoint"
    }
  ],
  "metadata": {
    "yourCustomField": "abc123"
  }
}'
```

**`Create event subscription`**

```python
import requests

url = "https://api.payroc.com/v1/event-subscriptions"

payload = {
    "enabled": True,
    "eventTypes": ["processingAccount.status.changed"],
    "notifications": [
        {
            "type": "webhook",
            "secret": "aBcD1234eFgH5678iJkL9012mNoP3456",
            "supportEmailAddress": "jane.doe@example.com",
            "uri": "https://my-server/notification/endpoint"
        }
    ],
    "metadata": { "yourCustomField": "abc123" }
}
headers = {
    "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

**`Create event subscription`**

```javascript
const url = 'https://api.payroc.com/v1/event-subscriptions';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"enabled":true,"eventTypes":["processingAccount.status.changed"],"notifications":[{"type":"webhook","secret":"aBcD1234eFgH5678iJkL9012mNoP3456","supportEmailAddress":"jane.doe@example.com","uri":"https://my-server/notification/endpoint"}],"metadata":{"yourCustomField":"abc123"}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

**`Create event subscription`**

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.payroc.com/v1/event-subscriptions"

	payload := strings.NewReader("{\n  \"enabled\": true,\n  \"eventTypes\": [\n    \"processingAccount.status.changed\"\n  ],\n  \"notifications\": [\n    {\n      \"type\": \"webhook\",\n      \"secret\": \"aBcD1234eFgH5678iJkL9012mNoP3456\",\n      \"supportEmailAddress\": \"jane.doe@example.com\",\n      \"uri\": \"https://my-server/notification/endpoint\"\n    }\n  ],\n  \"metadata\": {\n    \"yourCustomField\": \"abc123\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

**`Create event subscription`**

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.payroc.com/v1/event-subscriptions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Idempotency-Key"] = '8e03978e-40d5-43e8-bc93-6894a57f9324'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"enabled\": true,\n  \"eventTypes\": [\n    \"processingAccount.status.changed\"\n  ],\n  \"notifications\": [\n    {\n      \"type\": \"webhook\",\n      \"secret\": \"aBcD1234eFgH5678iJkL9012mNoP3456\",\n      \"supportEmailAddress\": \"jane.doe@example.com\",\n      \"uri\": \"https://my-server/notification/endpoint\"\n    }\n  ],\n  \"metadata\": {\n    \"yourCustomField\": \"abc123\"\n  }\n}"

response = http.request(request)
puts response.read_body
```

**`Create event subscription`**

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.payroc.com/v1/event-subscriptions")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"enabled\": true,\n  \"eventTypes\": [\n    \"processingAccount.status.changed\"\n  ],\n  \"notifications\": [\n    {\n      \"type\": \"webhook\",\n      \"secret\": \"aBcD1234eFgH5678iJkL9012mNoP3456\",\n      \"supportEmailAddress\": \"jane.doe@example.com\",\n      \"uri\": \"https://my-server/notification/endpoint\"\n    }\n  ],\n  \"metadata\": {\n    \"yourCustomField\": \"abc123\"\n  }\n}")
  .asString();
```

**`Create event subscription`**

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/event-subscriptions', [
  'body' => '{
  "enabled": true,
  "eventTypes": [
    "processingAccount.status.changed"
  ],
  "notifications": [
    {
      "type": "webhook",
      "secret": "aBcD1234eFgH5678iJkL9012mNoP3456",
      "supportEmailAddress": "jane.doe@example.com",
      "uri": "https://my-server/notification/endpoint"
    }
  ],
  "metadata": {
    "yourCustomField": "abc123"
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

echo $response->getBody();
```

**`Create event subscription`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/event-subscriptions");
var request = new RestRequest(Method.POST);
request.AddHeader("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324");
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"enabled\": true,\n  \"eventTypes\": [\n    \"processingAccount.status.changed\"\n  ],\n  \"notifications\": [\n    {\n      \"type\": \"webhook\",\n      \"secret\": \"aBcD1234eFgH5678iJkL9012mNoP3456\",\n      \"supportEmailAddress\": \"jane.doe@example.com\",\n      \"uri\": \"https://my-server/notification/endpoint\"\n    }\n  ],\n  \"metadata\": {\n    \"yourCustomField\": \"abc123\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Create event subscription`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "enabled": true,
  "eventTypes": ["processingAccount.status.changed"],
  "notifications": [
    [
      "type": "webhook",
      "secret": "aBcD1234eFgH5678iJkL9012mNoP3456",
      "supportEmailAddress": "jane.doe@example.com",
      "uri": "https://my-server/notification/endpoint"
    ]
  ],
  "metadata": ["yourCustomField": "abc123"]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/event-subscriptions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

<a id="response-fields"></a>
### Response fields

If your request is successful, we send you the ID of the subscription. You can use the ID to update, retrieve, or delete the event subscription.

The response contains the following fields:

<a id="schema-responsebody"></a>
### Schema (`response.body`)

[Response body schema for `POST /event-subscriptions`](/api/create-event-subscription)

<a id="example-response"></a>
### Example response

<a id="response-201"></a>
### Response (201)

```json
{
  "enabled": true,
  "eventTypes": [
    "processingAccount.status.changed"
  ],
  "notifications": [
    {
      "type": "webhook",
      "secret": "**********oP3456",
      "supportEmailAddress": "jane.doe@example.com",
      "uri": "https://my-server/notification/endpoint"
    }
  ],
  "id": 2565435189324,
  "status": "registered",
  "metadata": {
    "yourCustomField": "abc123"
  }
}
```

<a id="step-2-send-a-200-response-code"></a>
## Step 2. Send a 200 response code

We send notifications by webhook request to the URI endpoint that you provided when you created the subscription.

You must return a 200 status code when you receive the request.

If we do not receive a 200 response, we retry the request five times. After the fifth attempt, we send an email to the support email address that you provided when you created the subscription.

**Note:** We send an email only when a single instance of an event notification fails to deliver. If the event occurs again, we send another notification.

<a id="step-3-handle-the-notification-content"></a>
## Step 3. Handle the notification content

Each notification follows the

[CloudEvents](https://cloudevents.io/)

standard, and we use the data object to communicate information about the event that occurred, for example:

```json
{
  "specversion": "1.0",
  "type": "processingAccount.status.changed",
  "version": "1.0",
  "source": "payroc",
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "time": "2024-07-02T15:30:00.000Z",
  "datacontenttype": "application/json",
  "data": {
    "processingAccountId": "38765",
    "status": "entered"
  }
}
```

You can view our event notifications on the [Events](/knowledge/events) page.
