whatsapp 4.2.0
whatsapp: ^4.2.0 copied to clipboard
A pure Dart package for the WhatsApp Business Cloud API. Send messages, media, templates, interactive content, manage profiles and verify webhooks from any Dart or Flutter platform.
WhatsApp Flutter
A production-ready, pure Dart client for the WhatsApp Business Cloud API. Works in Flutter on every platform and in plain Dart servers.
Version 4.2.0 · API v27.0 · zero runtime dependencies
Documentation #
Full documentation lives at whatsapp-flutter.github.io. Use the version selector to read the docs for 4.2.0.
What's new in 4.2.0 #
- Pure Dart, zero runtime dependencies.
httpandhttp_parserwere removed. The package usesdart:ioon native platforms and the browser HTTP stack on the web. - WhatsApp Cloud API
v27.0by default, withsetVersion()still available. - Webhook support — verify
X-Hub-Signature-256, handle the GET handshake, and parse messages, statuses, media, reactions, replies, Flow responses and errors. - Media download — download media bytes by URL or media ID.
- Full template components — media headers, named body parameters, URL/quick-reply
buttons and carousels through
sendTemplateMessage. - Phone number details —
getPhoneNumber(). - Production hardening — request timeouts, typed HTTP errors,
2xxhandling, correct resumable uploads, file/bytes/XFile uploads and better validation.
See the changelog for the complete list.
Installation #
flutter pub add whatsapp
# or, in a plain Dart project:
dart pub add whatsapp
dependencies:
whatsapp: ^4.2.0
No additional runtime packages are installed. The package supports Dart 3 and Flutter 3.
Quick start #
import 'package:whatsapp/whatsapp.dart';
const accessToken = 'YOUR_ACCESS_TOKEN';
const fromNumberId = 'YOUR_PHONE_NUMBER_ID';
final whatsapp = WhatsApp(accessToken, fromNumberId);
try {
final message = await whatsapp.sendMessage(
phoneNumber: 'RECIPIENT_NUMBER',
text: 'Hello from WhatsApp Flutter 4.2.0',
previewUrl: true,
);
print('Message ID: ${message.getMessageId()}');
print('Recipient: ${message.getContactId()}');
print('Raw response: ${message.getFullResponse()}');
} on WhatsAppException catch (error) {
print('HTTP: ${error.statusCode}');
print('Code: ${error.errorCode}');
print('Message: ${error.message}');
print('Trace: ${error.fbtraceId}');
} on NetworkException catch (error) {
print('Could not reach the API: ${error.message}');
}
Keep the access token secret. Sending messages directly from a mobile or web client exposes the token. For production apps, proxy API calls through your backend. Browser builds are also subject to the Graph API's CORS policy.
Supported platforms #
| Platform | Status | HTTP implementation |
|---|---|---|
| Android | ✅ | dart:io |
| iOS | ✅ | dart:io |
| macOS | ✅ | dart:io |
| Windows | ✅ | dart:io |
| Linux | ✅ | dart:io |
| Flutter web (JavaScript) | ✅ | browser XMLHttpRequest |
| Dart server / CLI | ✅ | dart:io |
| Flutter web (WebAssembly) | Custom transport | inject an HttpTransport backed by fetch |
Uploading files #
uploadMediaFile accepts a File, an XFile, a native file path, List<int> or
Uint8List. On the web, pass bytes:
final uploaded = await whatsapp.uploadMediaFile(
file: bytes, // Uint8List or List<int>
fileType: 'image/png',
);
Common usage #
Service-specific getters #
Every API area is available as a dedicated, lazily-created service:
await whatsapp.textService.sendMessage('15551234567', 'Hello', false);
await whatsapp.mediaService.getMedia('MEDIA_ID');
await whatsapp.templateService.sendTemplate(
'15551234567',
'welcome',
'en_US',
[
{'type': 'text', 'text': 'Rohit'},
],
);
Available getters: textService, imageService, audioService, documentService,
videoService, stickerService, reactionService, locationService,
interactiveService, contactService, mediaService, accountService,
businessService, phoneService, registrationService, replyService,
templateService, customService, flowService, catalogService, statusService
and resumableService.
Templates with media headers and buttons #
await whatsapp.sendTemplateMessage(
phoneNumber: '15551234567',
template: 'order_update',
language: 'en_US',
components: [
{
'type': 'header',
'parameters': [
{
'type': 'image',
'image': {'id': 'MEDIA_ID'},
},
],
},
{
'type': 'body',
'parameters': [
{'type': 'text', 'text': 'Rohit'},
{'type': 'text', 'text': 'ORD-1042'},
],
},
{
'type': 'button',
'sub_type': 'url',
'index': 0,
'parameters': [
{'type': 'text', 'text': 'tracking-id'},
],
},
],
);
Downloading media #
Media URLs expire after five minutes. Ask for a fresh URL and download in one call:
final file = await whatsapp.downloadMediaById(mediaId: 'MEDIA_ID');
if (file.isSuccess()) {
final bytes = file.getBytes();
final mimeType = file.getMimeType();
final fileName = file.getFileName();
// Save the bytes with your storage layer.
}
Typing indicators and read receipts #
await whatsapp.markAsRead(messageId: 'wamid.FROM_WEBHOOK');
await whatsapp.sendTypingIndicator(messageId: 'wamid.FROM_WEBHOOK');
A typing indicator is dismissed when you reply or after 25 seconds.
Phone number details #
final number = await whatsapp.getPhoneNumber();
print(number.getDisplayPhoneNumber());
print(number.getQualityRating());
print(number.getVerifiedName());
Webhooks #
The package verifies Meta's X-Hub-Signature-256 signature and parses the payload
without any external crypto dependency.
import 'dart:convert';
import 'package:whatsapp/whatsapp.dart';
// In your HTTP handler (Shelf, Dart Frog, Cloud Functions, etc.):
final rawBody = request.body; // keep the exact bytes/string Meta sent
final signature = request.headers['x-hub-signature-256'] ?? '';
final valid = WhatsAppWebhook.isValidSignature(
payload: rawBody,
signature: signature,
appSecret: 'YOUR_APP_SECRET',
);
if (!valid) {
return Response(statusCode: 403);
}
final webhook = WhatsAppWebhook.fromJson(
jsonDecode(rawBody) as Map<String, dynamic>,
);
for (final message in webhook.messages) {
print('From: ${message.from}');
print('Text: ${message.text}');
print('Media ID: ${message.mediaId}');
print('Reply ID: ${message.replyId}');
}
for (final status in webhook.statuses) {
print('${status.id} -> ${status.status}');
}
The GET verification handshake is handled with:
final challenge = WhatsAppWebhook.verifyHandshake(
mode: query['hub.mode'] ?? '',
token: query['hub.verify_token'] ?? '',
challenge: query['hub.challenge'] ?? '',
verifyToken: 'YOUR_VERIFY_TOKEN',
);
If challenge is not null, respond with HTTP 200 and the challenge as plain text.
Configuration #
API version #
whatsapp.setVersion('v27.0');
Timeouts and custom transport #
final request = Request(
requestTimeout: const Duration(seconds: 30),
uploadTimeout: const Duration(minutes: 5),
// Useful for tests, proxies or logging:
// transport: MyHttpTransport(),
);
final whatsapp = WhatsApp(accessToken, fromNumberId, request);
Implement HttpTransport to integrate a proxy, retries, request logging or a platform
without a bundled transport.
Error handling #
All network and API failures are typed:
| Exception | When |
|---|---|
WhatsAppAuthenticationException |
401/403 or Graph error code 190 |
WhatsAppValidationException |
Invalid parameters (4xx) |
WhatsAppRateLimitException |
429 or known rate-limit codes |
WhatsAppServerException |
5xx from Meta |
WhatsAppException |
Other API errors; includes statusCode, errorCode, errorSubcode, fbtraceId and details |
NetworkException |
DNS, socket, TLS, timeout or browser CORS failure |
JsonFormatException |
The API returned an unexpected body |
Testing #
dart pub get
dart test # unit tests; live API tests are skipped
dart analyze
dart format --output=none --set-exit-if-changed lib test tool
Live tests are opt-in and read credentials from .env:
cp .env.example .env # add ACCESS_TOKEN, PHONE_NUMBER_ID, RECEIPT_NUMBER
RUN_INTEGRATION=true dart test test/integration
The test suite is split by feature under test/unit and test/integration.
Contributors #
Found a bug or have an idea? Open an issue or a pull request.
License #
Copyright © 2022 Rohit Chouhan. Licensed under the MIT License.
