wuapi 0.6.0

Rust SDK for wuapi, a WhatsApp API for developers. Link numbers by QR or pairing code, send and receive messages, manage chats, contacts, groups and channels, split them into projects and verify webhooks.
Documentation
// Generated by wuapi-codegen from the OpenAPI spec. Do not edit: run `bun run codegen`.

use crate::http::{HttpClient, Method, Request, RequestParts, encode_path};
use crate::pagination::Paginator;
use crate::types;

/// wuapi sends events to your webhook endpoints as `POST` requests with a JSON body (schema `Event`):
///
/// `{id, object: "event", type, createdAt, organizationId, projectId, data: {object, previousAttributes?}}`
///
/// `data.object` is the full resource in the same shape the REST API returns, or the event object named below. `data.previousAttributes` is set on `message.edited` (`{text}`) and `invitation.status_changed` (`{status}`).
///
/// **Events** (`WebhookEventType`):
///
/// | Events | When | `data.object` |
/// |---|---|---|
/// | `account.qr_code_issued`, `account.pairing_code_issued`, `account.connected`, `account.disconnected`, `account.failed` | Fired on real transitions: `account.qr_code_issued` when the account enters `qr_ready` (not on each QR rotation; poll the account for the current `qrCodeUrl`), `account.pairing_code_issued` when a new pairing code is issued, `account.disconnected` when the account loses its connection: at once when it does not recover on its own (`disconnectReason` `logged_out`, for example), or, for a drop the session reconnects from by itself, only if it is not `ready` again within a short reconnect grace (currently 20 seconds; `status` may then read `initializing` or `authenticating` while it keeps retrying), so a quick reconnect fires neither this nor `account.connected`; `account.connected` on `ready` (the first link, or back after `account.disconnected`), `account.failed` on `failed`. Deleting an account fires nothing. | `account` |
/// | `message.received`, `message.sent`, `message.delivered`, `message.read`, `message.failed`, `message.deleted` | `message.sent` also fires for messages sent from the phone (`source: phone`) and for stories and channel posts. `message.deleted` carries the row with `deletedAt` set and the content cleared. | `message` |
/// | `message.edited` | A message was edited. `previousAttributes.text` is the text before. | `message` |
/// | `poll.voted` | Someone voted in a poll. | `poll_vote` |
/// | `group.joined` | The account joined or created a group. | `group` |
/// | `group.updated` | A group changed. | `group_change` |
/// | `group.join_requested`, `group.join_request_revoked` | Someone asked to join a group that needs approval, or withdrew the request. | `group_join_request` |
/// | `chat.updated` | A chat was archived, pinned, muted, marked read, deleted, cleared or a message starred, on the phone or another device. Live changes only; the initial full sync is not replayed. | `chat_change` |
/// | `chat.presence_updated` | A contact is typing or recording in a chat. | `chat_presence` |
/// | `contact.presence_updated` | A subscribed contact came online or went offline. Subscribe with `POST .../contacts/{contactId}/subscribe-presence`. | `contact_presence` |
/// | `contact.picture_updated` | A contact or group picture changed or was removed. | `picture_change` |
/// | `contact.updated` | A contact changed their About text. Fields WhatsApp did not send are `null`. | `contact` |
/// | `blocklist.updated` | The blocklist changed. | `blocklist_change` |
/// | `label.updated` | A label was edited or (un)assigned to a chat or message. The full sync replays labels this way, which is how the label list arrives. | `label_change` |
/// | `call.received`, `call.ended` | `call.received` on an incoming call (reject it with `POST .../calls/{callId}/reject`), `call.ended` when it ends or is rejected. | `call` |
/// | `channel.message_received`, `channel.message_updated` | A new message in a followed channel, or new views and reactions on one. Not stored. | `channel_message` |
/// | `channel.updated` | The account followed, unfollowed, muted or unmuted a channel. | `channel_change` |
/// | `history.synced` | A part of the history the phone sent after linking was stored. Only for accounts with `historySync: recent`: history import is off by default. | `history_sync` |
/// | `project.created`, `project.updated`, `project.deleted` | `project.deleted` fires when the background purge finishes. | `project` |
/// | `invitation.status_changed` | An invitation changed status (started, completed, failed, cancelled, resent). `url` is `null`. `expired` has no event. `previousAttributes.status` is the status before. | `invitation` |
///
/// Everything beyond account, message and group joined/updated events needs the engine's extended events, which the hosted service turns on.
///
/// **Projects.** Every event carries `projectId` (`null` when unassigned). An organization endpoint receives every project's events; a project endpoint receives only its project's.
///
/// **Signature.** Every request carries `Wuapi-Signature: t=<unix seconds>,v1=<hex>`, where `v1` is the HMAC-SHA256 of `"<t>.<rawBody>"` keyed with the endpoint's `secret` (`whsec_...`). Recompute it over the raw body, compare in constant time, and reject timestamps more than 5 minutes from your clock. The TypeScript SDK exports `verifyWebhook(rawBody, header, secret)`. Requests also carry `Wuapi-Event-Id` and `Wuapi-Event-Type`.
///
/// **Delivery.** A 2xx within 10 seconds counts as delivered; redirects are not followed. Anything else is retried after 30s, 2m, 10m, 1h and 6h (6 attempts), then dropped. Events can arrive more than once and out of order: deduplicate on `id`.
#[derive(Clone, Debug)]
pub struct WebhookEndpointsResource {
    http: HttpClient,
}

