SMS Gateway Integration with Laravel/NestJS in Nepal
To integrate an SMS gateway in Nepal with Laravel or NestJS, choose a provider like Sparrow SMS or Aakash SMS, store API credentials in environment variables, create a dedicated service class for sending messages, implement queue-based asynchronous sending, add proper error handling and retry logic, and validate Nepali phone numbers in 97XX or 98XX format.
Introduction to SMS Gateway Integration in Nepal
Integrating an SMS gateway into your web application is a critical capability for businesses operating in Nepal. Whether you are building a customer notification system, implementing two-factor authentication, running marketing campaigns, or sending transactional alerts, a well-integrated SMS gateway connects your application directly to the mobile phones of your users. For developers in Nepal working with popular frameworks like Laravel (PHP) and NestJS (Node.js/TypeScript), understanding how to properly integrate with local SMS providers is an essential skill.
Nepal's SMS gateway ecosystem offers several providers, each with their own API specifications, pricing models, and feature sets. Sparrow SMS, Aakash SMS, and Nepal SMS are among the most widely used providers, offering RESTful APIs that can be integrated into virtually any web application. This guide provides a comprehensive walkthrough of integrating these SMS gateways with both Laravel and NestJS, covering everything from initial setup to production-ready implementations with error handling, rate limiting, and delivery tracking.
The choice between Laravel and NestJS often depends on your team's expertise and existing infrastructure. Laravel, built on PHP, is widely used by Nepali development agencies and freelancers due to its gentle learning curve and extensive ecosystem. NestJS, built on Node.js with TypeScript support, is gaining popularity among Nepali startups and tech companies that prefer JavaScript-based full-stack development. Regardless of your framework choice, the integration principles remain similar, and this guide covers both in parallel.
Choosing an SMS Gateway Provider in Nepal
Sparrow SMS
Sparrow SMS is one of the most established SMS gateway providers in Nepal, offering robust APIs for both single and bulk message delivery. Their REST API supports JSON payloads, making integration straightforward with modern web frameworks. Sparrow SMS provides features including delivery reports, sender ID customization, scheduled messaging, and Unicode support for sending messages in Devanagari script. Pricing is volume-based, with rates becoming more competitive at higher message volumes.
Aakash SMS
Aakash SMS provides a simple HTTP-based API that is particularly easy to integrate for developers new to SMS gateway integration. Their API accepts both GET and POST requests, with parameters for recipient number, message text, and authentication token. Aakash SMS offers competitive pricing for small to medium businesses and provides a user-friendly dashboard for monitoring message delivery and managing contacts. Their API documentation is straightforward and includes code examples in multiple programming languages.
Nepal SMS and Other Providers
Several other providers including Nepal SMS, Classic Tech SMS, and BroadLink SMS offer gateway services in Nepal. When evaluating providers, consider factors such as API reliability and uptime, delivery speed across all Nepali carriers (NTC, Ncell, Smart Telecom), support for Unicode and Devanagari text, webhook support for delivery receipts, documentation quality, and customer support responsiveness. Request sandbox or test accounts from multiple providers before committing to a production integration.
Laravel SMS Gateway Integration
Setting Up the Laravel Project
Begin by creating a new Laravel project or working within your existing application. Install the required HTTP client package if not already available. Laravel ships with the HTTP facade that wraps Guzzle HTTP, which is perfectly suited for making API calls to SMS gateways. Store your SMS gateway credentials in the environment configuration file to keep sensitive data out of your codebase.
Create a configuration file specifically for SMS settings. This file should contain your gateway provider's API endpoint URL, authentication token, sender ID, and any other provider-specific settings. Using Laravel's configuration system ensures that these values are cached in production and easily accessible throughout your application. Define your configuration entries for the API URL, the token, and the sender identity that will appear on recipients' devices.
Creating the SMS Service Class
Build a dedicated SMS service class that encapsulates all gateway communication logic. This service class should handle single message sending, bulk message sending, delivery status checking, and error handling. Implement the service as a Laravel service provider so it can be injected into controllers, jobs, and other classes via dependency injection. The service class should accept the recipient phone number and message text as parameters, validate the phone number format (Nepali numbers should be 10 digits starting with 97 or 98), and make the HTTP POST request to the gateway API.
Your service class should include robust error handling for common failure scenarios including network timeouts, invalid API credentials, insufficient balance, invalid phone numbers, and rate limit exceeded responses. Log all SMS sending attempts with their outcomes to a dedicated log channel or database table for troubleshooting and audit purposes. This logging becomes invaluable when debugging delivery issues or reconciling SMS costs with your gateway provider.
Implementing Queue-Based Sending
For production applications, always send SMS messages through Laravel's queue system rather than synchronously during HTTP requests. Create a dedicated SendSms job class that accepts the phone number and message text, then dispatches it to a queue. This approach prevents SMS API latency from slowing down your application's response times and provides automatic retry capability for failed sends.
Configure a dedicated queue for SMS jobs with appropriate retry settings. A typical configuration might allow three retry attempts with a 60-second delay between retries. Use exponential backoff for retries to avoid overwhelming the SMS gateway during temporary outages. Set a maximum retry limit after which the job moves to the failed jobs table for manual review. Monitor your SMS queue regularly to ensure messages are being processed in a timely manner.
Building the Notification System
Laravel's notification system provides an elegant way to integrate SMS sending into your application logic. Create a custom SMS notification channel that uses your SMS service class to deliver notifications. This allows you to use Laravel's standard notification syntax, including the ability to send notifications via multiple channels (SMS, email, database) from a single notification class. Define a routeNotificationForSms method on your User model that returns the user's phone number.
Create notification classes for common use cases such as order confirmation, OTP verification, password reset, payment received, and shipping update notifications. Each notification class defines the SMS message content and can include dynamic data from your application. This structured approach makes it easy to manage all your SMS templates in one place and ensures consistency across your application's messaging.
NestJS SMS Gateway Integration
Setting Up the NestJS Project
Create a new NestJS project or work within your existing application. Install the required HTTP module and configuration packages. NestJS uses the HttpModule based on Axios for making external API requests, which integrates seamlessly with the framework's dependency injection system. Store your SMS gateway credentials in environment variables and access them through NestJS's ConfigModule.
Create a dedicated SMS module that encapsulates all SMS-related functionality. This module should export an SmsService that can be imported by other modules throughout your application. Following NestJS's modular architecture ensures clean separation of concerns and makes your SMS integration easily testable and maintainable. Register the module globally if SMS functionality is needed across multiple parts of your application.
Creating the SMS Service
Build an SmsService class decorated with the Injectable decorator. This service should inject the HttpService and ConfigService through the constructor. Implement methods for sending single messages, sending bulk messages, and checking delivery status. The send method should accept a phone number and message text, validate the input parameters, and make the HTTP POST request to the gateway API using the HttpService.
Implement proper error handling using NestJS's exception filters and RxJS error handling operators. The HttpService returns Observables, so use the pipe operator with catchError to handle network failures, API errors, and timeout scenarios. Convert the Observable to a Promise using firstValueFrom if your application uses async/await patterns. Log all sending attempts using NestJS's built-in Logger class for debugging and monitoring.
Implementing Queue-Based Sending with Bull
For production deployments, integrate the Bull queue library through NestJS's BullModule to handle SMS sending asynchronously. Create a dedicated SMS queue processor that picks up jobs from the queue and processes them through your SmsService. This approach decouples SMS sending from your API response cycle and provides built-in retry mechanisms with configurable backoff strategies.
Define your queue processor with appropriate concurrency settings. For most Nepali SMS gateway providers, a concurrency of five to ten is reasonable to avoid hitting rate limits while maintaining good throughput. Configure job retry settings with exponential backoff, starting at 30 seconds and doubling with each attempt up to a maximum of five retries. Implement a dead letter queue for messages that fail after all retry attempts, allowing you to investigate and manually resend if necessary.
Building Middleware for Rate Limiting
Implement rate limiting middleware to prevent your application from exceeding the SMS gateway provider's API limits. Most Nepali SMS providers enforce rate limits of 10 to 50 requests per second. Create a custom NestJS guard or interceptor that tracks API calls and queues excess requests. Use Redis-based rate limiting for distributed applications running multiple server instances.
Beyond API rate limiting, implement business logic rate limiting to prevent abuse scenarios such as a user requesting excessive OTPs or a bug triggering repeated notifications. Set per-user and per-phone-number limits for different message types. For example, limit OTP messages to five per hour per phone number, and promotional messages to two per day per subscriber. These safeguards protect both your SMS budget and your users' experience.
Shared Integration Patterns for Both Frameworks
Phone Number Validation and Formatting
Proper phone number validation is critical for both cost efficiency and delivery reliability. Nepali mobile numbers follow the format 97XXXXXXXX or 98XXXXXXXX (10 digits). Some users may input numbers with the country code prefix (+977 or 977), with spaces or dashes, or with a leading zero. Your validation logic should strip all non-numeric characters, remove the country code prefix if present, and verify that the remaining number is exactly 10 digits starting with 97 or 98.
Message Template Management
Implement a template management system for your SMS messages rather than hardcoding message text throughout your application. Store templates in your database or configuration files with placeholder variables that are replaced at send time. This approach allows non-technical staff to modify message content without code changes, supports multilingual messages (Nepali and English), and ensures consistent messaging across your application.
Delivery Reporting and Analytics
Implement comprehensive delivery tracking by storing every SMS send attempt in your database with the recipient number, message content hash, gateway response, delivery status, and timestamp. If your SMS gateway provider supports delivery receipt webhooks, create an endpoint that receives and processes these callbacks to update your delivery records. Build a simple dashboard or reporting query that shows key metrics including total messages sent, delivery success rate, failure reasons, and cost per message.
Testing Your SMS Integration
Write comprehensive tests for your SMS integration using each framework's testing tools. In Laravel, use HTTP fakes to mock gateway API responses and test your service class without making actual API calls. In NestJS, use Jest with mocked HttpService to achieve the same goal. Test both success and failure scenarios, including network timeouts, invalid credentials, and rate limit responses. Create a staging environment that connects to your SMS provider's sandbox API for end-to-end testing before deploying to production.
Conclusion
Integrating an SMS gateway with Laravel or NestJS in Nepal requires careful attention to provider selection, error handling, queue management, and rate limiting. By following the patterns and practices outlined in this guide, you can build a robust, production-ready SMS integration that reliably delivers messages to your Nepali users across all major carriers. Whether you choose Laravel's elegant service provider architecture or NestJS's modular dependency injection system, the key principles remain the same—validate inputs, handle errors gracefully, send asynchronously, and monitor delivery metrics. Start with a single provider integration, test thoroughly, and expand your implementation as your business requirements grow.
Frequently Asked Questions
Which SMS gateway provider is best for Laravel or NestJS integration in Nepal?
Sparrow SMS and Aakash SMS are the most popular choices for framework integration in Nepal. Sparrow SMS offers a well-documented REST API with JSON payloads that integrates cleanly with both Laravel HTTP facade and NestJS HttpModule. Aakash SMS provides a simpler HTTP-based API that is easier for beginners. Choose based on your delivery rate requirements, pricing, and whether you need features like Unicode Devanagari support and delivery webhooks.
Should I send SMS synchronously or asynchronously in my web application?
Always send SMS messages asynchronously through a queue system in production applications. In Laravel, use the built-in queue system with a dedicated SendSms job class. In NestJS, use the BullModule with a dedicated SMS queue processor. Synchronous SMS sending blocks your HTTP request while waiting for the gateway API response, which degrades user experience and can cause timeouts during high-traffic periods or gateway slowdowns.
How do I validate Nepali phone numbers in my application?
Nepali mobile numbers follow the format 97XXXXXXXX or 98XXXXXXXX, totaling 10 digits. Your validation logic should strip all non-numeric characters, remove the country code prefix (+977 or 977) if present, remove any leading zero, and verify the remaining number is exactly 10 digits starting with 97 or 98. Implement this validation in a shared utility function that both your Laravel and NestJS applications can use before sending any SMS.
What rate limiting should I implement for SMS gateway APIs in Nepal?
Most Nepali SMS gateway providers enforce rate limits of 10 to 50 requests per second. Implement API-level rate limiting in your application using Redis-based throttling to stay within these limits. Additionally, implement business logic rate limiting to prevent abuse, such as limiting OTP messages to five per hour per phone number and promotional messages to two per day per subscriber. In NestJS, use a custom guard or interceptor, and in Laravel, use the built-in rate limiting middleware.