whatsapp_handler 0.2.0

A comprehensive Rust library for WhatsApp Cloud API integration, enabling seamless processing of webhook messages and sending of diverse message types, such as documents, images, videos, interactive messages, and business templates.
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
# WhatsApp Handler


[![Crates.io](https://img.shields.io/crates/v/whatsapp_handler.svg)](https://crates.io/crates/whatsapp_handler)
[![Docs.rs](https://docs.rs/whatsapp_handler/badge.svg)](https://docs.rs/whatsapp_handler)
[![License](https://img.shields.io/crates/l/whatsapp_handler.svg)](https://github.com/bambby-plus/whatsapp_handler/blob/main/LICENSE)
[![Repository](https://img.shields.io/badge/github-bambby--plus%2Fwhatsapp__handler-blue?logo=github)](https://github.com/bambby-plus/whatsapp_handler.git)


A Rust library for handling WhatsApp Business API operations, including sending messages and processing incoming webhooks.

## Installation


Add this to your `Cargo.toml`:

```toml
[dependencies]
whatsapp_handler = "0.2.0"
tokio = { version = "1.0", features = ["full"] }
```

## Quick Start


### Basic Setup


```rust
use whatsapp_handler::config::Config;

#[tokio::main]

async fn main() {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),    // WhatsApp base URL
        "v17.0".to_string(),                         // API version
        "your_business_id".to_string(),              // WhatsApp Business ID
        "your_phone_number_id".to_string(),          // Phone Number ID
        "your_access_token".to_string(),             // System User Token
    );
}
```

## Sending Messages


### 1. Send Text Message


```rust
use whatsapp_handler::{
    config::Config,
    formatter::outgoing_type::{
        MessageType,
        text::{Content, MType, Text}
    }
};

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),
        "v17.0".to_string(),
        "your_business_id".to_string(),
        "your_phone_number_id".to_string(),
        "your_access_token".to_string(),
    );

    let message = Text {
        to: "1234567890".to_string(),
        messaging_product: "whatsapp".to_string(),
        recipient_type: "individual".to_string(),
        r#type: MType::text,
        text: Content {
            preview_url: false,
            body: "Hello! This is a message from Rust 🦀".to_string(),
        },
    };

    let response = config.outgoing(MessageType::Text(message)).await?;
    println!("Message sent: {:?}", response);
    
    Ok(())
}
```

### 2. Send Interactive List Message


```rust
use whatsapp_handler::{
    config::Config,
    formatter::outgoing_type::{
        MessageType,
        interactive_list::{
            Action, Body, Footer, Header, InteractiveList, List, MType, Row, Section,
        }
    }
};

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),
        "v17.0".to_string(),
        "your_business_id".to_string(),
        "your_phone_number_id".to_string(),
        "your_access_token".to_string(),
    );

    let message = InteractiveList {
        to: "1234567890".to_string(),
        messaging_product: "whatsapp".to_string(),
        recipient_type: "individual".to_string(),
        r#type: MType::interactive,
        interactive: List {
            r#type: "list".to_string(),
            header: Header {
                r#type: "text".to_string(),
                text: "Choose a Service".to_string(),
            },
            body: Body {
                text: "Please select one of the following options:".to_string(),
            },
            footer: Footer {
                text: "Powered by Rust".to_string(),
            },
            action: Action {
                button: "View Options".to_string(),
                sections: vec![
                    Section {
                        title: "Services".to_string(),
                        rows: vec![
                            Row {
                                id: "support".to_string(),
                                title: "Customer Support".to_string(),
                                description: "Get help with your account".to_string(),
                            },
                            Row {
                                id: "billing".to_string(),
                                title: "Billing".to_string(),
                                description: "View your billing information".to_string(),
                            },
                        ],
                    },
                    Section {
                        title: "Information".to_string(),
                        rows: vec![
                            Row {
                                id: "about".to_string(),
                                title: "About Us".to_string(),
                                description: "Learn more about our company".to_string(),
                            }
                        ],
                    },
                ],
            },
        },
    };

    let response = config.outgoing(MessageType::InteractiveList(message)).await?;
    println!("Interactive list sent: {:?}", response);
    
    Ok(())
}
```

### 3. Send Template Message (OTP Verification)


```rust
use whatsapp_handler::{
    config::Config,
    formatter::outgoing_type::{
        MessageType,
        template::{
            Component, Language, MType, Parameter, Template, TemplateContent, TextParameter,
        }
    }
};

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),
        "v22.0".to_string(),
        "your_business_id".to_string(),
        "your_phone_number_id".to_string(),
        "your_access_token".to_string(),
    );

    let message = Template {
        messaging_product: "whatsapp".to_string(),
        recipient_type: "individual".to_string(),
        to: "1234567890".to_string(),
        r#type: MType::template,
        template: TemplateContent {
            name: "otp_verification".to_string(),
            language: Language {
                code: "en".to_string(),
            },
            components: vec![
                // Body component with text parameter
                Component {
                    r#type: "body".to_string(),
                    parameters: Some(vec![Parameter::Text(TextParameter {
                        r#type: "text".to_string(),
                        text: "123456".to_string(),
                    })]),
                    sub_type: None,
                    index: None,
                },
                // Button component with URL type
                Component {
                    r#type: "button".to_string(),
                    parameters: Some(vec![Parameter::Text(TextParameter {
                        r#type: "text".to_string(),
                        text: "123456".to_string(),
                    })]),
                    sub_type: Some("url".to_string()),
                    index: Some("0".to_string()),
                },
            ],
        },
    };

    let response = config.outgoing(MessageType::Template(message)).await?;
    println!("Template message sent: {:?}", response);
    
    Ok(())
}
```

## Processing Incoming Messages


### Handle Incoming Text Messages


```rust
use whatsapp_handler::config::Config;

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),
        "v17.0".to_string(),
        "your_business_id".to_string(),
        "your_phone_number_id".to_string(),
        "your_access_token".to_string(),
    );

    // Example webhook payload from WhatsApp
    let webhook_payload = r#"
    {
        "object": "whatsapp_business_account",
        "entry": [
            {
                "id": "your_business_id",
                "changes": [
                    {
                        "value": {
                            "messaging_product": "whatsapp",
                            "metadata": {
                                "display_phone_number": "1234567890",
                                "phone_number_id": "your_phone_number_id"
                            },
                            "contacts": [
                                {
                                    "profile": {
                                        "name": "John Doe"
                                    },
                                    "wa_id": "1234567890"
                                }
                            ],
                            "messages": [
                                {
                                    "from": "1234567890",
                                    "id": "wamid.unique_id",
                                    "timestamp": "1234567890",
                                    "text": {
                                        "body": "Hello there!"
                                    },
                                    "type": "text"
                                }
                            ]
                        },
                        "field": "messages"
                    }
                ]
            }
        ]
    }
    "#;

    let messages = config.incoming_message(webhook_payload);
    println!("Received messages: {:?}", messages);
    
    Ok(())
}
```

### Handle Message Status Updates


```rust
use whatsapp_handler::config::Config;

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),
        "v17.0".to_string(),
        "your_business_id".to_string(),
        "your_phone_number_id".to_string(),
        "your_access_token".to_string(),
    );

    // Example status webhook payload
    let status_payload = r#"
    {
        "object": "whatsapp_business_account",
        "entry": [
            {
                "id": "your_business_id",
                "changes": [
                    {
                        "value": {
                            "messaging_product": "whatsapp",
                            "metadata": {
                                "display_phone_number": "1234567890",
                                "phone_number_id": "your_phone_number_id"
                            },
                            "statuses": [
                                {
                                    "id": "wamid.unique_id",
                                    "status": "delivered",
                                    "timestamp": "1234567890",
                                    "recipient_id": "1234567890"
                                }
                            ]
                        },
                        "field": "messages"
                    }
                ]
            }
        ]
    }
    "#;

    let statuses = config.incoming_statuses(status_payload);
    println!("Message statuses: {:?}", statuses);
    
    Ok(())
}
```

## Complete Example: Echo Bot


```rust
use whatsapp_handler::{
    config::Config,
    formatter::outgoing_type::{
        MessageType,
        text::{Content, MType, Text}
    }
};

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::from(
        "https://graph.facebook.com".to_string(),
        "v17.0".to_string(),
        std::env::var("WHATSAPP_BUSINESS_ID")?,
        std::env::var("WHATSAPP_PHONE_NUMBER_ID")?,
        std::env::var("WHATSAPP_ACCESS_TOKEN")?,
    );

    // Simulate receiving a message
    let webhook_payload = r#"..."#; // Your webhook payload here
    
    let messages = config.incoming_message(webhook_payload);
    
    // Echo back received messages
    if let Ok(parsed_messages) = messages {
        for message in parsed_messages {
            let echo_message = Text {
                to: message.from, // Send back to sender
                messaging_product: "whatsapp".to_string(),
                recipient_type: "individual".to_string(),
                r#type: MType::text,
                text: Content {
                    preview_url: false,
                    body: format!("Echo: {}", message.text.body),
                },
            };

            let response = config.outgoing(MessageType::Text(echo_message)).await?;
            println!("Echo sent: {:?}", response);
        }
    }
    
    Ok(())
}
```

## Environment Variables


For production usage, store your credentials as environment variables:

```bash
export WHATSAPP_BUSINESS_ID="your_business_id"
export WHATSAPP_PHONE_NUMBER_ID="your_phone_number_id"
export WHATSAPP_ACCESS_TOKEN="your_access_token"
```

## Features


- ✅ Send text messages
- ✅ Send interactive list messages
- ✅ Send template messages (OTP, notifications)
- ✅ Process incoming messages
- ✅ Handle message status updates
- ✅ Async/await support
- ✅ Type-safe message handling

## License


This project is licensed under the MIT License.

## Contributing


Contributions are welcome! Please feel free to submit a Pull Request.