Skip to main content
Every webhook request from Kyren Pay includes a cryptographic signature that you should verify to ensure the request is authentic and hasn’t been tampered with.

Signature Algorithm

Kyren Pay uses HMAC-SHA256 to sign webhook payloads:
signature = "sha256=" + HMAC-SHA256(timestamp + "." + payload, webhook_secret)
The signature and timestamp are sent in HTTP headers:
HeaderExample
X-Kyren-Signaturesha256=5d2dc4f1a...
X-Kyren-Timestamp1704628800

Verification Steps

1

Extract headers

Read X-Kyren-Signature and X-Kyren-Timestamp from the request headers.
2

Check timestamp

Verify the timestamp is within 5 minutes (300 seconds) of the current time. This prevents replay attacks.
3

Compute expected signature

Concatenate timestamp + "." + raw_request_body, then compute HMAC-SHA256 using your webhook secret.
4

Compare signatures

Compare the computed signature with the one in the header. Use constant-time comparison to prevent timing attacks.

Code Examples

Node.js

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, timestamp, secret) {
  // Check timestamp tolerance (5 minutes)
  const currentTime = Math.floor(Date.now() / 1000);
  if (Math.abs(currentTime - parseInt(timestamp)) > 300) {
    return false;
  }

  // Compute expected signature
  const data = `${timestamp}.${payload}`;
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(data)
    .digest('hex');

  // Constant-time comparison
  try {
    return crypto.timingSafeEqual(
      Buffer.from(expected),
      Buffer.from(signature)
    );
  } catch {
    return false;
  }
}

// Usage in Express
app.post('/webhooks/kyren',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const isValid = verifyWebhookSignature(
      req.body.toString(),
      req.headers['x-kyren-signature'],
      req.headers['x-kyren-timestamp'],
      process.env.KYREN_WEBHOOK_SECRET
    );

    if (!isValid) {
      return res.status(400).send('Invalid signature');
    }

    // Process the event...
    res.status(200).send('OK');
  }
);

Python

import hmac
import hashlib
import time

def verify_webhook_signature(payload: str, signature: str, timestamp: str, secret: str) -> bool:
    # Check timestamp tolerance (5 minutes)
    current_time = int(time.time())
    if abs(current_time - int(timestamp)) > 300:
        return False

    # Compute expected signature
    data = f"{timestamp}.{payload}"
    expected = "sha256=" + hmac.new(
        secret.encode("utf-8"),
        data.encode("utf-8"),
        hashlib.sha256
    ).hexdigest()

    # Constant-time comparison
    return hmac.compare_digest(expected, signature)


# Usage in Flask
from flask import Flask, request

app = Flask(__name__)

@app.route("/webhooks/kyren", methods=["POST"])
def webhook():
    payload = request.get_data(as_text=True)
    signature = request.headers.get("X-Kyren-Signature", "")
    timestamp = request.headers.get("X-Kyren-Timestamp", "")

    if not verify_webhook_signature(payload, signature, timestamp, WEBHOOK_SECRET):
        return "Invalid signature", 400

    event = request.get_json()
    # Process the event...

    return "OK", 200

Go

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"math"
	"net/http"
	"strconv"
	"time"
)

func verifyWebhookSignature(payload, signature, timestamp, secret string) bool {
	// Check timestamp tolerance (5 minutes)
	ts, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return false
	}
	currentTime := time.Now().Unix()
	if math.Abs(float64(currentTime-ts)) > 300 {
		return false
	}

	// Compute expected signature
	data := fmt.Sprintf("%s.%s", timestamp, payload)
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(data))
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))

	// Constant-time comparison
	return hmac.Equal([]byte(expected), []byte(signature))
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	payload := string(body)
	signature := r.Header.Get("X-Kyren-Signature")
	timestamp := r.Header.Get("X-Kyren-Timestamp")

	if !verifyWebhookSignature(payload, signature, timestamp, webhookSecret) {
		http.Error(w, "Invalid signature", http.StatusBadRequest)
		return
	}

	// Process the event...
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OK"))
}
Important security considerations:
  • Always verify signatures before processing events
  • Use constant-time comparison functions to prevent timing attacks
  • Reject requests with timestamps older than 5 minutes to prevent replay attacks
  • Use the raw request body for signature verification (before JSON parsing)