My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
How to send SMS in spring boot application

How to send SMS in spring boot application

HARRISON OGBONNAYA's photo
HARRISON OGBONNAYA
·Apr 28, 2022·

5 min read

This article covers the process for integrating SMS "Short message Service" to your spring boot application.

Prerequisite: Should have basic understanding on how to use Java language and how to create a springboot application.

STEP 1 : Lets go ahead and create our spring boot application using springinitializr.io and set up our work environment using any IDE of your choice.

STEP 2 : As part of our setup process you will need to add this dependency to our pom.xml file

<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>

Refresh the pom file and start the application

STEP 3 : set up your application properties as follows:

myApp.sendChamp_publicKey = ${sendChamp_publicKey}
myApp.sendChamp_baseUrl= https://api.sendchamp.com/api/v1/sms/send
myApp.sendChamp_senderId_Url= https://api.sendchamp.com/api/v1/sms/create-sender-id

This always allows us to make our details not visible to the public.

STEP 4 : Create a package called smsConfig and create a class called SendChampConfig in it. copy the code below into the class.

import com.squareup.okhttp.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;



@Data
@Component
public class SendChampConfig {

    @Value("${myApp.sendChamp_baseUrl}")
    private String sendChampUrl;
    private final MediaType mediaType = MediaType.parse("application/json");
    @Value("${myApp.sendChamp_publicKey}")
     private String authorization;

    @Value("${myApp.sendChamp_senderId_Url}")
     private String senderIdUrl;

}

One of the most important thing we did here was importing the package from:

import com.squareup.okhttp.*;

Then we added our spring boot annotations such as @Data and @Component which allows spring boot to create a bean and pojos for our class.

After which we created our field variables to enable us store our details from sendChamp.

STEP 5 : Create another package in our src folder for our service implementation call it sms. Then create a package inside it called service and create an interface class called SmsService

package myApps.sms.service;

import myApps.sms.payload.requestPyload.SenderIdRequest;
import myApps.sms.payload.requestPyload.SmsRequest;
import myApps.sms.payload.requestPyload.SmsRequestForAllUsers;
import org.springframework.http.HttpEntity;

import java.io.IOException;

public interface SmsService {
    HttpEntity<SmsRequest> sendSms(SmsRequest smsRequest) throws IOException;
    HttpEntity<SmsRequestForAllUsers> sendSmsToAllRegisteredUsers(SmsRequestForAllUsers request);

}

As you can see this code above has some Classes we haven't created yet but we will in a moment.

Our interface has a HttpEntity is a helper object which encapsulates header and body of an HTTP request or response. It can be used as a handler method parameter.

  HttpEntity<SmsRequest> sendSms(SmsRequest smsRequest)

So we created a sendSms HttpEntity method of type SmsRequest. This accepts an sms request which we want to send to the user

HttpEntity<SmsRequestForAllUsers> sendSmsToAllRegisteredUsers(SmsRequestForAllUsers request);

and then we created another service called sendSmsToAllRegisteredUsers of type SmsRequestForAllUsers and accepts a parameter called SmsRequestForAllUsers .

STEP 6 : Lets go ahead and implement it by creating a java class called SmsServiceImpl

@AllArgsConstructor
@Service
public class SmsServiceImpl implements SmsService {
    private final SendChampConfig sendChampConfig;
    private final UserRepository repository;
    private final OkHttpClient client = new OkHttpClient();
    private final UserRepository userRepository;
    private final UserService userService;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Override
    public HttpEntity<SmsRequest> sendSms(SmsRequest smsRequest) throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(sendChampConfig.getAuthorization());
        return new HttpEntity<>(smsRequest, httpHeaders);
    }


    @Override
    public HttpEntity<SmsRequestForAllUsers> sendSmsToAllRegisteredUsers(SmsRequestForAllUsers request) {
        List<CivilUser> users = repository.findAll();
        for (CivilUser user : users) {
            if (user.getPhoneNumber() != null) request.getTo().add(user.getPhoneNumber());
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(sendChampConfig.getAuthorization());

        return new HttpEntity<>(request, httpHeaders);
    }

}
    private final SendChampConfig sendChampConfig;
    private final UserRepository repository;
    private final OkHttpClient client = new OkHttpClient();
    private final UserRepository userRepository;
    private final UserService userService;

Let me explain the code above before we move on to the next step. We stated by annotating it with @service a way to tell springboot that this is a service class also using @AllArgsConstructor gives us the access to all argument constructor. We then created object of these classes above.

import org.springframework.context.annotation.Bean;

@Bean
public RestTemplate restTemplate(){
        return new RestTemplate();
        }

Then a bean of a RestTemplate was created using @Bean and we created a new rest template:

 @Override
    public HttpEntity<SmsRequest> sendSms(SmsRequest smsRequest) throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(sendChampConfig.getAuthorization());
        return new HttpEntity<>(smsRequest, httpHeaders);
    }

Next we created a HttpEntity that takes in a request payload that we'll soon be creating. Also Java provides us with HttpHeaders class which we will use to set content type and bearer authentication, after that is done we then return the httpEntity we created with the sms request and the http headers.

NEXT STEP: we created another request to send to all users here is the code sippet below

@Override
    public HttpEntity<SmsRequestForAllUsers> sendSmsToAllRegisteredUsers(SmsRequestForAllUsers request) {
        List<CivilUser> users = repository.findAll();
        for (CivilUser user : users) {
            if (user.getPhoneNumber() != null) request.getTo().add(user.getPhoneNumber());
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(sendChampConfig.getAuthorization());

        return new HttpEntity<>(request, httpHeaders);
    }

Here all we are just trying to do in the above code is get a list of users then loop through each user if the user has a phone number, we add it to numbers we want to send sms to, then create another entity to for sending the sms.

STEP 7 : Lets now create our payload for sms request. Simply create a package called Payload and create two packages called requestPayload and responsePayload respectively. Inside requestPayload create a class called SmsRequest and copy the code below to it.

import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

@Data
public class SmsRequest {
    @NotBlank
    @NotNull
    private List<String> to;

    private String sender_name;

    private String route;

    @NotBlank
    @NotNull
    private String message;
}

Here we just defined the fields we feel we might require for our sms. This is going to be our request for sending sms.

STEP 8 : Create another class called SingleSmsRequest paste the code below inside it

package myApp.apps.sms.payload.requestPyload;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

@Data
public class SingleSMSRequest {

    @NotBlank
    @NotNull
    private String phoneNumber;

    private String sender_name;

    private String route;

    @NotBlank
    @NotNull
    private String message;
}

Here we also defined some fields we require for sending a single user request payload.

    @NotBlank
    @NotNull
    private String phoneNumber;

This field will store the required number we want to send sms to. We also made it not null and not blank by annotating it with @NotNull and @NotBlank

private String sender_name;

this will store the sender name.

private String route;

We will be needing a route this is gotten from the service providers.

STEP 9 : Goto response Payload and create a class for it. then copy this code to it.

import lombok.Data;

@Data
public class SmsResponse {
    private String status;
    private String code;
    private String message;
}

Here we created a response which the user will get on successful creation or failure. NOTE: these payloads are what we referenced in our service class for our implementation.

Conclusion. This feature allows us to send sms to a user or multiple users using spring boot and our implementation was for us to see what the code looks like and how straight forward it was to achieve.