use serde::Deserialize;
use crate::error::RazorpayError;
use crate::resources::invoices::Invoice;
use crate::resources::orders::Order;
use crate::resources::payments::Payment;
use crate::resources::refunds::Refund;
use crate::resources::subscriptions::Subscription;
use crate::signature::verify_webhook_signature;
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Wrapped<T> {
pub entity: T,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct PaymentPayload {
pub payment: Wrapped<Payment>,
#[serde(default)]
pub order: Option<Wrapped<Order>>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct OrderPayload {
pub order: Wrapped<Order>,
#[serde(default)]
pub payment: Option<Wrapped<Payment>>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct RefundPayload {
pub refund: Wrapped<Refund>,
#[serde(default)]
pub payment: Option<Wrapped<Payment>>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct SubscriptionPayload {
pub subscription: Wrapped<Subscription>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct InvoicePayload {
pub invoice: Wrapped<Invoice>,
#[serde(default)]
pub payment: Option<Wrapped<Payment>>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(tag = "event", content = "payload", remote = "Self")]
pub enum WebhookEvent {
#[serde(rename = "payment.authorized")]
PaymentAuthorized(PaymentPayload),
#[serde(rename = "payment.captured")]
PaymentCaptured(PaymentPayload),
#[serde(rename = "payment.failed")]
PaymentFailed(PaymentPayload),
#[serde(rename = "order.paid")]
OrderPaid(OrderPayload),
#[serde(rename = "refund.created")]
RefundCreated(RefundPayload),
#[serde(rename = "refund.processed")]
RefundProcessed(RefundPayload),
#[serde(rename = "refund.failed")]
RefundFailed(RefundPayload),
#[serde(rename = "subscription.authenticated")]
SubscriptionAuthenticated(SubscriptionPayload),
#[serde(rename = "subscription.activated")]
SubscriptionActivated(SubscriptionPayload),
#[serde(rename = "subscription.charged")]
SubscriptionCharged(SubscriptionPayload),
#[serde(rename = "subscription.cancelled")]
SubscriptionCancelled(SubscriptionPayload),
#[serde(rename = "subscription.paused")]
SubscriptionPaused(SubscriptionPayload),
#[serde(rename = "subscription.halted")]
SubscriptionHalted(SubscriptionPayload),
#[serde(rename = "subscription.completed")]
SubscriptionCompleted(SubscriptionPayload),
#[serde(rename = "invoice.paid")]
InvoicePaid(InvoicePayload),
#[serde(rename = "invoice.expired")]
InvoiceExpired(InvoicePayload),
#[serde(other)]
Unknown,
}
impl<'de> serde::Deserialize<'de> for WebhookEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
Ok(WebhookEvent::deserialize(value).unwrap_or(WebhookEvent::Unknown))
}
}
impl WebhookEvent {
pub fn parse_verified(
raw_body: &str,
signature: &str,
webhook_secret: &str,
) -> Result<Self, RazorpayError> {
verify_webhook_signature(raw_body, signature, webhook_secret)?;
Ok(serde_json::from_str(raw_body)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::signature::compute_signature;
const CAPTURED: &str = r#"{"event":"payment.captured","payload":{"payment":{"entity":
{"id":"pay_1","amount":50000,"currency":"INR","status":"captured","created_at":1}}}}"#;
#[test]
fn parses_payment_captured() {
let event: WebhookEvent = serde_json::from_str(CAPTURED).unwrap();
match event {
WebhookEvent::PaymentCaptured(p) => {
assert_eq!(p.payment.entity.id, "pay_1");
assert!(p.payment.entity.is_captured());
}
other => panic!("expected PaymentCaptured, got {other:?}"),
}
}
#[test]
fn unmodelled_event_becomes_unknown_rather_than_erroring() {
let json = r#"{"event":"virtual_account.credited","payload":{"anything":1}}"#;
assert_eq!(serde_json::from_str::<WebhookEvent>(json).unwrap(), WebhookEvent::Unknown);
}
#[test]
fn parse_verified_rejects_bad_signature_before_parsing() {
let err = WebhookEvent::parse_verified(CAPTURED, "deadbeef", "whsec").unwrap_err();
assert!(matches!(err, RazorpayError::SignatureMismatch));
}
#[test]
fn parse_verified_accepts_good_signature() {
let sig = compute_signature(CAPTURED, "whsec");
let event = WebhookEvent::parse_verified(CAPTURED, &sig, "whsec").unwrap();
assert!(matches!(event, WebhookEvent::PaymentCaptured(_)));
}
#[test]
fn subscription_charged_parses() {
let json = r#"{"event":"subscription.charged","payload":{"subscription":{"entity":
{"id":"sub_1","plan_id":"plan_1","status":"active"}}}}"#;
match serde_json::from_str::<WebhookEvent>(json).unwrap() {
WebhookEvent::SubscriptionCharged(s) => assert_eq!(s.subscription.entity.id, "sub_1"),
other => panic!("expected SubscriptionCharged, got {other:?}"),
}
}
}