Open navigation

Klevu Webhook Integration Guide

Welcome to the Klevu Webhook Integration Guide! This guide explains how to integrate and validate webhooks sent by Klevu to your application. Webhooks allow your application to receive real-time updates from Klevu when specific events occur.

How It Works

Klevu sends a POST request to your configured endpoint whenever an event occurs. To ensure security, each request includes:

  • X-KLEVU-HMAC: A cryptographic signature to verify the authenticity of the request.
  • X-KLEVU-TIMESTAMP: A timestamp of when the request was generated, helping prevent replay attacks.
  • X-KLEVU-APIKEY: Klevu apikey of the store.

You must verify the HMAC signature before processing the webhook.

Webhook Configuration

To configure a webhook in Klevu, contact Klevu Support with the following details:

Request Body Example

{
  "endpoint": "https://your-application-endpoint.com/webhook",
  "eventTypes": [
    "vm.default.rules"
  ],
  "apiKeys": [
    "klevu-16952739575191599",
    "klevu-17183706041591599",
    "klevu-17183619175271599"
  ],
}

Parameters

  • endpoint: Your application's URL where Klevu will send webhook events.
  • eventTypes: List of event types to subscribe to (e.g., vm.default.rules).
  • apiKeys: Keys for which webhook will be generated

Validating Webhook Requests

1. Extract Headers

Each webhook request includes the following headers:

HeaderDescription
X-KLEVU-HMACBase64-encoded HMAC signature for validating the request.
X-KLEVU-TIMESTAMPTimestamp of the request in ISO 8601 format, used to prevent replay attacks.
X-KLEVU-APIKEYApiKey of the store

2. Verify HMAC Signature

To validate the request's authenticity:

  1. Convert the request body into single line json(Minified) string.
    Example Minified JSON Output.
    {"id":"39f0290a-3eb1-4cec-a8fd-71a0792f3d15","apiVersion":"1.0","created":"2024-11-14T08:21:40.004166976","type":"vm.default.rules","apikey":"klevu-1719389107060243","data":{"payload":{"action":"UPDATE","eventObject":{"categories":[{"categoryPath":"automated collection"}]}}}}

    To minify or compress a JSON string to a single line, you can use various libraries depending on your programming language. 

    1. Use JSON Minifier by Code Beautify for a quick online solution.
  2. Hash the resulting string using HMAC-SHA256 with rest auth key of the X-KLEVU-APIKEY.
  3. Compare the computed hash with the value in the X-Klevu-HMAC header.

Example: HMAC Validation (Java)

   /**
     * Verifies the HMAC of a message using the provided secret and HMAC.
     *
     * @param requestBody       The original message (payload) whose HMAC needs to be verified.
     * @param restAuthKey       Refer the X-KLEVU-APIKEY and fetch rest auth key to compute the HMAC.
     * @param providedHmac      The HMAC received, which needs to be validated.
     * @throws Exception if an error occurs during HMAC computation.
     */
    public boolean verifyHmac(String requestBody, String restAuthKey, String providedHmac) throws Exception {
        // Initialize the HMAC-SHA256 Mac instance
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(restAuthKey.getBytes(), "HmacSHA256");
        mac.init(secretKeySpec);

        // Compute the HMAC for the given message
        byte[] computedHmacBytes = mac.doFinal(requestBody.getBytes());
        String computedHmac = Base64.getEncoder().encodeToString(computedHmacBytes);

        // Verify the computed HMAC against the provided HMAC
        if (providedHmac.equals(computedHmac)) {
            return true;
        } 
        return false;
    }

3. Validate Timestamp

Ensure the timestamp (X-Klevu-Timestamp) is within a reasonable timeframe (e.g., ±10 minutes) to prevent replay attacks.

4. Webhook Request Structure

Below is an example of a webhook request sent by Klevu to your configured endpoint:

Webhook Request Example

{
  "id": "e00d94c1-bcb4-4ba9-93ac-cbf39ae37b41",
  "apiVersion": "1.0",
  "created": "2024-11-08T05:29:54.272006888",
  "type": "vm.default.rules",
  "apikey": "klevu-17183619175271599",
  "data": {
    "payload": {
      "action": "UPDATE", 
      "eventObject": {
        "categories": [
          {
            "categoryPath": "10% off"
          }
        ]
      }
    }
  }
}

Key Fields

FieldTypeDescription
idStringUnique identifier for the webhook request.
apiVersionStringVersion of the Klevu API used for this request.
createdStringTimestamp when the webhook was created.
typeStringType of event that triggered the webhook (e.g., vm.default.rules).
apikeyStringAPI key associated with this webhook event.
data.payload.actionStringAction associated with the event (e.g., UPDATE, INHERITANCE_STORE_MAPPING, INHERITANCE_PARENT_MERCHANDISING_UPDATE).
data.payload.eventObject.categoriesArray of ObjectsList of categories affected by the event.

Supported Actions

ActionDescription
UPDATEIndicates that a category, rule, or configuration has been updated.
INHERITANCE_PARENT_MERCHANDISING_UPDATEIndicates that merchandising rule updates in a parent category are propagated to its child stores.
INHERITANCE_STORE_MAPPING_UPDATEIndicates that a store inheritance  mapping is updated. A new child store is added, updated or removed from mapping.
RESETIndicates that a category, rule, or configuration has been reset.

Webhook Processing Details

  • Batching of Categories:
    • To improve efficiency and scalability, Klevu webhooks will send up to 1000 categories per webhook call.
    • If more than 1000 categories are affected, multiple webhook calls will be made.

Testing Webhooks

Using Webhook.site

  1. Register an endpoint on Webhook.site.
  2. Update your Klevu webhook configuration with the generated endpoint URL.
  3. Observe incoming requests and test validation logic.

Simulating Webhook Requests

  1. Change any vm default rules in your store

Response Codes

HTTP Status CodeMeaning
201 ACCEPTEDWebhook processed successfully.

Event Types

Below are the common event types supported by Klevu webhooks:

Event TypeDescription
vm.default.rulesTriggered for VM default rules.

Search API Caching

  • Caching Duration:
    The results of Klevu's Search API are cached for approximately 20 minutes.This caching ensures optimized performance and reduced load on the API servers.
  • Impact on Real-Time Data:
    If any updates are made to merchandising rules, they may not immediately reflect in Search API results. The cache will expire after 20 minutes, ensuring the updated data is available within this time frame.

FAQs

How do I update my webhook?

Contact Klevu Support with the updated webhook details.

How soon do updates to merchandising rules reflect in Search API results? 

Updates to merchandising rules may take up to 20 minutes to be reflected in Search API results due to caching. This ensures that changes are consistently applied and served once the cache refreshes.

What event types are supported by Klevu webhooks? 

Klevu webhooks currently support the vm.default.rules event type, which is triggered specifically for VM default rules. At this time, scheduled campaigns are not supported by Klevu webhooks.

Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.