LogoLogo
No-code docsResources
  • 🖥️Welcome to the Bird API Docs
  • API Access
    • Access Policies
    • Access Roles
    • API Authorization
    • Common API usage
  • Conversations API
    • API reference
      • Channel configuration
        • Get conversations configuration
        • Update conversations configuration
      • Conversations messaging
        • Create conversation message
        • List conversation messages
        • Get conversation message
        • Update conversation message
        • Delete conversation message
        • Create pre-signed upload
      • Conversations management
        • Create conversation
        • List conversations
        • Get conversation
        • Update conversation
        • Delete conversation
      • Conversation Participants
        • Add participant to conversation
        • List participants
        • Get participant by ID
        • Get participant by identifier key and value
        • Update participant by ID
        • Update participant by identifier key and value
        • Delete participant
        • List participant conversations by ID
        • List participant conversations by identifier key and value
      • Workspace settings
        • Get antispam setting
        • Update antispam setting
        • Create allow/block rule
        • Get allow/block rule
        • List allow/block rules
        • Update allow/block rule
        • Delete allow/block rule
        • Add allow/block rules in bulk
        • Get allow/block bulk upload status
      • Events
  • Collaborations API
    • API reference
      • Agent Management
      • Team Management
      • Feeds
      • Feed item activity
      • Tags
      • Automation Rules
      • Business Hours
      • Capacity Rules
      • Routing Queues
      • Skills
      • SLA Policies
      • Macros
      • Sender Profiles
      • Ticket fields
  • Channels API
    • Supported channels
      • Programmable WhatsApp
        • Sending WhatsApp messages
        • Customer service window
        • Receiving messages
        • Message interactions
        • WhatsApp ISV integration
          • Setting up your customer workspaces
            • API Access
            • Associating your Facebook solution ID and business ID with your Bird CRM Organization
            • Creating a workspace for your customer
            • Buying a number through Bird
            • Subscribing to channel created webhooks
          • WhatsApp channel onboarding
            • Setting up the WhatsApp Embedded flow
            • Install WhatsApp phone number in Bird CRM
            • Subscribe to channel webhooks
      • Programmable SMS
        • Installing an SMS channel
          • US 10DLC API Installation
          • Toll-Free Numbers Verification API
        • Sending SMS messages
        • Receiving messages
        • Twilio Exit API
          • Using Twilio PHP SDK
          • Using Twilio Go SDK
          • Using Twilio Ruby SDK
        • Sinch Exit API
      • Programmable RCS
        • Sending messages
        • Receiving messages
        • Message interactions
      • Programmable Email
        • Sending Emails
        • Receiving messages
        • Message status
        • Message interactions
      • Programmable Line
        • Sending messages
        • Receiving messages
        • Message interactions
      • Programmable Telegram
        • Sending messages
        • Receiving messages
        • Message interactions
    • Message types
      • Text
      • Images
      • Files
      • List
      • Carousel
      • Template
    • Message status and interactions
      • Message Failure Codes
      • Message Failure Sources
        • SMS Platform Extended Error Codes
    • Send batch messages
    • API reference
      • Channel Groups
      • Messaging
      • Channels management
      • Channel connectors
      • Navigators
      • Compliance Keywords Messages
      • Conversions Sharing
      • Events
    • Rate Limit
  • Voice API
    • Installing a Voice channel
    • Voice Calls API
      • Initiate an outbound call
      • List calls from a channel
      • Get a call
      • Update a call
      • Answer a call
      • Ring a call
      • Hangup a call
      • Play a message in a call
      • Say Text-To-Speech (TTS)
      • Gather DTMF from a call
      • Forward a call
      • Record a Call
      • Record a call session
      • Update a call recording
      • List call recordings of a call
      • Get a call recording
      • Get a call insights
      • Get calls log
    • Recordings API
      • List Recordings
      • Get a Recording
      • Delete a Recording
      • List recording storage metrics
    • Transcriptions API
      • Initiate a Transcription
      • List Transcriptions
      • Get a Transcription
      • Delete a Transcription
    • Voice webhooks
    • Flash Calling API
  • Verify API
    • Verify API: Quick Start
  • Contacts API
    • Tracking Contact Events
      • API Reference
        • Get configuration
        • Track events
    • API reference
      • Manage workspace contacts
        • Create a contact
        • Get a contact
        • List contacts
        • Search contact by identifier
        • Update a contact
        • Create or update a contact by identifier
        • Delete a contact
      • Manage contact identifiers
        • Create contact identifier
        • List contact identifiers
        • Delete contact identifier
      • Manage contact attribute definition
        • Create attribute definition
        • Get attribute definition
        • List attribute definitions
      • Manage contact lists
        • Create a list
        • Get a list
        • List lists
        • Update a list
        • Delete a list
        • Add contacts to a list
        • Get contact list memberships
        • List contacts in a list
        • Remove contacts from a list
      • Lookup
        • Network/Country information for a phone number
  • Numbers API
    • API reference
      • Search Available Numbers
      • Buy a Number
      • List your Numbers
      • Get Long Code Number Details
      • Manage Endpoint Subscriptions
        • Cancel Number Subscription
      • Manage Endpoint Compliance Requirements
        • List Workspace compliace Requirements
        • Get Workspace Compliace Requirements
        • Update Workspace Compliace Requirements
      • 10DLC Compliance
        • Brands - Organization
          • Create a brand
          • List all brands
          • Get a brand
          • Update a brand
          • Delete a brand
          • Create a brand vetting
        • Brands - workspace
          • Create a brand
          • List all brands
          • Get a brand
          • Update a brand
          • Delete a brand
          • Create a brand vetting
          • List brand vettings
        • Campaigns
          • Optional: acting as Reseller
          • Create a campaign
          • List all campaigns
          • Get a campaign
          • Update a campaign
          • Delete a campaign
        • TCR Enums
        • Events
      • Toll-Free Numbers Verification API
      • Long Code Numbers
      • Short Code Numbers
      • Alphanumeric Senders
      • Events
  • Know-Your-Customer (KYC) API
    • List KYC forms
    • Get KYC form
    • Create KYC form entry
    • Update KYC form entry
    • List KYC form entries
    • Get a KYC form entry details
  • Reporting API
    • API reference
      • Channel Metrics
      • Flow Run Metrics
      • Wallet Metrics
      • Campaign Metrics
      • Message Metrics
  • Accounts API
    • API reference
      • Current user
        • Change password
        • Presigned upload
        • Memberships
        • Sessions
        • Configurations
          • Groups
            • Keys
      • IAM policies
      • Organizations
        • Upload media
        • Profile
        • Workspaces
        • Users
        • Access keys
        • Organization roles
        • Organization policies
        • Teams
          • Members
        • Approvals
          • Runs
            • Reviews
        • Configurations
          • Groups
            • Keys
      • Region groups
  • Touchpoints API
    • Supported Projects
      • Whatsapp Approved Message Templates
        • Creating WhatsApp Message templates
          • Text template blocks
          • Blocks Documentation
    • API reference
      • Projects
      • Message Templates
  • Notifications API
    • API Reference
      • Webhook subscriptions
        • Create a webhook subscription
        • List available webhook events
        • Get a webhook subscription
        • List webhook subscriptions
        • Update a webhook subscription
        • Delete a webhook subscription
        • Verifying a webhook subscription
        • Webhook subscription logs
  • Knowledge Base (KB) API
    • API reference
      • Documents
      • Folders
        • Import
      • Search
      • Presigned upload
  • Email API
    • Transmissions
  • Connectivity platform migration guide
    • Channels API and Conversations API
    • Migrating conversations API actions
    • Migrating WhatsApp channels
  • Client SDKs
    • Applications
    • Contact Profiles
      • Signed Identity
    • Push notifications
      • Quick Start
      • Subscribe contacts to push notification campaigns
      • Notification Display Priority
    • Event Tracking
      • Quick Start
      • Track Events
        • App
        • Audiences
        • Conference
        • Ecommerce
        • Hospitality
        • Lists
        • Messaging
        • Payments
        • Subscription
        • Suppressions
        • Survey
        • Web
    • App Inbox
      • Quick Start
      • Usage
      • Subscribe contacts to app inbox campaigns
    • SDK Integration
      • Android SDK
        • Notification Interactions
      • Swift SDK
        • Notification Interactions
      • Web SDK
        • Quick Start
        • Usage
        • API Reference
          • IdentityManager
          • BirdSdkApi
          • BirdTracker
            • Ecommerce
            • Conference
            • Messaging
            • Suppressions
            • Subscription
            • Survey
            • Web
            • Audiences
        • Web Push Notifications
          • Notification Interactions
  • Quickstarts
    • Conversations
    • Send an SMS message
    • Send an Email message
    • Send a WhatsApp message
Powered by GitBook
On this page

Was this helpful?

  1. Notifications API
  2. API Reference
  3. Webhook subscriptions

Verifying a webhook subscription

Last updated 5 months ago

Was this helpful?

If you have created your using a signingKey you can validate the authenticity of the webhook by validating the request signature sent in the request header.

From the incoming webhook, parse the following request headers:

messagebird-signature

messagebird-request-timestamp

In addition, parse the request URL and the request Body.

To calculate the request signature:

  1. Base64 decode the messagebird-signature header;

  2. Create a SHA256 hash checksum of the request body as a binary result;

  3. Join the request timestamp (messagebird-request-timestamp header) with the request URL and request body checksum computed in step 2, separated by a new line (\n);

  4. Calculate HMACSHA256 using the signing key as the secret and the joined payload from step 3 to calculate the signature;

  5. Compare the output of Step 4 with the signature from Step 1. The code snippets below illustrate the intended process. We recommend tailoring these examples to fit your preferred programming language, codebase, or framework.

Examples

The following code snippets are provided to illustrate the intended process. We recommend adapting them to your preferred programming language, codebase, or framework to ensure compatibility.

<?php

function verifyWebhookSignature(
    string $headerSignature,
    string $headerTimestamp,
    string $receivedBody,
    string $requestedUrl,
    string $signingKey
): bool {
    $receivedDecodedSignature = base64_decode($headerSignature);

    $bodyHash = hash('sha256', $receivedBody, true);
    $computedSignature = hash_hmac(
        'sha256',
        sprintf("%s\n%s\n%s", $headerTimestamp, $requestedUrl, $bodyHash),
        $signingKey,
        true
    );

    return hash_equals($computedSignature, $receivedDecodedSignature);
}

