flutter_afriksms 0.1.1
flutter_afriksms: ^0.1.1 copied to clipboard
A powerful and easy-to-use Dart package for integrating AfrikSMS API. Send SMS, bulk SMS, personalized campaigns, check balance, and receive delivery reports.
// ignore_for_file: avoid_print
import 'package:flutter_afriksms/flutter_afriksms.dart';
/// Complete example demonstrating all features of the AfrikSMS package.
Future<void> main() async {
// Create the client with your credentials
final client = AfrikSmsClient(
config: const AfrikSmsConfig(
clientId: '43475195', // Replace with your ClientId
apiKey: 'p-mKisPT9JdmzOvf54zcz1jpmc05UvrW', // Replace with your ApiKey
senderId: 'LELENG', // Your sender name (max 11 chars)
enableLogging: true, // Enable logging for debugging
timeout: Duration(seconds: 30),
),
);
try {
// ========================================
// Example 1: Send a single SMS
// ========================================
print('\n=== Example 1: Send Single SMS ===');
final smsResponse = await client.sendSms(
phoneNumber: '22890495033', // Replace with actual phone number
message: 'Hello! This is a test SMS from AfrikSMS package.',
);
if (smsResponse.isSuccess) {
print('✅ SMS sent successfully!');
print('Resource ID: ${smsResponse.resourceId}');
print('Message: ${smsResponse.message}');
} else {
print('❌ SMS failed: ${smsResponse.message}');
}
// ========================================
// Example 2: Send bulk SMS to multiple recipients
// ========================================
print('\n=== Example 2: Send Bulk SMS ===');
final bulkResponse = await client.sendBulkSms(
phoneNumbers: '22890495033,22897533546', // Comma-separated
message: 'This is a bulk SMS test to multiple recipients.',
);
print('Total sent: ${bulkResponse.data.length}');
print('Successful: ${bulkResponse.successCount}');
print('Failed: ${bulkResponse.failureCount}');
// Print details for each recipient
for (final item in bulkResponse.data) {
final status = item.isSuccess ? '✅' : '❌';
print('$status ${item.phone}: ${item.status} (${item.resourceId})');
}
// ========================================
// Example 3: Send personalized bulk SMS
// ========================================
print('\n=== Example 3: Send Personalized Bulk SMS ===');
final personalizedResponse = await client.sendPersonalizedBulkSms(
messages: [
const PersonalizedSmsMessage(
mobileNumbers: '22890495033',
message: 'Hello Bernard, this is your personalized message!',
),
const PersonalizedSmsMessage(
mobileNumbers: '22897533546',
message: 'Hello Modeste, your appointment is tomorrow at 10 AM.',
),
],
);
print(
'Personalized SMS sent: ${personalizedResponse.successCount}/${personalizedResponse.data.length}');
for (final item in personalizedResponse.data) {
print('${item.isSuccess ? "✅" : "❌"} ${item.phone}: ${item.status}');
}
// ========================================
// Example 4: Send SMS with email notification
// ========================================
print('\n=== Example 4: Send SMS with Email ===');
final emailSmsResponse = await client.sendSmsWithEmail(
phoneNumber: '22890495033',
message: 'Your verification code is 123456',
email: 'user@example.com', // Optional
subject: 'Verification Code', // Required if email is provided
);
if (emailSmsResponse.isSuccess) {
print('✅ SMS and Email sent successfully!');
print('Resource ID: ${emailSmsResponse.resourceId}');
}
// ========================================
// Example 5: Check account balance
// ========================================
print('\n=== Example 5: Check Balance ===');
final balance = await client.checkBalance();
if (balance.isSuccess) {
print('Total credits across all countries: ${balance.totalCredits}');
print('\nBalance by country:');
for (final country in balance.information) {
final hasCredits = country.hasCredits ? '✅' : '⚠️';
print('$hasCredits ${country.country}: ${country.solde} SMS');
}
// Get balance for a specific country
final togoBalance = balance.getBalanceForCountry('Togo');
if (togoBalance != null) {
print('\nTogo balance: ${togoBalance.solde} SMS');
}
}
// ========================================
// Example 6: Configure callback URL
// ========================================
print('\n=== Example 6: Configure Callback URL ===');
final callbackConfig = await client.configureCallback(
notifyUrl: 'https://yourdomain.com/sms/delivery-report?key=secret123',
notificationType: NotificationType.post, // or NotificationType.get
);
if (callbackConfig.isSuccess) {
print('✅ Callback URL configured successfully!');
print('URL: ${callbackConfig.notifyUrl}');
print('Method: ${callbackConfig.typeNotification.apiString}');
}
// ========================================
// Example 7: Parse delivery report (in your webhook)
// ========================================
print('\n=== Example 7: Parse Delivery Report ===');
// Simulating a delivery report received on your callback URL
final mockDeliveryReport = {
'resourceId': 'y1k9s-7FId27SKC3qwJ4Q6fkANQ_CuZc',
'code': '000',
'message': 'Successful delivered to Terminal',
};
final deliveryReport =
AfrikSmsClient.parseDeliveryReport(mockDeliveryReport);
print('Resource ID: ${deliveryReport.resourceId}');
print('Status: ${deliveryReport.status.name}');
print('Is Success: ${deliveryReport.isSuccess}');
print('Is Pending: ${deliveryReport.isPending}');
print('Is Failed: ${deliveryReport.isFailed}');
print('Message: ${deliveryReport.message}');
// ========================================
// Error Handling Examples
// ========================================
print('\n=== Example 8: Error Handling ===');
try {
// This will throw a ValidationException
await client.sendSms(
phoneNumber: '+22890909090', // Invalid: has + prefix
message: 'Test',
);
} on ValidationException catch (e) {
print('Validation error: ${e.message}');
}
try {
// This will throw a ValidationException
await client.sendSms(
phoneNumber: '22890909090',
message: '', // Invalid: empty message
);
} on ValidationException catch (e) {
print('Validation error: ${e.message}');
}
try {
// This will throw a ValidationException
await client.sendSms(
phoneNumber: '22890909090',
message: 'Test',
senderId: 'TOOLONGSENDERID', // Invalid: too long
);
} on ValidationException catch (e) {
print('Validation error: ${e.message}');
}
// Handle different exception types
try {
// Simulate an API call
await client.sendSms(
phoneNumber: '22890909090',
message: 'Test message',
);
} on AuthenticationException catch (e) {
print('❌ Authentication error: ${e.message}');
// Invalid ClientId or ApiKey
} on AuthorizationException catch (e) {
print('❌ Authorization error: ${e.message}');
// IP not whitelisted or sender not authorized
} on ValidationException catch (e) {
print('❌ Validation error: ${e.message}');
// Invalid input parameters
} on NetworkException catch (e) {
print('❌ Network error: ${e.message}');
// Connection issues
} on TimeoutException catch (e) {
print('❌ Timeout error: ${e.message}');
// Request took too long
} on RateLimitException catch (e) {
print('❌ Rate limit error: ${e.message}');
// Too many requests
} on ApiException catch (e) {
print('❌ API error: ${e.message}');
// Server returned an error
} on AfrikSmsException catch (e) {
print('❌ General error: ${e.message}');
// Any other AfrikSMS error
} catch (e) {
print('❌ Unexpected error: $e');
// Unknown error
}
print('\n✅ All examples completed!');
} finally {
// Always close the client when done
client.close();
}
}