Plugin Flutter para o Zendesk Messaging SDK. Oferece suporte ao cliente dentro do aplicativo com suporte a múltiplas conversas, eventos em tempo real e autenticação JWT.
Orientação gerada a partir de informações públicas. Apenas para referência.
Um plugin Flutter que integra o SDK de Mensagens do Zendesk, permitindo suporte ao cliente dentro do aplicativo com gerenciamento de múltiplas conversas, atualizações em tempo real e autenticação segura com JWT. Projetado para comunicação fluida em aplicativos Flutter no Android e iOS, permite que os usuários participem de conversas ao vivo com agentes de suporte diretamente na interface do aplicativo. O plugin simplifica a implementação de recursos robustos de mensagens, mantendo desempenho e compatibilidade específicos da plataforma.
Casos de uso
Suporte ao cliente no aplicativo
Mensagens de múltiplas conversas
Interações em tempo real com agentes
integração de atendimento ao cliente
Canais de suporte do aplicativo móvel
mensagens protegidas por JWT
Principais recursos
Suporte a múltiplas conversas
Tratamento de eventos em tempo real
Autenticação JWT
Compatibilidade com Android e iOS
Integração nativa do Flutter
Mensagens seguras
Indicado para
aplicativos de suporte ao cliente
Aplicativos móveis que precisam de bate-papo ao vivo
Ferramentas de comunicação empresarial
Aplicativos com mensagens de agente do usuário
Desenvolvedores usando o backend do Zendesk
Plataformas de engajamento de clientes baseadas em Flutter
Considerações
Requer configuração da conta do Zendesk
Necessita gerenciamento de token JWT
Limitado ao backend do Zendesk
dependências de SDK específicas da plataforma
Configuração de autenticação necessária
Dependente da infraestrutura externa de mensagens
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
A Flutter plugin for integrating Zendesk Messaging SDK into your mobile applications. Provides in-app customer support messaging with multi-conversation support, real-time events, and JWT authentication.
Features
Initialize and display the Zendesk Messaging UI
JWT user authentication
Multi-conversation navigation
Real-time event streaming (24 event types)
Unread message count tracking
Conversation tags and custom fields
Connection status monitoring
Runtime locale override for messaging UI
Push notifications support (FCM/APNs)
Requirements
Platform
Minimum Version
iOS
14.0
Android
API 21 (minSdk)
Dart
3.6.0
Flutter
3.27.0
Installation
Add zendesk_messaging to your pubspec.yaml:
dependencies:zendesk_messaging:<latest_version>
Android Setup
Add the Zendesk Maven repository to your project-level android/build.gradle:
This plugin also supports Swift Package Manager. If your app has migrated to SPM, no extra setup is required — just make sure your app's iOS deployment target is at least 14.0. CocoaPods remains fully supported, so existing apps need no changes.
Quick Start
Getting Channel Keys
Before initializing the SDK, you need to obtain your Android and iOS channel keys from the Zendesk Admin Center:
Go to Admin Center > Channels > Messaging and social > Messaging
Hover over the brand you want to configure and click the options icon
Click Edit and navigate to the Installation section
Under Channel ID, click Copy to copy the key to your clipboard
Use this key for both Android and iOS initialization
Note: The same Channel ID is used for both platforms. You can create separate channels for Android and iOS if needed.
Initialize
import'package:zendesk_messaging/zendesk_messaging.dart';
// Initialize the SDK (call once at app startup)awaitZendeskMessaging.initialize(
androidChannelKey: '<YOUR_ANDROID_CHANNEL_KEY>',
iosChannelKey: '<YOUR_IOS_CHANNEL_KEY>',
);
Show Messaging UI
// Show the default messaging interfaceawaitZendeskMessaging.show();
// Show a specific conversation (requires multi-conversation enabled)awaitZendeskMessaging.showConversation('conversation_id');
// Show the conversation listawaitZendeskMessaging.showConversationList();
// Start a new conversationawaitZendeskMessaging.startNewConversation();
User Authentication
// Login with JWTtry {
final response = awaitZendeskMessaging.loginUser(jwt: '<YOUR_JWT_TOKEN>');
print('Logged in: ${response.id}');
} catch (e) {
print('Login failed: $e');
}
// Check login statusfinal isLoggedIn = awaitZendeskMessaging.isLoggedIn();
// Get current userfinal user = awaitZendeskMessaging.getCurrentUser();
if (user != null) {
print('User ID: ${user.id}');
print('External ID: ${user.externalId}');
print('Auth type: ${user.authenticationType.name}');
}
// LogoutawaitZendeskMessaging.logoutUser();
Event Handling
The SDK provides a unified event stream for all Zendesk events. Use Dart 3 pattern matching to handle specific event types:
// Get current countfinal count = awaitZendeskMessaging.getUnreadMessageCount();
// Get count for specific conversationfinal convCount = awaitZendeskMessaging.getUnreadMessageCountForConversation('conv_id');
// Listen to count changes (legacy API)ZendeskMessaging.unreadMessagesCountStream.listen((count) {
print('Unread: $count');
});
Conversation Tags & Fields
// Set tags (applied when user sends a message)awaitZendeskMessaging.setConversationTags(['vip', 'mobile', 'flutter']);
// Clear tagsawaitZendeskMessaging.clearConversationTags();
// Set custom fieldsawaitZendeskMessaging.setConversationFields({
'app_version': '3.0.0',
'platform': 'flutter',
'user_tier': 'premium',
});
// Clear fieldsawaitZendeskMessaging.clearConversationFields();
Connection Status
final status = awaitZendeskMessaging.getConnectionStatus();
// Handle different connection statesfinal color = switch (status) {
ZendeskConnectionStatus.connected ||
ZendeskConnectionStatus.connectedRealtime => Colors.green,
ZendeskConnectionStatus.connectingRealtime => Colors.orange,
ZendeskConnectionStatus.disconnected => Colors.red,
ZendeskConnectionStatus.unknown => Colors.grey,
};
Locale
Override the device's system locale so the Zendesk messaging UI matches your app's language. The Zendesk SDK ships with 33 languages.
// Best: set locale before initializationawaitZendeskMessaging.setLocale('es');
awaitZendeskMessaging.initialize(
androidChannelKey: '<YOUR_ANDROID_CHANNEL_KEY>',
iosChannelKey: '<YOUR_IOS_CHANNEL_KEY>',
);
// Android: can also switch at runtime before show()awaitZendeskMessaging.setLocale('ja');
awaitZendeskMessaging.show();
// iOS runtime switch: requires re-initializationawaitZendeskMessaging.setLocale('fr');
awaitZendeskMessaging.invalidate();
awaitZendeskMessaging.initialize(
androidChannelKey: '<YOUR_ANDROID_CHANNEL_KEY>',
iosChannelKey: '<YOUR_IOS_CHANNEL_KEY>',
);
Platform details:
Android: Sets Locale.setDefault() and updates application/activity resource configuration. The SDK resolves UI strings from Android's resource system, so this takes effect when the SDK launches its messaging Activity. Can switch at runtime.
iOS: Sets the AppleLanguages user default, which controls which localization bundle the SDK loads. Must be set beforeinitialize(). To change after initialization, call invalidate() then initialize() again.
Push Notifications
Enable push notifications to notify users of new messages when the app is in the background or closed.
Upload the key to Zendesk Admin Center > Channels > Messaging > Android > Notifications
iOS
Create an APNs certificate in Apple Developer Portal
Export as .p12 file from Keychain Access
Upload to Zendesk Admin Center > Channels > Messaging > iOS > Notifications
Add Push Notifications capability in Xcode
Usage
import'dart:io'showPlatform;
import'package:firebase_messaging/firebase_messaging.dart';
import'package:zendesk_messaging/zendesk_messaging.dart';
Future<void> setupPushNotifications() async {
final messaging = FirebaseMessaging.instance;
// Request permissionawait messaging.requestPermission();
// Get and register the correct token per platform// - Android: FCM token via getToken()// - iOS: APNs device token via getAPNSToken()// (Zendesk iOS SDK requires APNs token, NOT the FCM token)await_registerPushToken(messaging);
// Listen for token refresh// - Android: onTokenRefresh returns new FCM tokens// - iOS: APNs tokens rarely change (device restore, OS update);// re-fetch via getAPNSToken() on each app launch (done above).// onTokenRefresh returns FCM tokens which are NOT usable here.if (Platform.isAndroid) {
messaging.onTokenRefresh.listen((token) {
ZendeskMessaging.updatePushNotificationToken(token);
});
}
// Handle foreground notificationsFirebaseMessaging.onMessage.listen((message) async {
final responsibility = awaitZendeskMessaging.shouldBeDisplayed(message.data);
switch (responsibility) {
caseZendeskPushResponsibility.messagingShouldDisplay:
awaitZendeskMessaging.handleNotification(message.data);
caseZendeskPushResponsibility.notFromMessaging:
// Handle your own notificationbreak;
default:
break;
}
});
// Handle notification tap (app in background)FirebaseMessaging.onMessageOpenedApp.listen((message) async {
awaitZendeskMessaging.handleNotificationTap(message.data);
});
}
Future<void> _registerPushToken(FirebaseMessaging messaging) async {
String? token;
if (Platform.isAndroid) {
token = await messaging.getToken();
} elseif (Platform.isIOS) {
token = await messaging.getAPNSToken();
}
if (token != null) {
awaitZendeskMessaging.updatePushNotificationToken(token);
}
}
Important (iOS): The Zendesk iOS SDK uses APNs directly for push notifications, not FCM. You must pass the APNs device token via getAPNSToken(), not the FCM registration token from getToken(). Using the wrong token type will silently fail to deliver notifications. APNs tokens rarely change, but calling getAPNSToken() on each app launch ensures the token stays current.
Push Notification API
Method
Returns
Description
updatePushNotificationToken(token)
Future<void>
Register FCM/APNs token with Zendesk
shouldBeDisplayed(data)
Future<ZendeskPushResponsibility>
Check if notification is from Zendesk
handleNotification(data)
Future<bool>
Display the notification
handleNotificationTap(data)
Future<void>
Handle notification tap
ZendeskPushResponsibility
Value
Description
messagingShouldDisplay
Zendesk notification, SDK can display it
messagingShouldNotDisplay
Zendesk notification, but should not display (e.g., user is viewing the conversation)
notFromMessaging
Not a Zendesk notification, handle it yourself
unknown
Unable to determine
SDK Lifecycle
// Check if SDK is initializedfinal isInit = awaitZendeskMessaging.isInitialized();
// Invalidate SDK instance (cleanup)awaitZendeskMessaging.invalidate();
// After invalidate, you must call initialize() again to use the SDK
iOS 14.0 minimum - Apps targeting iOS 12/13 must upgrade
Dart 3.6+ required - Update your SDK constraint
Flutter 3.24+ required - Update your Flutter SDK
New event API - Use sealed class pattern for type-safe event handling
Migration Steps
Update pubspec.yaml:
environment:sdk:^3.6.0flutter:">=3.27.0"
Update iOS Podfile:
platform :ios, '14.0'
Update event handling (optional but recommended):
// Old way (still works)ZendeskMessaging.unreadMessagesCountStream.listen((count) {
print('Unread: $count');
});
// New way (recommended)ZendeskMessaging.eventStream.listen((event) {
if (event isUnreadMessageCountChanged) {
print('Unread: ${event.totalUnreadCount}');
}
});
Troubleshooting
iOS Build Fails
Ensure your Podfile has the correct platform version: