# Stay Up to Date with Webhooks

Source: https://docs.gocardless.com/docs/getting-started/stay-up-to-date-with-webhooks

# Stay up to date with webhooks

A webhook is a request that GoCardless sends to your server to alert you of an event. Adding support for webhooks allows you to receive real-time notifications from GoCardless when things happen in your account, so you can take automated actions in response.

- When a payment fails due to lack of funds, retry it automatically.
- When a customer cancels their mandate with the bank, suspend their account.
- When a subscription generates a new payment, record it against their account.

## Create a webhook endpoint

To start receiving webhooks, add a webhook endpoint from your [Sandbox Dashboard](https://manage-sandbox.gocardless.com/developers/webhook-endpoints).

![Creating a webhook endpoint in the GoCardless dashboard](/images/docs/getting-started/stay-up-to-date-with-webhooks/create_webhook_endpoint.png)

Enter the HTTPS URL where your webhook handler will be available, give your endpoint a name, and click **"Create webhook endpoint"**. Then click on your new endpoint in the list and **copy the secret to your clipboard**.

## Build a webhook handler

Webhooks are HTTP POST requests made to the URL you provided, with a JSON body. Here's an example:

```http
POST https://example.com/webhooks HTTP/1.1
User-Agent: gocardless-webhook-service/1.1
Content-Type: application/json
Webhook-Signature: 78e3507f61f141046969c73653402cb50b714f04322da04d766ee0f6d2afe65f

,
      "details": 
    }
  ]
}
```

> **Info: For Partners**
> The body contains one or more events (up to a maximum of 250), specifying the type of the resource
>   affected (e.g. "mandates" or "payments"), its ID, the ID of the organisation the resource belongs
>   to (which you stored when obtaining their access token) and the action that occurred (e.g.
>   "cancelled" or "expired").

### Secure your webhooks

The first step when you receive a webhook is to check its signature — this ensures it's genuinely from GoCardless and hasn't been forged. A signature is provided in the `Webhook-Signature` header. Compute the signature yourself using the POST body and your webhook endpoint secret, then compare it to the header value.

If they match, the webhook is genuine. Keep the secret safe and change it periodically using the Dashboard.

```php
<?php
// We recommend storing your webhook endpoint secret in an environment variable
// for security
\$webhook_endpoint_secret = getenv("GOCARDLESS_WEBHOOK_ENDPOINT_SECRET");
\$request_body = file_get_contents('php://input');

\$headers = array_change_key_case(getallheaders(), CASE_LOWER);
\$signature_header = \$headers["webhook-signature"];

try \ catch(\\GoCardlessPro\\Core\\Exception\\InvalidSignatureException \$e) \
```

```python
# Here, we're using a Django view, but essentially the same code will work in

# other Python web frameworks (e.g. Flask) with minimal changes

from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import HttpResponse

from gocardless_pro import webhooks
from gocardless_pro.errors import InvalidSignatureError

# Handle the incoming Webhook and check its signature.

class Webhook(View):
@method_decorator(csrf_exempt)
def dispatch(self, *args, \*\*kwargs):
return super(Webhook, self).dispatch(*args, \*\*kwargs)

    def get_events(self, request):
        secret = os.environ['GC_WEBHOOK_SECRET']
        signature = request.META["HTTP_WEBHOOK_SIGNATURE"]
        body = request.body.strip()
        return webhooks.parse(body, secret, signature)

    def post(self, request, *args, **kwargs):
        try:
            for event in self.get_events(request):
                # Do something with the events ...
                pass

            return HttpResponse(200)
        except InvalidSignatureError:
            return HttpResponse(498)
```

```ruby
# Here, we're using a Rails controller, but essentially the same code will work in other

# Ruby web frameworks (e.g. Sinatra) with minimal changes

class WebhooksController < ApplicationController
include ActionController::Live

protect_from_forgery except: :create

def create # We recommend storing your webhook endpoint secret in an environment variable # for security
webhook_endpoint_secret = ENV['GOCARDLESS_WEBHOOK_ENDPOINT_SECRET']

    # In a Rack app (e.g. Sinatra), access the POST body with
    # \`request.body.tap(&:rewind).read\`
    request_body = request.raw_post

    # In a Rack app (e.g. Sinatra), the header is available as
    # \`request.env['HTTP_WEBHOOK_SIGNATURE']\`
    signature_header = request.headers['Webhook-Signature']

    begin
      events = GoCardlessPro::Webhook.parse(request_body: request_body,
                                            signature_header: signature_header,
                                            webhook_endpoint_secret: webhook_endpoint_secret)

      # Process the events...

      render status: 204, nothing: true
    rescue GoCardlessPro::Webhook::InvalidSignatureError
      render status: 498, nothing: true
    end

end
end
```

```java
package hello;

// Use the POM file at
// https://raw.githubusercontent.com/gocardless/gocardless-pro-java-maven-example/master/pom.xml

@RestController
public class HelloController \

            return new ResponseEntity("OK", HttpStatus.OK);
        \} catch(InvalidSignatureException e) \
    \}

\}
```

```nodejs
const process = require("process");
const webhooks = require("gocardless-nodejs/webhooks");

const webhookEndpointSecret = process.env.WEBHOOK_ENDPOINT_SECRET;

// Handle the incoming Webhook and check its signature.
const parseEvents = (
eventsRequestBody,
signatureHeader, // From webhook header
) => \ catch (error) \
\}
\};
```

```net
[HttpPost]
public ActionResult HandleWebhook()
\

        return new HttpStatusCodeResult(HttpStatusCode.OK);
    \}
    catch (InvalidSignatureException e)
    \

\}
```

```go
package main

	"http"

    gocardless "github.com/gocardless/gocardless-pro-go/v6"

)

func main() \))
wh.ServeHTTP(w, r)
\})
\}

func parseEvents(event gocardless.Event) \
```

### Processing events

A webhook can contain multiple events, each with a `resource_type` (e.g. "payments" or "mandates"), an `action` (e.g. "cancelled"), and `details` (specifying why the event happened).

You can see a full list of possible combinations in the [event types reference](/docs/api-reference/events/mandates).

Here's an example handler for when a mandate is cancelled:

```php
<?php
function process_mandate_event(\$event)
\

\}

// We recommend storing your webhook endpoint secret in an environment variable
// for security
\$webhook_endpoint_secret = getenv("GOCARDLESS_WEBHOOK_ENDPOINT_SECRET");
\$request_body = file_get_contents('php://input');

\$headers = getallheaders();
\$signature_header = \$headers["Webhook-Signature"];

try \
    \}

    header("HTTP/1.1 200 OK");

\} catch(\\GoCardlessPro\\Core\\Exception\\InvalidSignatureException \$e) \
```

```python
# Here, we're using a Django view, but essentially the same code will work in

# other Python web frameworks (e.g. Flask) with minimal changes

from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import HttpResponse

from gocardless_pro import webhooks, Client
from gocardless_pro.errors import InvalidSignatureError

from myinvoicingapp.models import GoCardlessEvent

# Handle the incoming Webhook and perform an action with the Webhook data.

class Webhook(View):
logger = logging.getLogger(**name**)

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(Webhook, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        try:
            for event in self._get_events(request):
                self.process(event)
            return HttpResponse(204)
        except InvalidSignatureError:
            return HttpResponse(498)

    def is_already_processed(event):
        return GoCardlessEvent.objects.filter(gocardless_id=event.id).exists()

    def process(self, event):
        self.logger.info("Processing event \\n".format(event.id))

        if self.is_already_processed(event):
            return

        if event.resource_type == 'mandates':
            return self.process_mandate_event(event)
        # ... Handle other resource types
        else:
            self.logger.info("Don't know how to process an event with \\
                resource_type \\n".format(event.resource_type))

    def process_mandate_event(self, event):
        access_token = os.environ('GOCARDLESS_ACCESS_TOKEN')

        client = Client(
            access_token=access_token,
            environment='sandbox'
        )

        mandate = client.mandates.get(event.id)

        if event.action == 'cancelled':
            # You should perform processing steps asynchronously to avoid timing out
            # if you receive many events at once. To do this, you could use a
            # queueing system like RQ (https://github.com/ui/django-rq)
            self.logger.info("Mandate  has been cancelled\\n".format(mandate.id))
        # ... Handle other mandate actions
        else:
            self.logger.info("Don't know how to process an event with \\
                resource_type \\n".format(event.resource_type))

        GoCardlessEvent.objects.create(gocardless_id=mandate.id)

    def _get_events(self, request):
        secret = os.environ['GC_WEBHOOK_SECRET']
        signature = request.META["HTTP_WEBHOOK_SIGNATURE"]
        body = request.body.strip()
        return webhooks.parse(body, secret, signature)
```

```ruby
require 'gocardless_pro'

class MandateEventProcessor
def self.process(event, response)
case event.action
when 'cancelled'
response.stream.write("Mandate #\ has been cancelled\\n")

      # You should keep some kind of record of what events have been processed
      # to avoid double-processing, checking if the event already exists before
      # event = Event.find_by(gocardless_id: event['id'])

      # You should perform processing steps asynchronously to avoid timing out
      # if you receive many events at once. To do this, you could use a
      # queueing system like
      # Resque (https://github.com/resque/resque)
      #
      # Once you've performed the actions you want to perform for an event, you
      # should make a record to avoid accidentally processing the same one twice
      # CancelServiceAndNotifyCustomer.enqueue(event['links']['mandate'])
    else
      response.stream.write("Don't know how to process a mandate #\ " \\
                            "event\\n")
    end

end
end

def create

# We recommend storing your webhook endpoint secret in an environment variable

# for security

webhook_endpoint_secret = ENV['GOCARDLESS_WEBHOOK_ENDPOINT_SECRET']

# In a Rack app (e.g. Sinatra), access the POST body with

# \`request.body.tap(&:rewind).read\`

request_body = request.raw_post

# In a Rack app (e.g. Sinatra), the header is available as

# \`request.env['HTTP_WEBHOOK_SIGNATURE']\`

signature_header = request.headers['Webhook-Signature']

begin
events = GoCardlessPro::Webhook.parse(request_body: request_body,
signature_header: signature_header,
webhook_endpoint_secret: webhook_endpoint_secret)

    events.each do |event|
      # We're using Rails's streaming functionality here to write directly to the
      # response rather than using views, as one would usually.
      response.stream.write("Processing event #\\\n")

      case event.resource_type
      when 'mandates'
        MandateEventProcessor.process(event, response)
      else
        response.stream.write("Don't know how to process an event with resource_type " \\
                              "#\\\n")
      end
    end

    response.stream.close
    render status: 200

rescue GoCardlessPro::Webhook::InvalidSignatureError
render status: 498
end
end
```

```java
package hello;

// Use the POM file at
// https://raw.githubusercontent.com/gocardless/gocardless-pro-java-maven-example/master/pom.xml

@RestController
public class HelloController \
    \}

    private String processEvent(Event event) \
    \}

    @PostMapping("/")
    public ResponseEntityhandlePost(
            @RequestHeader("Webhook-Signature") String signatureHeader,
            @RequestBody String requestBody) \

            return new ResponseEntity(responseBody, HttpStatus.OK);
        \} catch(InvalidSignatureException e) \
    \}

\}
```

```nodejs
const process = require("process");
const webhooks = require("gocardless-nodejs/webhooks");
const express = require("express");
const bodyParser = require("body-parser");

const app = express();
// parse incoming body of Content-Type of application/json to return it as a plain string which needs to be passed into the webhooks.parse method
app.use(bodyParser.text(\));

const webhookEndpointSecret = process.env.WEBHOOK_ENDPOINT_SECRET;

const processMandate = (event) => \ has been cancelled.\\n\`;
default:
return \`Do not know how to process an event with action \$\\`;
\}
\};