impl WebhookEndpointsResource {
    pub(crate) fn new(http: HttpClient) -> Self {
        Self { http }
    }

    /// List webhook endpoints
    ///
    /// Endpoints in scope. Secrets are never included.
    ///
    /// `GET /v1/webhook-endpoints`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn list(
        &self,
        params: types::WebhookEndpointsListParams,
    ) -> Paginator<types::WebhookEndpointList> {
        let parts = RequestParts::new(Method::Get, "/v1/webhook-endpoints")
            .query_opt("limit", params.limit.as_ref())
            .query_opt("projectId", params.project_id.as_ref())
            .retryable();
        Paginator::new(self.http.clone(), parts, "cursor", params.cursor)
    }

    /// Create a webhook endpoint
    ///
    /// At most 5 organization endpoints and 5 per project; one more answers `400 invalid_request`. The `secret` is returned only here and by rotate-secret.
    ///
    /// `POST /v1/webhook-endpoints`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn create(
        &self,
        params: types::WebhookEndpointsCreateParams,
    ) -> Request<types::WebhookEndpoint> {
        let parts = RequestParts::new(Method::Post, "/v1/webhook-endpoints").body(&params).keyed();
        self.http.request(parts)
    }

    /// Get a webhook endpoint
    ///
    /// The endpoint, without its secret.
    ///
    /// `GET /v1/webhook-endpoints/{webhookEndpointId}`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn get(&self, webhook_endpoint_id: &str) -> Request<types::WebhookEndpoint> {
        let parts = RequestParts::new(Method::Get, format!("/v1/webhook-endpoints/{}", encode_path(webhook_endpoint_id)))
            .retryable();
        self.http.request(parts)
    }

    /// Update a webhook endpoint
    ///
    /// Change the URL, the events, or pause it with `active: false`.
    ///
    /// `PATCH /v1/webhook-endpoints/{webhookEndpointId}`
    ///
    /// Not idempotent: retried only when the request never reached the API or was refused with `429`.
    pub fn update(
        &self,
        webhook_endpoint_id: &str,
        params: types::WebhookEndpointsUpdateParams,
    ) -> Request<types::WebhookEndpoint> {
        let parts = RequestParts::new(Method::Patch, format!("/v1/webhook-endpoints/{}", encode_path(webhook_endpoint_id)))
            .body(&params);
        self.http.request(parts)
    }

    /// Delete a webhook endpoint
    ///
    /// Stop delivering to it.
    ///
    /// `DELETE /v1/webhook-endpoints/{webhookEndpointId}`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn delete(&self, webhook_endpoint_id: &str) -> Request<()> {
        let parts = RequestParts::new(Method::Delete, format!("/v1/webhook-endpoints/{}", encode_path(webhook_endpoint_id)))
            .retryable()
            .no_content();
        self.http.request(parts)
    }

    /// Rotate the signing secret
    ///
    /// A new `secret` replaces the old one, which stops working at once.
    ///
    /// `POST /v1/webhook-endpoints/{webhookEndpointId}/rotate-secret`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn rotate_secret(&self, webhook_endpoint_id: &str) -> Request<types::WebhookEndpoint> {
        let parts = RequestParts::new(Method::Post, format!("/v1/webhook-endpoints/{}/rotate-secret", encode_path(webhook_endpoint_id)))
            .keyed();
        self.http.request(parts)
    }
}