crypto-pay-api 0.2.1

A Rust client library for Crypto Pay API provided by Telegram CryptoBot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use chrono::{DateTime, Utc};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use std::future::Future;
use std::pin::Pin;

use crate::{
    error::{CryptoBotError, WebhookErrorKind},
    models::{WebhookResponse, WebhookUpdate},
};

use super::WebhookHandlerConfig;

pub type WebhookHandlerFn =
    Box<dyn Fn(WebhookUpdate) -> Pin<Box<dyn Future<Output = Result<(), CryptoBotError>> + Send>> + Send + Sync>;

pub struct WebhookHandler {
    pub(crate) api_token: String,
    pub(crate) config: WebhookHandlerConfig,
    pub(crate) update_handler: Option<WebhookHandlerFn>,
}

impl WebhookHandler {
    pub(crate) fn with_config(api_token: impl Into<String>, config: WebhookHandlerConfig) -> Self {
        Self {
            api_token: api_token.into(),
            config,
            update_handler: None,
        }
    }

    pub fn parse_update(json: &str) -> Result<WebhookUpdate, CryptoBotError> {
        serde_json::from_str(json).map_err(|e| CryptoBotError::WebhookError {
            kind: WebhookErrorKind::InvalidPayload,
            message: e.to_string(),
        })
    }

    /// Verifies the signature of a webhook request
    ///
    /// The signature is created by the Crypto Bot API using HMAC-SHA-256
    /// with the API token as the key and the request body as the message.
    ///
    /// # Arguments
    /// * `body` - The raw request body
    /// * `signature` - The signature from the 'crypto-pay-api-signature' header
    ///
    /// # Returns
    /// * `true` if the signature is valid
    /// * `false` if the signature is invalid or malformed
    ///
    /// # Example
    /// ```
    /// use crypto_pay_api::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), CryptoBotError> {
    ///     let client = CryptoBot::builder().api_token("your_api_token").build().unwrap();
    ///     let handler = client.webhook_handler().build();
    ///     let body = r#"{"update_id": 1, "update_type": "invoice_paid"}"#;
    ///     let signature = "1234567890abcdef"; // The actual signature from the request header
    ///
    ///     if handler.verify_signature(body, signature) {
    ///         println!("Signature is valid");
    ///     } else {
    ///         println!("Invalid signature");
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn verify_signature(&self, body: &str, signature: &str) -> bool {
        let secret = Sha256::digest(self.api_token.as_bytes());
        let mut mac = Hmac::<Sha256>::new_from_slice(&secret).expect("HMAC can take key of any size");

        mac.update(body.as_bytes());

        if let Ok(hex_signature) = hex::decode(signature) {
            mac.verify_slice(&hex_signature).is_ok()
        } else {
            false
        }
    }

    /// Handles a webhook update from Crypto Bot API
    ///
    /// This method:
    /// 1. Parses the webhook update from JSON
    /// 2. Validates the request date
    /// 3. Checks if the request has expired
    /// 4. Calls the registered update handler if one exists
    ///
    /// # Arguments
    /// * `body` - The raw webhook request body as JSON string
    ///
    /// # Returns
    /// * `Ok(WebhookResponse)` - If the update was handled successfully
    /// * `Err(CryptoBotError)` - If any validation fails or the handler returns an error
    ///
    /// # Errors
    /// * `WebhookErrorKind::InvalidPayload` - If the JSON is invalid or missing required fields
    /// * `WebhookErrorKind::Expired` - If the request is older than the expiration time
    pub async fn handle_update(&self, body: &str) -> Result<WebhookResponse, CryptoBotError> {
        let update: WebhookUpdate = Self::parse_update(body)?;

        if let Some(expiration_time) = self.config.expiration_time {
            let request_date =
                DateTime::parse_from_rfc3339(&update.request_date).map_err(|_| CryptoBotError::WebhookError {
                    kind: WebhookErrorKind::InvalidPayload, // TODO: test this
                    message: "Invalid request date".to_string(),
                })?;

            let age = Utc::now().signed_duration_since(request_date.with_timezone(&Utc));

            let webhook_expiration_time = expiration_time.as_secs();

            let webhook_expiration = chrono::Duration::seconds(webhook_expiration_time as i64);

            if age > webhook_expiration {
                return Err(CryptoBotError::WebhookError {
                    kind: WebhookErrorKind::Expired,
                    message: "Webhook request too old".to_string(),
                });
            }
        }

        if let Some(handler) = &self.update_handler {
            handler(update).await?;
        }

        Ok(WebhookResponse::ok())
    }

