WebhookHandler

Struct WebhookHandler 

Source
pub struct WebhookHandler { /* private fields */ }

Implementations§

Source§

impl WebhookHandler

Source

pub fn parse_update(json: &str) -> Result<WebhookUpdate, CryptoBotError>

Source

pub fn verify_signature(&self, body: &str, signature: &str) -> bool

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(())
}
Source

pub async fn handle_update( &self, body: &str, ) -> Result<WebhookResponse, CryptoBotError>

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
Source

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,

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
}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more