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;
pub const SIGNATURE_HEADER: &str = "X-Webhook-Signature-512";
type HmacSha512 = Hmac<Sha512>;
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookEvent {
pub merchant_id: String,
pub event_id: String,
pub event_type: String,
pub content: WebhookContent,
pub timestamp: String,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct WebhookContent {
#[serde(rename = "type")]
pub kind: String,
pub object: Value,
}
impl WebhookContent {
pub fn as_payment(&self) -> Option<PaymentResponse> {
if self.kind == "payment_details" {
serde_json::from_value(self.object.clone()).ok()
} else {
None
}
}
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()))
}
}
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()))
}