const processEvent = (event) => \\`;
\}
\};

app.post("/", async (req, res) => \ catch (error) \
\}
\};

try \

    res.send(responseBody);

\} catch (error) \);
\}
\});

app.listen(process.env.PORT, () => \\`);
\});
```

```net
[HttpPost]
public ActionResult HandleWebhook()
\ has been created, yay!");
                        break;
                    case "cancelled":
                        Console.WriteLine(\$"Oh no, mandate \ was cancelled!");
                        break;
                    default:
                        Console.WriteLine(\$"\ has been \");
                        break;
                \}
            \}
            else
            \ events yet");
            \}
        \}
        return new HttpStatusCodeResult(HttpStatusCode.OK);

    \}
    catch (InvalidSignatureException e)
    \

\}
```

```go
package main

	"fmt"
	"http"

    gocardless "github.com/gocardless/gocardless-pro-go/v6"

)

func main() \
    \}

    parseEvent := func(event gocardless.Event) \
    \}

    http.HandleFunc("/webhookEndpoint", func(w http.ResponseWriter, r *http.Request) \))
    	wh.ServeHTTP(w, r)
    \})

\}
```

Send a test webhook and click on it in the list. You'll see a response like this:

```http
Processing event EVTEST8XP9DCPK
Mandate index_ID_123 has been cancelled!
```

We'll send webhooks exactly like this when real events happen in your account. You can add support for as many `resource_type`s and `action`s as you like, using all of the [event data](/docs/api-reference/events/payments) we provide.

## Test your webhook handler

  
#### [Dashboard](https://manage-sandbox.gocardless.com/developers/webhooks/create)

Use the **"Send test webhook"** feature. Select your endpoint, set the resource type to
    `mandates` and the action to `cancelled`, then click send.

  
#### [GoCardless CLI](/docs/developer-resources/gc-cli)

Use the `gc` CLI to locally test webhook integrations. Trigger events and forward them to your
    server's webhook handler directly from the terminal.

  
#### [Scenario Simulator](/docs/developer-resources/scenario-simulators)

In the **sandbox environment**, use scenario simulators to manually trigger specific cases.
    Available in the Developer section of the dashboard and through the API.

  
### Advanced: Using TLS client authentication

Using TLS enables us to encrypt data in transit. Additional security can be achieved by using client authentication alongside server authentication.

Client authentication adds an extra check in the TLS handshake to validate that the client is authorised to access the endpoint — confirming that it is GoCardless making the request, not a malicious entity.

To authorise GoCardless to send webhooks, provide a valid certificate and private key issued by your certificate authority. In practice, this can be a self-signed certificate. Useful instructions for generating certificates can be found in the [CoreOS documentation](https://github.com/coreos/docs/blob/master/os/generate-self-signed-certificates.md), using Cloudflare's [cfssl](https://github.com/cloudflare/cfssl) toolkit.

> **Info: Certificate requirements**
> We only support RSA keypairs. We recommend setting a long lifetime for the certificate to avoid
>   unnecessary management overhead. Both certificate and key must be provided in base64-encoded PEM
>   format.

Enter the certificate and key into the webhook endpoint form in the developers section of the GoCardless dashboard. All subsequent requests will be client-authenticated.

![Webhook client certificate configuration](/images/docs/getting-started/stay-up-to-date-with-webhooks/webhook_client_certificate.png)

## Next steps

  
#### [Go-live checklist](/docs/getting-started/go-live-checklist)

Review the requirements and complete the steps needed to move your integration from sandbox to
    production.