Twilio SMS API Integration with Java & Spring Boot for Sending OTP
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:
- i. Buy phone number
- Sms Api ( twilio provide bills for sending messsage)
NOTE: Different price for different country for sending sms
Set Up:
- Create account in Twilio .
- Generate auth id and auth token.
- After login click on the Account link in the top-right navigation.
- 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 :
- 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:
- User:It is end user entity, where we send SMS to user phone number.
2. OTP: To generate and save otp in db.
Dtos:
- OtpReqDto:
2. OtpDto:
Controller:
- SmsController:
Service:
- SmsService:
Categories
Recent Posts
- Client Device Identification in REST API using Java & Spring Boot
- Extract Meta Data and Compress RAW Images using Python
- Twilio SMS API Integration with Java & Spring Boot for Sending OTP
- Razorpay Payment Gateway Implementation for Merchants using Java & Spring Boot
- Pagination using Spring Boot & Spring Data JPA