Checking Webhook Signatures

    Validate the events that Stripe sends to your webhook URLs.

    Stripe can optionally sign the webhook events it sends to your endpoints. We do so by including a signature in each event’s Stripe-Signature header. This allows you to validate that the events were sent by Stripe, not by a third party. You can verify signatures either using our official libraries, or manually using your own solution.

    Before you can verify signatures, you need to retrieve your endpoint’s secret from your Dashboard’s Webhooks settings. Select an endpoint for which you want to obtain the secret, then select the Click to reveal button. Each secret is unique to the endpoint to which it corresponds. If you use multiple endpoints, you must obtain a secret for each one. After this setup, Stripe starts to sign each webhook it sends to the endpoint.

    Verifying signatures using our official libraries

    We recommend using one of our official libraries to verify signatures. You perform the verification by providing the event payload, the Stripe-Signature header, and the endpoint’s secret. If verification fails, Stripe returns an error.

    # Set your secret key: remember to change this to your live secret key in production
    # See your keys here: https://dashboard.stripe.com/account/apikeys
    Stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
    
    # You can find your endpoint's secret in your webhook settings
    endpoint_secret = 'whsec_...'
    
    # Using Sinatra
    post '/my/webhook/url' do
        payload = request.body.read
        sig_header = request.env['HTTP_STRIPE_SIGNATURE']
        event = nil
    
        begin
            event = Stripe::Webhook.construct_event(
                payload, sig_header, endpoint_secret
            )
        rescue JSON::ParserError => e
            # Invalid payload
            status 400
            return
        rescue Stripe::SignatureVerificationError => e
            # Invalid signature
            status 400
            return
        end
    
        # Do something with event
    
        status 200
    end
    
    # Set your secret key: remember to change this to your live secret key in production
    # See your keys here: https://dashboard.stripe.com/account/apikeys
    stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
    
    from django.http import HttpResponse
    
    # You can find your endpoint's secret in your webhook settings
    endpoint_secret = 'whsec_...'
    
    # Using Django
    @csrf_exempt
    def my_webhook_view(request):
      payload = request.body
      sig_header = request.META['HTTP_STRIPE_SIGNATURE']
      event = None
    
      try:
        event = stripe.Webhook.construct_event(
          payload, sig_header, endpoint_secret
        )
      except ValueError as e:
        # Invalid payload
        return HttpResponse(status=400)
      except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        return HttpResponse(status=400)
    
      # Do something with event
    
      return HttpResponse(status=200)
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    \Stripe\Stripe::setApiKey("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
    
    // You can find your endpoint's secret in your webhook settings
    $endpoint_secret = 'whsec_...';
    
    $payload = @file_get_contents('php://input');
    $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
    $event = null;
    
    try {
      $event = \Stripe\Webhook::constructEvent(
        $payload, $sig_header, $endpoint_secret
      );
    } catch(\UnexpectedValueException $e) {
      // Invalid payload
      http_response_code(400); // PHP 5.4 or greater
      exit();
    } catch(\Stripe\Error\SignatureVerification $e) {
      // Invalid signature
      http_response_code(400); // PHP 5.4 or greater
      exit();
    }
    
    // Do something with $event
    
    http_response_code(200); // PHP 5.4 or greater
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc";
    
    // Using the Spark framework (http://sparkjava.com)
    public Object handle(Request request, Response response) {
      String payload = request.body();
      String sigHeader = request.headers("Stripe-Signature");
      Event event = null;
    
      try {
        event = Webhook.constructEvent(
          payload, sigHeader, endpointSecret
        );
      } catch (JsonSyntaxException e) {
        // Invalid payload
        response.status(400);
        return "";
      } catch (SignatureVerificationException e) {
        // Invalid signature
        response.status(400);
        return "";
      }
    
      // Do something with event
    
      response.status(200);
      return "";
    }
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    var stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
    
    // You can find your endpoint's secret in your webhook settings
    const endpointSecret = 'whsec_blSjcGhK1UHRbyGwXa9wSaK9FzLErNIS';
    
    // This example uses Express to receive webhooks
    const app = require('express')();
    
    // Retrieve the raw body as a buffer and match all content types
    app.use(require('body-parser').raw({type: '*/*'}));
    
    app.post('/webhook/example', (req, res) => {
      let sig = req.headers["stripe-signature"];
    
      try {
        let event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
        // Do something with event
      }
      catch (err) {
        res.status(400).end()
      }
    
      // Return a response
      res.json({received: true});
    });
    
    app.listen(8000, () => console.log('Running on port 8000'));
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
    
    http.HandleFunc("/webhook", func(w http.ResponseWriter, req *http.Request) {
        body, err := ioutil.ReadAll(req.Body)
        if err != nil {
            fmt.Sprintf(os.Stderr, "Error reading request body: %v
    ", err)
            w.WriteHeader(http.StatusServiceUnavailable)
            return
        }
    
        // Pass the request body & Stripe-Signature header to ConstructEvent, along with the webhook signing key
        // You can find your endpoint's secret in your webhook settings
        endpointSecret := "whsec_...";
        event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), endpointSecret)
    
        if err != nil {
            fmt.Sprintf(os.Stderr, "Error verifying webhook signature: %v
    ", err)
            w.WriteHeader(http.StatusBadRequest) // Return a 400 error on a bad signature
            return
        }
    
        // Unmarshal the event data into an appropriate struct depending on its Type
        if event.Type == "customer.updated" {
            var customer stripe.Customer
            err := json.Unmarshal(event.Data.Raw, &customer)
            if err != nil {
                fmt.Sprintf(os.Stderr, "Error parsing webhook JSON: %v
    ", err)
                w.WriteHeader(http.StatusBadRequest)
                return
            }
            // do something with customer
        }
        w.WriteHeader(http.StatusOK)
    })
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    StripeConfiguration.SetApiKey("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
    
    using System;
    using System.IO;
    using Microsoft.AspNetCore.Mvc;
    using Stripe;
    
    namespace workspace.Controllers {
        [Route("api/[controller]")]
        public class StripeWebHook : Controller {
            // You can find your endpoint's secret in your webhook settings
            const secret = "whsec_blSjcGhK1UHRbyGwXa9wSaK9FzLErNIS";
    
            [HttpPost]
            public void Index() {
                var json = new StreamReader(HttpContext.Request.Body).ReadToEnd();
    
                try {
                    var stripeEvent = StripeEventUtility.ConstructEvent(json,
                        Request.Headers["Stripe-Signature"], secret);
    
                    // Do something with event
    
                }
                catch (StripeException e) {
                    return BadRequest();
                }
    
            }
        }
    }
    

    Preventing replay attacks

    A replay attack is when an attacker intercepts a valid payload and its signature, then re-transmits them. To mitigate such attacks, Stripe includes a timestamp in the Stripe-Signature header. Because this timestamp is part of the signed payload, it is also verified by the signature, so an attacker cannot change the timestamp without invalidating the signature. If the signature is valid but the timestamp is too old, you can have your application reject the payload.

    Our libraries have a default tolerance of five minutes between the timestamp and the current time. You can change this tolerance by providing an additional parameter when verifying signatures. We recommend that you use Network Time Protocol (NTP) to ensure that your server’s clock is accurate and synchronizes with the time on Stripe’s servers.

    Stripe generates the timestamp and signature each time we send an event to your endpoint. If Stripe retries an event (e.g., your endpoint previously replied with a non-2xx status code), then we generate a new signature and timestamp for the new delivery attempt.

    Verifying signatures manually

    Although we recommend using our official libraries to verify webhook event signatures, you can use the following information to create a custom solution.

    The Stripe-Signature header contains a timestamp and one or more signatures. The timestamp is prefixed by t=, and each signature is prefixed by a scheme. Schemes start with v, followed by an integer. Currently, the only valid signature scheme is v1. To aid with testing, Stripe sends an additional signature with a fake v0 scheme, for test-mode events.

    Stripe-Signature: t=1492774577,
        v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd,
        v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39
    

    Note that newlines have been added in the example above for clarity, but a real Stripe-Signature header will be all one line.

    Stripe generates signatures using a hash-based message authentication code (HMAC) with SHA-256. To prevent downgrade attacks, you should ignore all schemes that are not v1.

    It is possible to have multiple signatures with the same scheme/secret pair. This can happen when you roll an endpoint’s secret from the Dashboard, and choose to keep the previous secret active for up to 24 hours. During this time, your endpoint has multiple active secrets and Stripe generates one signature for each secret.

    Step 1: Extract the timestamp and signatures from the header

    Split the header, using the , character as the separator, to get a list of elements. Then split each element, using the = character as the separator, to get a prefix and value pair.

    The value for the prefix t corresponds to the timestamp, and v1 corresponds to the signature(s). You can discard all other elements.

    Step 2: Prepare the signed_payload string

    You achieve this by concatenating:

    • The timestamp (as a string)
    • The character .
    • The actual JSON payload (i.e., the request’s body)

    Step 3: Determine the expected signature

    Compute an HMAC with the SHA256 hash function. Use the endpoint’s signing secret as the key, and use the signed_payload string as the message.

    Step 4: Compare signatures

    Compare the signature(s) in the header to the expected signature. If a signature matches, compute the difference between the current timestamp and the received timestamp, then decide if the difference is within your tolerance.

    To protect against timing attacks, use a constant-time string comparison to compare the expected signature to each of the received signatures.

    More information

    Questions?

    We're always happy to help with code or other questions you might have! Search our documentation, contact support, or connect with our sales team. You can also chat live with other developers in #stripe on freenode.

    Was this page helpful? Yes No

    Send

    Thank you for helping improve Stripe's documentation. If you need help or have any questions, please consider contacting support.