Twilio is a modern communication API Used by developers to build unique, personalized experiences application for their customers. Twilio can be used to send SMS, WhatsApp, Voice, Video, email, etc across the customer journey.

Requirements:

  1. i. Buy phone number
  2. Sms Api ( twilio provide bills for sending messsage)

NOTE: Different price for different country for sending sms

Set Up:

  1. Create account in Twilio .
  2. Generate auth id and auth token.
    1. After login click on the Account link in the top-right navigation.
    2. In the submenu, click on API keys & tokens. Console | Twilio ← click to redirect

Verify Number:

In trial period we send sms only verified mobile number. To verify number follow the steps:

  • i. After login goto console
  • ii. In left corner Develop > Phone Numbers > Manage > Verified Callers Console | Twilio ← redirect
  • iii. Add new caller id

Implementation:

1.Add Twilio Dependency

<dependency>
			<groupId>com.twilio.sdk</groupId>
			<artifactId>twilio</artifactId>
			<version>8.32.0</version>
</dependency>

2. Add auth-id and auth-key in appliction.properties.

3. Integration step:

i. Set up the Twilio environment with unique Account Sid(auth-id) and Token(auth-token).

  • To set environment Twilio provide a init() method.
  • Call this method and pass auth- id and token.
Twilio.init(ACCOUNT_SID,AUTH_TOKEN);

ii. Create Message .

  • Create message in twilio by using Message.creator()
  • pass to and from phone numbers and message and call create();
Message message=Message.creator(new PhoneNumber(user.getPhoneNo())
                ,new PhoneNumber(FRM_NUMBER),msg).create();

Example:

Set Twilio Environment :

  1. To set environment we create a TwilioConfig class

1.Set auth-id, auth- token and from number as parameter.

2.Create TwilioInitializer to call Twilio init() method .

TwilioConfig:

TwilioInitiazer:

Class:

  1. User:It is end user entity, where we send SMS to user phone number.

2. OTP: To generate and save otp in db.

Dtos:

  1. OtpReqDto:

2. OtpDto:

Controller:

  1. SmsController:

Service:

  1. SmsService: