NestJS: Sending SMS with smsglobal

NestJS: Sending SMS with smsglobal

In this tutorial, we’ll explore how to integrate the smsglobal API with NestJS to send SMS messages. smsglobal is a popular SMS provider with a well-documented API that allows you to send and receive SMS messages programmatically.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • Node.js and npm installed on your machine
  • Basic understanding of NestJS
  • Access to an smsglobal account with API credentials

Step 1: Setting Up the Project

To get started, let’s create a new NestJS project using the Nest CLI:

$ nest new nest-sms-smsglobal

Once the project is created, navigate to the project directory:

$ cd nest-sms-smsglobal

Step 2: Installing Dependencies

Next, let’s install the necessary dependencies for our project. We’ll need the axios package to make HTTP requests to the smsglobal API:

$ npm install axios

Step 3: Configuring the smsglobal API

Now, let’s configure the smsglobal API in our NestJS project. Create a new file called sms.config.ts in the root of your project, and add the following code:

// sms.config.ts

export const smsConfig = {
  apiKey: 'YOUR_API_KEY',
  apiSecret: 'YOUR_API_SECRET',
  sender: 'YOUR_SENDER_NAME',
};

Replace 'YOUR_API_KEY', 'YOUR_API_SECRET', and 'YOUR_SENDER_NAME' with your actual smsglobal API credentials.

Step 4: Sending SMS with smsglobal

With the API configured, let’s create a service to handle sending SMS messages using the smsglobal API. Create a new file called sms.service.ts in the src directory, and add the following code:

// sms.service.ts

import { Injectable } from '@nestjs/common';
import axios from 'axios';
import { smsConfig } from '../sms.config';

@Injectable()
export class SmsService {
  private readonly apiUrl = 'https://api.smsglobal.com/v2/';

  async sendSms(recipient: string, message: string): Promise<void> {
    try {
      await axios.post(
        `${this.apiUrl}/sms`,
        {
          destination: recipient,
          message: message,
          origin: smsConfig.sender,
        },
        {
          auth: {
            username: smsConfig.apiKey,
            password: smsConfig.apiSecret,
          },
        },
      );
      console.log('SMS sent successfully');
    } catch (error) {
      console.error('Failed to send SMS: ', error.response.data);
      throw new Error('Failed to send SMS');
    }
  }
}

Step 5: Using the SMS Service

Now that we have our service set up, let’s use it to send an SMS message. Open the app.controller.ts file in the src directory, and update the code as follows:

// app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { SmsService } from './sms.service';

@Controller()
export class AppController {
  constructor(private readonly smsService: SmsService) {}

  @Get('send-sms')
  async sendSms(): Promise<string> {
    const recipient = '+1234567890'; // Replace with the recipient's phone number
    const message = 'Hello from NestJS!'; // Replace with your desired message

    await this.smsService.sendSms(recipient, message);

    return 'SMS sent successfully';
  }
}

Update the recipient variable with the phone number of the recipient and message variable with your desired message.

Step 6: Testing the Application

To test our application, start the NestJS server:

$ npm run start:dev

Once the server is running, open your browser and navigate to http://localhost:3000/send-sms. If everything is set up correctly, you should see the message “SMS sent successfully” in your browser console.

Congratulations! You have successfully integrated the smsglobal API with NestJS to send SMS messages.

Conclusion

In this tutorial, we explored how to integrate the smsglobal API with NestJS to send SMS messages. We configured the API credentials, created a service to handle sending SMS messages, and used the service in a controller to send an SMS. Feel free to customize this implementation to fit your specific use case or explore other API endpoints provided by smsglobal.