flutter_afriksms
A powerful and easy-to-use Dart package for integrating the AfrikSMS API. Send SMS messages, bulk campaigns, check your balance, and receive delivery reports with just a few lines of code.
Features
- βοΈ Send Single SMS - Send SMS to individual recipients
- π€ Send Bulk SMS - Send the same message to up to 500 recipients
- π¬ Personalized Bulk SMS - Send customized messages to multiple recipients
- π§ SMS with Email - Send SMS with optional email notifications
- π Delivery Reports - Receive real-time delivery status via webhooks
- π° Check Balance - Query your account balance for all countries
- βοΈ Configure Callbacks - Set up webhook URLs for delivery reports
- π Type-Safe - Fully typed with comprehensive error handling
- β Validation - Built-in input validation for phone numbers and parameters
- π Logging - Optional debug logging for troubleshooting
Getting Started
Installation
Add this to your package's pubspec.yaml file:
dependencies:
flutter_afriksms: ^1.0.0
Then run:
dart pub get
Prerequisites
- Create an AfrikSMS account by reaching afriksms.com/.
- Get your credentials by contacting support@afriksms.com.
- Purchase SMS credits to start sending messages.
Usage
Basic Example
import 'package:flutter_afriksms/flutter_afriksms.dart';
Future<void> main() async {
// Create the client
final client = AfrikSmsClient(
config: AfrikSmsConfig(
clientId: 'your_client_id',
apiKey: 'your_api_key',
senderId: 'MYAPP',
enableLogging: true,
),
);
try {
// Send an SMS
final response = await client.sendSms(
phoneNumber: '22890909090',
message: 'Hello from AfrikSMS!',
);
if (response.isSuccess) {
print('SMS sent! Resource ID: ${response.resourceId}');
}
} finally {
client.close();
}
}
Send Bulk SMS
final response = await client.sendBulkSms(
phoneNumbers: '22890909090,22996760000,22378810000',
message: 'Bulk SMS to multiple recipients',
);
print('Sent: ${response.successCount}/${response.data.length}');
Send Personalized Bulk SMS
final response = await client.sendPersonalizedBulkSms(
messages: [
PersonalizedSmsMessage(
mobileNumbers: '22890909090',
message: 'Hello Bernard, your order #123 is ready!',
),
PersonalizedSmsMessage(
mobileNumbers: '22996760000',
message: 'Hello Modeste, your appointment is tomorrow.',
),
],
);
Send SMS with Email
final response = await client.sendSmsWithEmail(
phoneNumber: '22890909090',
message: 'Your verification code is 123456',
email: 'user@example.com',
subject: 'Verification Code',
);
Check Balance
final balance = await client.checkBalance();
print('Total credits: ${balance.totalCredits}');
for (final country in balance.information) {
print('${country.country}: ${country.solde} SMS');
}
Configure Callback URL
final config = await client.configureCallback(
notifyUrl: 'https://yourdomain.com/delivery-report',
notificationType: NotificationType.post,
);
Handle Delivery Reports
In your webhook endpoint:
// Parse the delivery report from your webhook
final report = AfrikSmsClient.parseDeliveryReport(request.queryParameters);
if (report.isSuccess) {
print('SMS ${report.resourceId} was delivered successfully!');
} else if (report.isPending) {
print('SMS ${report.resourceId} is pending delivery');
} else if (report.isFailed) {
print('SMS ${report.resourceId} failed: ${report.message}');
}
Error Handling
The package provides specific exception types for different errors:
try {
await client.sendSms(
phoneNumber: '22890909090',
message: 'Test message',
);
} on AuthenticationException catch (e) {
// Invalid ClientId or ApiKey
print('Authentication error: ${e.message}');
} on AuthorizationException catch (e) {
// IP not whitelisted or sender not authorized
print('Authorization error: ${e.message}');
} on ValidationException catch (e) {
// Invalid input parameters
print('Validation error: ${e.message}');
} on NetworkException catch (e) {
// Connection issues
print('Network error: ${e.message}');
} on TimeoutException catch (e) {
// Request timeout
print('Timeout: ${e.message}');
} on RateLimitException catch (e) {
// Too many requests
print('Rate limit exceeded: ${e.message}');
} on AfrikSmsException catch (e) {
// Any other AfrikSMS error
print('Error: ${e.message}');
}
Configuration
AfrikSmsConfig
| Parameter | Type | Required | Description |
|---|---|---|---|
clientId |
String | Yes | Your unique API identifier |
apiKey |
String | Yes | Your API authentication key |
senderId |
String | Yes | Sender name (max 11 characters) |
enableLogging |
bool | No | Enable debug logging (default: false) |
timeout |
Duration | No | Request timeout (default: 30 seconds) |
Phone Number Format
β οΈ Important: Phone numbers must include the country code without the + or 00 prefix.
β
Correct: 22890909090
β Incorrect: +22890909090, 0022890909090, 90909090
API Endpoints
All endpoints are available through the AfrikSmsClient:
| Method | Description | Max Recipients |
|---|---|---|
sendSms() |
Send single SMS | 1 |
sendBulkSms() |
Send same message to multiple recipients | 500 |
sendPersonalizedBulkSms() |
Send customized messages | 500 |
sendSmsWithEmail() |
Send SMS with email notification | 1 |
configureCallback() |
Configure delivery report webhook | - |
checkBalance() |
Check account balance | - |
parseDeliveryReport() |
Parse delivery report (static) | - |
Response Models
SmsResponse
code- Response code (100 = success)message- Status messageresourceId- Unique tracking identifierisSuccess- Convenience property
BulkSmsResponse
code- Overall response codemessage- Status messagedata- List of individual delivery statusessuccessCount- Number of successful deliveriesfailureCount- Number of failed deliveriessuccessfulItems- List of successful itemsfailedItems- List of failed items
BalanceResponse
code- Response codemessage- Status messageinformation- List of country balancestotalCredits- Total credits across all countriesgetBalanceForCountry(country)- Get balance for specific country
DeliveryReport
resourceId- Original SMS identifiercode- Delivery status codemessage- Delivery status messagestatus- Enum (success/pending/failed)isSuccess/isPending/isFailed- Convenience properties
Delivery Status Codes
| Code | Status | Description |
|---|---|---|
000 |
Success | Successfully delivered to recipient |
001 |
Pending | Sent to operator, awaiting confirmation |
002 |
Failed | Number unreachable or reception error |
Best Practices
Security
- Never expose credentials in client-side code
- Store
ClientIdandApiKeyin environment variables - Use HTTPS for callback URLs
- Add authentication tokens to webhook URLs
Performance
- Use bulk endpoints for multiple recipients
- Implement exponential backoff for retries
- Monitor rate limits
Message Content
- Standard SMS: 160 characters
- Unicode SMS (with emojis/accents): 70 characters
- Messages exceeding limits are sent as multiple SMS
Testing
- Test with your own phone number first
- Verify callback URL receives delivery reports
- Monitor balance to avoid service interruption
Example Project
A complete example is available in the example directory. Run it with:
cd example
dart run example.dart
Documentation
For detailed API documentation, visit the AfrikSMS API Documentation.
Support
Issues
If you encounter any issues, please file them on GitHub Issues.
Contact
- Email: support@afriksms.com
- Website: https://api.afriksms.com
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
See CHANGELOG.md for a list of changes.
Made with β€οΈ for the AfrikSMS community
Libraries
- flutter_afriksms
- A powerful and easy-to-use Dart package for integrating AfrikSMS API.