Skip to main content

Crate whatsapp_business_rs

Crate whatsapp_business_rs 

Source
Expand description

§whatsapp_business_rs

A comprehensive Rust SDK for interacting with the Meta WhatsApp Business Platform. This crate provides robust and type-safe abstractions for sending and receiving WhatsApp messages, managing WhatsApp Business Accounts (WABAs), configuring webhooks, and handling product catalogs.

§✨ Features

  • Message Management: Construct, send, and receive various message types, including text, media, interactive messages (buttons, lists), and reactions.
  • Client API: A fluent builder for authenticating and managing interactions with the WhatsApp Business API.
  • Webhook Server: Easily set up a webhook server to receive and process incoming messages and message status updates with signature validation.
  • App Management: Configure webhook subscriptions and manage onboarding flows for connecting businesses to your app.
  • WABA Management: Administer your WhatsApp Business Account, including listing catalogs, managing phone numbers, and running guided phone number registration flows.
  • Catalog Management: Programmatically manage your product catalogs, allowing you to list, create, and update products.

§🚀 Examples

Here are some quick examples to get you started:


§Create a Client

use std::time::Duration;
use whatsapp_business_rs::client::Client;

let client = Client::builder()
    .timeout(Duration::from_secs(15))
    .api_version("v19.0")
    .connect("YOUR_ACCESS_TOKEN")
    .await?;

§Send a Simple Text Message

use whatsapp_business_rs::{Client, Draft};

// Initialize your client with your access token
let client = Client::new("YOUR_ACCESS_TOKEN").await?;

// Replace with your WhatsApp Phone Number ID and recipient's phone number
let sender_phone_id = "YOUR_BUSINESS_PHONE_NUMBER_ID";
let recipient_phone_number = "+16012345678";

// Send a text message
client
    .message(sender_phone_id)
    .send(recipient_phone_number, Draft::text("Hello from Rust! How can I help you today?"))
    .await?;

println!("Text message sent!");

§Send Bulk Messages with Batch 🚀

use whatsapp_business_rs::Client;

let client = Client::new("YOUR_ACCESS_TOKEN").await?;

let sender = client.message("business_phone_id");
let batch = client
    .batch()
        .include(sender.send("+1234567890", "Hi A!"))
        .include(sender.send("+1234667809", "Hi B!"))
        .include(sender.send("+1224537891", "Hi C!"));

batch.execute().await?;

§Send a Media Message (e.g., Video)

use whatsapp_business_rs::{Client, message::Media};

let client = Client::new("YOUR_ACCESS_TOKEN").await?;

let sender_phone_id = "YOUR_BUSINESS_PHONE_NUMBER_ID";
let recipient_phone_number = "+16012345678";

// Example: Send a video from a file path
// Make sure to replace "path/to/your/video.mp4" with an actual path
let video = Media::from_path("path/to/your/video.mp4")
    .await?
    .caption("Check out this cool video!");

client.message(sender_phone_id).send(recipient_phone_number, video).await?;
println!("Video message sent!");

§Send a Location Message

use whatsapp_business_rs::{Client, message::Location};

let client = Client::new("YOUR_ACCESS_TOKEN").await?;

let sender_phone_id = "YOUR_BUSINESS_PHONE_NUMBER_ID";
let recipient_phone_number = "+16012345678";

// Send a location message with name and address
let location = Location::new(37.44216251868683, -122.16153582049394)
    .name("Philz Coffee")
    .address("101 Forest Ave, Palo Alto, CA 94301");

client.message(sender_phone_id).send(recipient_phone_number, location).await?;
println!("Location message sent!");

§Send an Interactive Message (Call-to-Action Button)

use whatsapp_business_rs::message::{InteractiveMessage, UrlButton};
use whatsapp_business_rs::Client;

let client = Client::new("YOUR_ACCESS_TOKEN").await?;

let sender_phone_id = "YOUR_BUSINESS_PHONE_NUMBER_ID";
let recipient_phone_number = "+16012345678";

// Create a URL button
let button = UrlButton::new("https://example.com/purchase", "2 for price of 1");

// Create an interactive message with the button and a body text
let interactive_message = InteractiveMessage::new(
    button,
    "One-time offer for this shiny product. Hurry-up!"
);

client.message(sender_phone_id).send(recipient_phone_number, interactive_message).await?;
println!("Call-to-Action message sent!");

§Send an Interactive Message (List of Options)

use whatsapp_business_rs::message::{InteractiveMessage, OptionList, OptionButton, Section};
use whatsapp_business_rs::Client;

let client = Client::new("YOUR_ACCESS_TOKEN").await?;

let sender_phone_id = "YOUR_BUSINESS_PHONE_NUMBER_ID";
let recipient_phone_number = "+16012345678";

// Create sections with options
let section = Section::new(
    "Choose an option regarding your last order",
    [
        OptionButton::new("Cancels deliver", "Cancel", "cancel-delivery"),
        OptionButton::new("Proceed with order", "Order", "proceed-with-order"),
    ],
);

// Create an option list with the section and a global label
let options = OptionList::new_section(section, "Delivery Options");

// Create an interactive message with the option list, body, and footer
let interactive_message = InteractiveMessage::new(
    options,
    "Sorry your delivery is delayed... would you like to cancel the order?",
).footer("Only 70% in refund");

client.message(sender_phone_id).send(recipient_phone_number, interactive_message).await?;
println!("Option list message sent!");

§Configure a Webhook

