1. Authentication Setup
Proper authentication is the foundation of secure API integration. Follow these steps:
- Generate API Key: Create a unique API key from your MacraSMS dashboard under Settings > API Keys
- Store Securely: Never hardcode API keys in source code. Use environment variables or secrets management tools
- Verify Sender ID: Ensure your registered Sender ID matches exactly what you pass in API requests
- Test Credentials: Make a test request using sandbox credentials before switching to production
- Rotate Regularly: Plan to rotate API keys every 90 days as a security best practice
Critical Security Rule
Never commit API keys to version control systems like Git. Use .env files excluded from repositories or cloud-native secrets managers.
2. Environment Configuration
Configure your application environments correctly:
| Setting | Sandbox | Production |
|---|---|---|
| Base URL | https://sms.macrasms.com/api/v1/sandbox/ |
https://sms.macrasms.com/api/v1/ |
| API Key | Sandbox-specific key | Production API key |
| Sender ID | TESTID (pre-approved) | Your registered brand Sender ID |
| Rate Limit | 10 req/min | 100 req/min (standard tier) |
| Billing | Free test credits | Deducted from account balance |
3. Error Handling
Implement comprehensive error handling for all API responses:
- HTTP 400: Validate request parameters before sending. Log invalid requests for debugging
- HTTP 401: Trigger immediate alert if authentication fails. Check API key validity and expiration
- HTTP 402: Handle insufficient balance gracefully. Notify admin and pause non-critical sends
- HTTP 429: Implement exponential backoff when rate limited. Never ignore rate limit headers
- HTTP 5xx: Retry with exponential backoff up to 3 attempts. Log server errors for monitoring
- Timeout: Set 30-second timeout for all requests. Handle timeouts as transient failures
// Example: Robust error handling pattern
try {
const response = await fetch(apiUrl, options);
if (!response.ok) {
switch(response.status) {
case 401: throw new AuthError('Invalid credentials');
case 402: throw new BalanceError('Insufficient funds');
case 429: throw new RateLimitError('Rate limited');
default: throw new ApiError(`HTTP ${response.status}`);
}
}
return await response.json();
} catch (error) {
logger.error('SMS API failed', { error: error.message });
// Implement fallback or notification logic
}
4. Retry Logic
Transient failures are inevitable. Implement smart retry strategies:
- Exponential Backoff: Start with 1s delay, double after each attempt (1s → 2s → 4s)
- Maximum Retries: Cap at 3 attempts to avoid infinite loops
- Jitter: Add random jitter (±25%) to prevent thundering herd problems
- Idempotency: Use unique message IDs to prevent duplicate sends on retry
- Circuit Breaker: Stop retrying after consecutive failures to protect system stability
Retry Caution
Only retry on transient errors (5xx, timeouts, 429). Never retry on 400, 401, or 402 errors - these require manual intervention.
5. Webhook Setup
Configure webhooks for real-time delivery status updates:
- Endpoint Security: Protect webhook endpoints with signature verification using shared secret
- Response Time: Respond within 5 seconds to avoid carrier timeout retries
- Idempotent Processing: Handle duplicate webhook deliveries gracefully using message IDs
- Error Logging: Log all webhook payloads for debugging and audit purposes
- Fallback Polling: Implement periodic status polling as backup if webhooks fail
6. Testing Procedures
Thoroughly test before going live:
- Sandbox Testing: Send test messages to verified numbers using sandbox credentials
- Error Simulation: Test all error scenarios (invalid key, insufficient balance, invalid number)
- Bulk Testing: Send batch of 10+ messages to verify bulk endpoint behavior
- Webhook Testing: Verify webhook reception and processing with test delivery statuses
- Load Testing: Simulate peak traffic volume to validate rate limiting and performance
- User Acceptance: Have stakeholders verify message content, timing, and opt-out functionality
7. Security Hardening
Protect your integration against common vulnerabilities:
- Input Validation: Sanitize all phone numbers and message content before API calls
- HTTPS Only: Never make API calls over HTTP. Enforce TLS 1.2+
- Secret Management: Rotate API keys quarterly. Revoke compromised keys immediately
- Access Control: Restrict API access to authorized services only via IP whitelisting
- Audit Logging: Log all API requests with timestamps, IPs, and response codes
- Dependency Scanning: Regularly update SDKs and dependencies to patch security vulnerabilities
Security Bonus
Enable two-factor authentication on your MacraSMS dashboard account to add an extra layer of protection for API key management.
8. Pre-Launch Verification
Final checklist before enabling production traffic:
- ✅ Production API key configured and tested
- ✅ Registered Sender ID approved and active
- ✅ Sufficient account balance for expected volume
- ✅ Error handling and retry logic implemented
- ✅ Webhook endpoint secured and tested
- ✅ Monitoring and alerting configured for failures
- ✅ Opt-out mechanism functional and compliant
- ✅ Privacy notice displayed at consent capture points
- ✅ Team trained on API usage and incident response
- ✅ Rollback plan documented for emergency situations
Ready to Integrate?
Get your API key and 100 free test credits when you create a MacraSMS account.
Get API Key