Skip to main content

razorpay_api/resources/
webhooks.rs

1//! Typed webhook events.
2//!
3//! # Always verify before parsing
4//!
5//! Parsing tells you what an event *says*; it does not tell you Razorpay sent it.
6//! Verify the `X-Razorpay-Signature` header against the **raw request body** with
7//! [`crate::signature::verify_webhook_signature`] first,
8//! then parse that same string. See [`WebhookEvent::parse_verified`], which does
9//! both in the right order.
10
11use serde::Deserialize;
12
13use crate::error::RazorpayError;
14use crate::resources::invoices::Invoice;
15use crate::resources::orders::Order;
16use crate::resources::payments::Payment;
17use crate::resources::refunds::Refund;
18use crate::resources::subscriptions::Subscription;
19use crate::signature::verify_webhook_signature;
20
21/// Razorpay nests every entity one level deep, as `{"entity": {...}}`.
22#[derive(Debug, Clone, PartialEq, Deserialize)]
23pub struct Wrapped<T> {
24    /// The entity itself.
25    pub entity: T,
26}
27
28/// Payload of a payment-related event.
29#[derive(Debug, Clone, PartialEq, Deserialize)]
30pub struct PaymentPayload {
31    /// The payment the event is about.
32    pub payment: Wrapped<Payment>,
33    /// The order it belongs to, when Razorpay includes it.
34    #[serde(default)]
35    pub order: Option<Wrapped<Order>>,
36}
37
38/// Payload of an order-related event.
39#[derive(Debug, Clone, PartialEq, Deserialize)]
40pub struct OrderPayload {
41    /// The order the event is about.
42    pub order: Wrapped<Order>,
43    /// The payment that paid it, when included.
44    #[serde(default)]
45    pub payment: Option<Wrapped<Payment>>,
46}
47
48/// Payload of a refund-related event.
49#[derive(Debug, Clone, PartialEq, Deserialize)]
50pub struct RefundPayload {
51    /// The refund the event is about.
52    pub refund: Wrapped<Refund>,
53    /// The payment being refunded, when included.
54    #[serde(default)]
55    pub payment: Option<Wrapped<Payment>>,
56}
57
58/// Payload of a subscription-related event.
59#[derive(Debug, Clone, PartialEq, Deserialize)]
60pub struct SubscriptionPayload {
61    /// The subscription the event is about.
62    pub subscription: Wrapped<Subscription>,
63}
64
65/// Payload of an invoice-related event.
66#[derive(Debug, Clone, PartialEq, Deserialize)]
67pub struct InvoicePayload {
68    /// The invoice the event is about.
69    pub invoice: Wrapped<Invoice>,
70    /// The payment that settled it, when included.
71    #[serde(default)]
72    pub payment: Option<Wrapped<Payment>>,
73}
74
75/// A webhook event, dispatched on its `event` field.
76///
77/// [`Unknown`](WebhookEvent::Unknown) catches every event this crate does not
78/// model. You enable events in the Razorpay dashboard independently of this
79/// crate's version, so an unmodelled event must not break your handler.
80#[derive(Debug, Clone, PartialEq, Deserialize)]
81#[serde(tag = "event", content = "payload", remote = "Self")]
82pub enum WebhookEvent {
83    /// A payment was authorized but not yet captured.
84    #[serde(rename = "payment.authorized")]
85    PaymentAuthorized(PaymentPayload),
86
87    /// A payment was captured — the money is yours.
88    #[serde(rename = "payment.captured")]
89    PaymentCaptured(PaymentPayload),
90
91    /// A payment attempt failed.
92    #[serde(rename = "payment.failed")]
93    PaymentFailed(PaymentPayload),
94
95    /// An order was paid in full.
96    #[serde(rename = "order.paid")]
97    OrderPaid(OrderPayload),
98
99    /// A refund was created.
100    #[serde(rename = "refund.created")]
101    RefundCreated(RefundPayload),
102
103    /// A refund completed.
104    #[serde(rename = "refund.processed")]
105    RefundProcessed(RefundPayload),
106
107    /// A refund failed; the money stayed with you.
108    #[serde(rename = "refund.failed")]
109    RefundFailed(RefundPayload),
110
111    /// A subscription was authenticated by the customer.
112    #[serde(rename = "subscription.authenticated")]
113    SubscriptionAuthenticated(SubscriptionPayload),
114
115    /// A subscription became active.
116    #[serde(rename = "subscription.activated")]
117    SubscriptionActivated(SubscriptionPayload),
118
119    /// A subscription was charged for a cycle.
120    #[serde(rename = "subscription.charged")]
121    SubscriptionCharged(SubscriptionPayload),
122
123    /// A subscription was cancelled.
124    #[serde(rename = "subscription.cancelled")]
125    SubscriptionCancelled(SubscriptionPayload),
126
127    /// A subscription was paused.
128    #[serde(rename = "subscription.paused")]
129    SubscriptionPaused(SubscriptionPayload),
130
131    /// A subscription ran out of retries.
132    #[serde(rename = "subscription.halted")]
133    SubscriptionHalted(SubscriptionPayload),
134
135    /// A subscription finished its scheduled cycles.
136    #[serde(rename = "subscription.completed")]
137    SubscriptionCompleted(SubscriptionPayload),
138
139    /// An invoice was paid.
140    #[serde(rename = "invoice.paid")]
141    InvoicePaid(InvoicePayload),
142
143    /// An invoice went past its due date.
144    #[serde(rename = "invoice.expired")]
145    InvoiceExpired(InvoicePayload),
146
147    /// An event this crate does not model, or one whose payload did not match the
148    /// shape expected for its type.
149    #[serde(other)]
150    Unknown,
151}
152
153// `#[serde(other)]` only accepts a unit variant, and a unit variant cannot absorb
154// the `payload` object that every real event carries — so the derived impl alone
155// errors on unmodelled events, exactly the breakage `Unknown` exists to prevent.
156// Deriving onto a remote shadow and falling back here keeps the variant list
157// declarative while making the fallback total.
158impl<'de> serde::Deserialize<'de> for WebhookEvent {
159    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
160    where
161        D: serde::Deserializer<'de>,
162    {
163        let value = serde_json::Value::deserialize(deserializer)?;
164        Ok(WebhookEvent::deserialize(value).unwrap_or(WebhookEvent::Unknown))
165    }
166}
167
168impl WebhookEvent {
169    /// Verify `raw_body` against `signature`, then parse it.
170    ///
171    /// This is the only entry point that cannot be used in the wrong order. It
172    /// returns [`RazorpayError::SignatureMismatch`] if the body was not signed by
173    /// `webhook_secret`, and never parses in that case.
174    ///
175    /// `raw_body` must be the **exact bytes** of the request. Do not parse and
176    /// re-serialize before calling — that changes the digest and always fails.
177    ///
178    /// # Examples
179    ///
180    /// ```
181    /// use razorpay_api::resources::WebhookEvent;
182    /// use razorpay_api::signature::compute_signature;
183    ///
184    /// let secret = "webhook_secret";
185    /// let raw_body = r#"{"event":"payment.captured","payload":{"payment":{"entity":
186    ///     {"id":"pay_1","amount":50000,"currency":"INR","status":"captured","created_at":1}}}}"#;
187    /// let signature = compute_signature(raw_body, secret);
188    ///
189    /// match WebhookEvent::parse_verified(raw_body, &signature, secret)? {
190    ///     WebhookEvent::PaymentCaptured(p) => {
191    ///         assert_eq!(p.payment.entity.id, "pay_1");
192    ///     }
193    ///     other => panic!("unexpected event: {other:?}"),
194    /// }
195    ///
196    /// // A forged body is rejected before parsing.
197    /// assert!(WebhookEvent::parse_verified(raw_body, "00", secret).is_err());
198    /// # Ok::<(), razorpay_api::RazorpayError>(())
199    /// ```
200    pub fn parse_verified(
201        raw_body: &str,
202        signature: &str,
203        webhook_secret: &str,
204    ) -> Result<Self, RazorpayError> {
205        verify_webhook_signature(raw_body, signature, webhook_secret)?;
206        Ok(serde_json::from_str(raw_body)?)
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::signature::compute_signature;
214
215    const CAPTURED: &str = r#"{"event":"payment.captured","payload":{"payment":{"entity":
216        {"id":"pay_1","amount":50000,"currency":"INR","status":"captured","created_at":1}}}}"#;
217
218    #[test]
219    fn parses_payment_captured() {
220        let event: WebhookEvent = serde_json::from_str(CAPTURED).unwrap();
221        match event {
222            WebhookEvent::PaymentCaptured(p) => {
223                assert_eq!(p.payment.entity.id, "pay_1");
224                assert!(p.payment.entity.is_captured());
225            }
226            other => panic!("expected PaymentCaptured, got {other:?}"),
227        }
228    }
229
230    #[test]
231    fn unmodelled_event_becomes_unknown_rather_than_erroring() {
232        let json = r#"{"event":"virtual_account.credited","payload":{"anything":1}}"#;
233        assert_eq!(serde_json::from_str::<WebhookEvent>(json).unwrap(), WebhookEvent::Unknown);
234    }
235
236    #[test]
237    fn parse_verified_rejects_bad_signature_before_parsing() {
238        let err = WebhookEvent::parse_verified(CAPTURED, "deadbeef", "whsec").unwrap_err();
239        assert!(matches!(err, RazorpayError::SignatureMismatch));
240    }
241
242    #[test]
243    fn parse_verified_accepts_good_signature() {
244        let sig = compute_signature(CAPTURED, "whsec");
245        let event = WebhookEvent::parse_verified(CAPTURED, &sig, "whsec").unwrap();
246        assert!(matches!(event, WebhookEvent::PaymentCaptured(_)));
247    }
248
249    #[test]
250    fn subscription_charged_parses() {
251        let json = r#"{"event":"subscription.charged","payload":{"subscription":{"entity":
252            {"id":"sub_1","plan_id":"plan_1","status":"active"}}}}"#;
253        match serde_json::from_str::<WebhookEvent>(json).unwrap() {
254            WebhookEvent::SubscriptionCharged(s) => assert_eq!(s.subscription.entity.id, "sub_1"),
255            other => panic!("expected SubscriptionCharged, got {other:?}"),
256        }
257    }
258}