use whatsapp_business_rs::{
    app::SubscriptionField,
    client::Client,
    App,
};

let app = App::new("YOUR_APP_ID");

let client = Client::new("YOUR_ACCESS_TOKEN").await?;
client
    .app(app)
    .configure_webhook(("https://example.com/webhook", "very_secret"))
    .events(
        [
            SubscriptionField::Messages,
            SubscriptionField::MessageTemplateStatusUpdate,
        ]
    .into(),
    )
    .await?;

§Start a Webhook Server and Echo Messages

use whatsapp_business_rs::{
    client::Client,
    server::{Server, Handler, EventContext, IncomingMessage},
    app::SubscriptionField,
    Auth,
};
use std::error::Error;

// Define a handler struct for incoming webhook events
#[derive(Debug)]
struct EchoServerHandler {
    client: Client, // Store a client to send replies
}

impl EchoServerHandler {
    fn new(client: Client) -> Self {
        Self { client }
    }
}

impl Handler for EchoServerHandler {
    // This method handles incoming messages
    async fn handle_message(
        &self,
        _ctx: EventContext,
        message: IncomingMessage,
    ) {
        println!("Received message: {:#?}", message);
        let message = message.into_inner();
        // Echo the received message content back to the sender
        if let Err(e) = self.client
            .message(message.recipient) // The recipient for the echo is the original sender's ID
            .send(message.sender, message.content) // Send the same content back
            .await
        {
            eprintln!("Failed to send echo message: {}", e);
        }
    }
}

// Initialize a client with your app token (or system user token)
// For app actions, it's recommended to use `Auth::secret`
let client = Client::new(Auth::secret(("YOUR_APP_ID", "YOUR_APP_SECRET"))).await?;

// Your public webhook URL (e.g., from ngrok) and verify token
let webhook_url = "https://your-ngrok-url.ngrok-free.app/webhook"; // Replace with your actual URL
let verify_token = "my_super_secret_verify_token";

// Configure the webhook subscription with Meta
let pending_configure = client
    .app("YOUR_APP_ID") // Replace with your app ID
    .configure_webhook((webhook_url, verify_token))
    .events([SubscriptionField::Messages].into()); // Subscribe to message events

// Create an instance of your webhook handler
let handler = EchoServerHandler::new(client);

// Build and start the webhook server
Server::builder()
    .endpoint("127.0.0.1:8080".parse().unwrap()) // The local address where your server will listen
    .verify_payload("YOUR_APP_SECRET") // Use your app secret for payload verification
    .build()
    .serve(handler)
    .configure_webhook(verify_token, pending_configure) // Register webhook with Meta through the server
    .await?;

println!("Webhook server started and configured!");

§Listing Catalogs

use whatsapp_business_rs::{client::Client, Waba, waba::CatalogMetadataField};
use futures::TryStreamExt as _;

let business = Waba::new("YOUR_WABA_ID");
let client = Client::new("YOUR_ACCESS_TOKEN").await?;

let mut catalogs = client
    .waba(business)
    .list_catalogs()
    .metadata([CatalogMetadataField::Name, CatalogMetadataField::Vertical].into())
    .into_stream();

while let Some(catalog) = catalogs.try_next().await? {
    println!("{:?}", catalog);
}

§Creating a Product

use whatsapp_business_rs::catalog::{ProductData, Price};
use whatsapp_business_rs::Client;

let client = Client::new("YOUR_ACCESS_TOKEN").await?;
let catalog_manager = client.catalog("YOUR_CATALOG_ID");

let product = ProductData::default()
    .name("Rust Programming Book")
    .description("Learn Rust with this comprehensive guide")
    .price(Price(39.99, "USD".into()))
    .currency("USD")
    .image_url("https://example.com/book.jpg")
    .build("rust-book-001");

let created = catalog_manager.create_product(product).await.unwrap();
println!("Created product ID: {}", created.product.product_id());

Re-exports§

pub use client::Auth;
pub use client::Client;
pub use error::Error;
pub use message::Draft;
pub use message::Message;
pub use server::Handler as WebhookHandler;
pub use server::Server;

Modules§

app
WhatsApp App Management
batch
A type-safe, fluent API for creating and executing batch API requests.
catalog
WhatsApp Business Catalog Management
client
WhatsApp Business API client implementation
error
Error Handling
message
WhatsApp Message Types and Builders
server
WhatsApp webhook server implementation
waba
WhatsApp Business Account (WABA) Management
webhook_service
For “Bring Your Own Server” (BYOS) integrations.

Structs§

App
Represents a Meta App
Business
Represents a specific WhatsApp Business profile, associating a WABA with a particular phone number’s identity.
CatalogRef
A reference to a catalog
Fields
A fluent interface for selecting fields for Meta’s Graph API.
FlowStepSkipped
A type indicating that an optional flow’s step had been skipped.
Identity
Represents a full WhatsApp identity with additional metadata.
IdentityMetadata
Additional information associated with a WhatsApp Identity.
IdentityRef
A reference to a WhatsApp identity, used for addressing messages.
MetaError
Represents an error object returned directly by Meta’s Graph API in its responses or webhook payload.
MetaErrorMetadata
Timestamp
Represents a timestamp returned by the WhatsApp Business API.
Update
A composable update request builder for Graph-style resources.
UpdateResponseReference
Waba
A Whatsapp Business Account (WABA).

Enums§

IdentityMetadataField
IdentityType
Defines the type of participant in a WhatsApp conversation.