delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Webhook signature verification.
//!
//! DeloPay signs every outgoing webhook with **HMAC-SHA512 over the raw request
//! body**, using your shop's webhook signing secret (the *payment response hash
//! key* configured on the shop). The hex digest is delivered in the
//! `X-Webhook-Signature-512` header.
//!
//! Always verify the **raw bytes** of the request, before any JSON parsing —
//! re-serializing the body first will not match the signature.

use hmac::{Hmac, KeyInit, Mac};
use serde::Deserialize;
use serde_json::Value;
use sha2::Sha512;

use crate::core::encoding::hex_decode;
use crate::core::error::{DelopayError, Result};
use crate::core::models::payment::PaymentResponse;

/// HTTP header carrying the hex-encoded HMAC-SHA512 signature.
pub const SIGNATURE_HEADER: &str = "X-Webhook-Signature-512";

type HmacSha512 = Hmac<Sha512>;

/// A parsed, signature-verified DeloPay webhook event.
///
/// Matches the signed wire body exactly:
/// `{ merchant_id, event_id, event_type, content: { type, object }, timestamp }`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookEvent {
    /// ID of the merchant that owns this event.
    pub merchant_id: String,
    /// Unique event ID (stable across delivery retries).
    pub event_id: String,
    /// Event type identifier, e.g. `"payment_succeeded"` or `"refund_succeeded"`.
    pub event_type: String,
    /// The event payload, tagged by kind.
    pub content: WebhookContent,
    /// ISO 8601 timestamp at which the webhook was sent.
    pub timestamp: String,
    /// Any additional fields present on the wire but not modeled here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The tagged payload of a webhook event: `{ "type": …, "object": … }`.
///
/// `object` is kept as a raw [`serde_json::Value`] for forward-compatibility;
/// use the typed accessors (e.g. [`WebhookContent::as_payment`]) to deserialize
/// the shapes this crate models.
#[derive(Debug, Clone, Deserialize)]
pub struct WebhookContent {
    /// Payload kind, e.g. `"payment_details"`, `"refund_details"`.
    #[serde(rename = "type")]
    pub kind: String,
    /// The payload object.
    pub object: Value,
}

impl WebhookContent {
    /// Deserialize the payload as a [`PaymentResponse`] when
    /// `kind == "payment_details"`.
    pub fn as_payment(&self) -> Option<PaymentResponse> {
        if self.kind == "payment_details" {
            serde_json::from_value(self.object.clone()).ok()
        } else {
            None
        }
    }

    /// Deserialize the payload into any type you provide, regardless of `kind`.
    pub fn deserialize<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_value(self.object.clone()).map_err(|e| DelopayError::Decode(e.to_string()))
    }
}

/// Verify an incoming webhook and return the parsed event.
///
/// - `raw_body` — the **unmodified** request body bytes (do not parse first).
/// - `signature_header` — the value of the `X-Webhook-Signature-512` header.
/// - `secret` — your shop's webhook signing secret.
///
/// Returns [`DelopayError::InvalidSignatureFormat`] if the header is not valid
/// hex, and [`DelopayError::InvalidSignature`] if it does not match the body.
///
/// The comparison is constant-time.
pub fn verify(raw_body: &[u8], signature_header: &str, secret: &str) -> Result<WebhookEvent> {
    let signature =
        hex_decode(signature_header.trim()).ok_or(DelopayError::InvalidSignatureFormat)?;

    let mut mac =
        HmacSha512::new_from_slice(secret.as_bytes()).expect("HMAC accepts keys of any length");
    mac.update(raw_body);
    mac.verify_slice(&signature)
        .map_err(|_| DelopayError::InvalidSignature)?;

    serde_json::from_slice(raw_body).map_err(|e| DelopayError::Decode(e.to_string()))
}