    /// Registers a handler function for webhook updates
    ///
    /// The handler function will be called for each webhook update received through
    /// `handle_update`. The function should process the update and return a Result
    /// indicating success or failure.
    ///
    /// # Arguments
    /// * `handler` - An async function that takes a `WebhookUpdate` and returns a `Result<(), CryptoBotError>`
    ///
    /// # Type Parameters
    /// * `F` - The handler function type
    /// * `Fut` - The future type returned by the handler
    ///
    /// # Requirements
    /// The handler function must:
    /// * Be `Send` + `Sync` + 'static
    /// * Return a Future that is `Send` + 'static
    /// * The Future must resolve to `Result<(), CryptoBotError>`
    ///
    /// # Example
    /// ```
    /// use crypto_pay_api::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
    ///     let mut handler = client.webhook_handler().build();
    ///
    ///     handler.on_update(|update| async move {
    ///         match (update.update_type, update.payload) {
    ///             (UpdateType::InvoicePaid, WebhookPayload::InvoicePaid(invoice)) => {
    ///                 println!("Payment received!");
    ///                 println!("Amount: {} {}", invoice.amount, invoice.asset.unwrap());
    ///                 
    ///                 // Process the payment...
    ///             }
    ///         }
    ///         Ok(())
    ///     });
    ///
    ///     // Now ready to handle webhook updates
    /// }
    /// ```
    pub fn on_update<F, Fut>(&mut self, handler: F)
    where
        F: Fn(WebhookUpdate) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), CryptoBotError>> + Send + 'static,
    {
        self.update_handler = Some(Box::new(move |update| Box::pin(handler(update))));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        models::{InvoiceStatus, UpdateType, WebhookPayload},
        webhook::WebhookHandlerConfigBuilder,
    };
    use chrono::Utc;
    use serde_json::json;

    use std::{sync::Arc, time::Duration};
    use tokio::sync::Mutex;

    #[tokio::test]
    async fn test_webhook_handler() {
        let mut handler = WebhookHandler::with_config("test_token", WebhookHandlerConfigBuilder::new().build_config());

        let received = Arc::new(Mutex::new(None));
        let received_clone = received.clone();

        handler.on_update(move |update| {
            let received = received_clone.clone();
            async move {
                let mut guard = received.lock().await;
                *guard = Some(update);
                Ok(())
            }
        });

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": Utc::now().to_rfc3339(),
            "payload": {
                "invoice_id": 528890,
                "hash": "IVDoTcNBYEfk",
                "currency_type": "crypto",
                "asset": "TON",
                "amount": "10.5",
                "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                "description": "Test invoice",
                "status": "paid",
                "created_at": "2025-02-08T12:11:01.341Z",
                "allow_comments": true,
                "allow_anonymous": true
            }
        })
        .to_string();

        let result = handler.handle_update(&json).await;
        assert!(result.is_ok());

        let update = received.lock().await.take().expect("Should have received update");
        assert_eq!(update.update_type, UpdateType::InvoicePaid);
        match update.payload {
            WebhookPayload::InvoicePaid(invoice) => {
                assert_eq!(invoice.invoice_id, 528890);
                assert_eq!(invoice.status, InvoiceStatus::Paid);
            }
        }
    }

    #[tokio::test]
    async fn test_webhook_handler_propagates_handler_error() {
        let mut handler = WebhookHandler::with_config("test_token", WebhookHandlerConfigBuilder::new().build_config());
        handler.on_update(|_| async move {
            Err(CryptoBotError::WebhookError {
                kind: WebhookErrorKind::InvalidPayload,
                message: "handler error".to_string(),
            })
        });

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": Utc::now().to_rfc3339(),
            "payload": {
                "invoice_id": 528890,
                "hash": "IVDoTcNBYEfk",
                "currency_type": "crypto",
                "asset": "TON",
                "amount": "10.5",
                "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                "description": "Test invoice",
                "status": "paid",
                "created_at": "2025-02-08T12:11:01.341Z",
                "allow_comments": true,
                "allow_anonymous": true
            }
        })
        .to_string();

        let result = handler.handle_update(&json).await;
        assert!(matches!(
            result,
            Err(CryptoBotError::WebhookError {
                kind: WebhookErrorKind::InvalidPayload,
                message
            }) if message == "handler error"
        ));
    }

    #[tokio::test]
    async fn test_webhook_handler_invalid_request_date() {
        let handler = WebhookHandler::with_config("test_token", WebhookHandlerConfigBuilder::new().build_config());

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": "invalid_date",
            "payload": {
                "invoice_id": 528890,
                "hash": "IVDoTcNBYEfk",
                "currency_type": "crypto",
                "asset": "TON",
                "amount": "10.5",
                "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                "description": "Test invoice",
                "status": "paid",
                "created_at": "2025-02-08T12:11:01.341Z",
                "allow_comments": true,
                "allow_anonymous": true
            }
        });

        let result = handler.handle_update(&json.to_string()).await;

        assert!(matches!(
            result,
            Err(CryptoBotError::WebhookError {
                kind: WebhookErrorKind::InvalidPayload,
                message,
            }) if message == "Invalid request date"
        ));
    }

    #[tokio::test]
    async fn test_webhook_handler_with_disabled_expiration() {
        let handler = WebhookHandler::with_config(
            "test_token",
            WebhookHandlerConfigBuilder::new().disable_expiration().build_config(),
        );

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": Utc::now().to_rfc3339(),
            "payload": {
                "invoice_id": 528890,
                "hash": "IVDoTcNBYEfk",
                "currency_type": "crypto",
                "asset": "TON",
                "amount": "10.5",
                "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                "description": "Test invoice",
                "status": "paid",
                "created_at": "2025-02-08T12:11:01.341Z",
                "allow_comments": true,
                "allow_anonymous": true
            }
        });

        let result = handler.handle_update(&json.to_string()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_default_webhook_expiration() {
        let handler = WebhookHandler::with_config("test_token", WebhookHandlerConfigBuilder::new().build_config());

        let date = (Utc::now() - chrono::Duration::minutes(3)).to_rfc3339();

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": date,
            "payload":  {
                    "invoice_id": 528890,
                    "hash": "IVDoTcNBYEfk",
                    "currency_type": "crypto",
                    "asset": "TON",
                    "amount": "10.5",
                    "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                    "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                    "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                    "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                    "description": "Test invoice",
                    "status": "paid",
                    "created_at": "2025-02-08T12:11:01.341Z",
                    "allow_comments": true,
                    "allow_anonymous": true
            }
        })
        .to_string();

        let result = handler.handle_update(&json).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_custom_webhook_expiration() {
        let handler = WebhookHandler::with_config(
            "test_token",
            WebhookHandlerConfigBuilder::new()
                .expiration_time(Duration::from_secs(60))
                .build_config(),
        );

        let old_date = (Utc::now() - chrono::Duration::minutes(2)).to_rfc3339();

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": old_date,
            "payload": {
                    "invoice_id": 528890,
                    "hash": "IVDoTcNBYEfk",
                    "currency_type": "crypto",
                    "asset": "TON",
                    "amount": "10.5",
                    "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                    "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                    "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                    "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                    "description": "Test invoice",
                    "status": "paid",
                    "created_at": "2025-02-08T12:11:01.341Z",
                    "allow_comments": true,
                    "allow_anonymous": true
                }
        })
        .to_string();

        let result = handler.handle_update(&json).await;
        assert!(matches!(
            result,
            Err(CryptoBotError::WebhookError {
                kind: WebhookErrorKind::Expired,
                ..
            })
        ));
    }

    #[test]
    fn test_webhook_signature_verification() {
        let handler = WebhookHandler::with_config("test_token", WebhookHandlerConfigBuilder::new().build_config());
        let body = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": "2024-01-01T12:00:00Z",
            "payload": {
                "invoice_id": 528890,
                "hash": "IVDoTcNBYEfk",
                "status": "paid",
                // ... other invoice fields ...
            }
        })
        .to_string();

        // Generate a valid signature
        let secret = Sha256::digest(b"test_token");
        let mut mac = Hmac::<Sha256>::new_from_slice(&secret).unwrap();
        mac.update(body.as_bytes());
        let signature = hex::encode(mac.finalize().into_bytes());

        assert!(handler.verify_signature(&body, &signature));
        assert!(!handler.verify_signature(&body, "invalid_signature"));
    }

    #[test]
    fn test_parse_webhook_update() {
        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": "2024-02-02T12:11:02Z",
            "payload": {
                "invoice_id": 528890,
                "hash": "IVDoTcNBYEfk",
                "currency_type": "crypto",
                "asset": "TON",
                "amount": "10.5",
                "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                "description": "Test invoice",
                "status": "paid",
                "created_at": "2025-02-08T12:11:01.341Z",
                "allow_comments": true,
                "allow_anonymous": true
            }
        });

        let result = WebhookHandler::parse_update(&json.to_string());
        assert!(result.is_ok());

        let update = result.unwrap();
        assert_eq!(update.update_id, 1);
        assert_eq!(update.update_type, UpdateType::InvoicePaid);
        assert_eq!(update.request_date, "2024-02-02T12:11:02Z");

        match update.payload {
            WebhookPayload::InvoicePaid(invoice) => {
                assert_eq!(invoice.invoice_id, 528890);
                assert_eq!(invoice.status, InvoiceStatus::Paid);
            }
        }
    }

    #[test]
    fn test_parse_invalid_webhook_update() {
        let invalid_json = r#"{"invalid": "json"}"#;

        let result = WebhookHandler::parse_update(invalid_json);
        assert!(matches!(
            result,
            Err(CryptoBotError::WebhookError {
                kind: WebhookErrorKind::InvalidPayload,
                ..
            })
        ));
    }

    #[tokio::test]
    async fn test_handle_update_with_missing_handler_ok() {
        let handler = WebhookHandler::with_config("test_token", WebhookHandlerConfig::default());

        let json = json!({
            "update_id": 1,
            "update_type": "invoice_paid",
            "request_date": Utc::now().to_rfc3339(),
            "payload": {
                "invoice_id": 1,
                "hash": "hash",
                "status": "paid",
                "currency_type": "crypto",
                "asset": "TON",
                "amount": "1",
                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=hash",
                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-hash",
                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/hash",
                "created_at": "2025-02-08T12:11:01.341Z",
                "allow_comments": true,
                "allow_anonymous": true
            }
        })
        .to_string();

        let result = handler.handle_update(&json).await;
        assert!(result.is_ok());
    }
}