// Example usage
$isVerified = verifyWebhookSignature(
    $_SERVER['HTTP_MESSAGEBIRD_SIGNATURE'],
    $_SERVER['HTTP_MESSAGEBIRD_REQUEST_TIMESTAMP'],
    file_get_contents('php://input'),
    'https://domain.com/webhook/bird',
    'secureSigningKey'
);

package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
    "os"
)

func main() {
    var key string
    var signatureHeader string
    var timestampHeader string
    var url string
    var body []byte

    // Example usage
    match, err := checkSignature(key, signatureHeader, timestampHeader, url, body)
    if err != nil {
       // Error out
       fmt.Printf("something went wrong: %v", err)
       os.Exit(1)
    }

    if !match {
       // Signature doesn't match
       fmt.Println("Signatures don't match!")
    } else {
       // Signature matches
       fmt.Println("Signatures match!")
    }
}

// checkSignature verifies the Bird style HMAC-SHA256 signature for the given data.
func checkSignature(signingKey, signatureHeader, timestampHeader, requestURL string, data []byte) (bool, error) {
    // Step 1: Decode the signature from the header
    actualSignature, err := base64.StdEncoding.DecodeString(signatureHeader)
    if err != nil {
       return false, err
    }

    // Step 2 - 4: Calculate the expected signature
    expectedSignature, err := signSha256(signingKey, timestampHeader, requestURL, data)
    if err != nil {
       return false, err
    }

    // Step 5: Compare the expected signature with the actual signature
    return hmac.Equal(expectedSignature, actualSignature), nil
}

// signSha256 returns the Bird style HMAC-SHA1 signature for the given data.
func signSha256(signingKey, timestamp, requestURL string, data []byte) ([]byte, error) {
    // Step 2: Calculate the SHA256 hash for the given data
    bh := sha256.Sum256(data)

    // Step 3: Concatenate the timestamp, request URL, and the SHA256 hash, separated by a newline character
    var m bytes.Buffer
    _, err := fmt.Fprintf(&m, "%s\n%s\n%s", timestamp, requestURL, bh)
    if err != nil {
       return []byte{}, err
    }

    // Step 4: Calculate the HMAC-SHA256 hash for the concatenated string using the signing key
    mac := hmac.New(sha256.New, []byte(signingKey))
    if _, err := mac.Write(m.Bytes()); err != nil {
       return []byte{}, err
    }
    return mac.Sum(nil), nil
}
import hashlib
import hmac
import base64
import time

class SignedRequest:
    def __init__(self, requestSignature, requestTimestamp, requestBody, requestUrl):
        self._requestSignature = requestSignature
        self._requestTimestamp = str(requestTimestamp)
        self._requestBody = requestBody
        self._requestUrl = requestUrl

    def verify(self, signing_key):
        payload = self._build_payload()
        expected_signature = base64.b64decode(self._requestSignature)
        calculated_signature = hmac.new(signing_key.encode('latin-1'), payload.encode('latin-1'),
                                        hashlib.sha256).digest()
        return expected_signature == calculated_signature

    def is_recent(self, offset=10):
        return int(time.time()) - int(self._requestTimestamp) < offset

    def _build_payload(self):
        checksum_body = hashlib.sha256(self._requestBody.encode('latin-1')).digest()
        str_checksum_body = checksum_body.decode('latin-1')
        parts = [self._requestTimestamp, self._requestUrl, str_checksum_body]
        return "\n".join(parts)
webhook subscription
Example of header content used for validation. You can see the messagebird-signature and the messagebird-request-timestamp, which are used to validate the request. The event reference is the messagebird-request-id, which can be used for debugging failures using Webhook subscription logs. For more information regarding logs, refer to Webhook subscription logs.