Broadleaf Microservices
  • v1.0.0-latest-prod

Using Twilio To Send SMS messages with Broadleaf Notification Service

Twilio is a leading provider for sending SMS messages. Broadleaf provides an out of box implementation for integrating with Twilio using your Twilio account.

See the Twilio Website for more information on Twilio and to obtain an account and credentials.

Configuring the TwilioMessageSender

To use the out of box Twilio configuration, add the following configuration to your SpringBoot application that is running the NotificationService.

import org.springframework.context.annotation.*;
import com.broadleafcommerce.notification.service.*;
import com.broadleafcommerce.notification.service.integration.TwilioMessageSender;

@Configuration
public class MyNotificationConfiguration {

    // Step 1: Configure a TwilioMessageSender
    @Bean
    TwilioMessageSender twilioMessageSender() {
        // Obtain an credentials and authorized sender mobile from Twilio
        String accountSID = "TwilioAccountSID"; // This is usually the username
        String authToken = "TwilioAuthToken";
        String mobileNumber = "1-555-555-1234";

        TwilioRestClient client = new TwilioRestClient.Builder(accountSID, authToken).build();
        TwilioMessageSender = new TwilioMessageSender(client);
        sender.setDefaultSenderMobile(mobileNumber);
        return sender;
    }

    // Step 2: Register a SMS handler with the NotificationService
    @Bean
    NotificationHandler smsNotificationHandler(ThymeleafMessageBuilder builder,
            TwilioMessageSender sender) {
        return new DefaultNotificationHandler(builder, sender);
    }
}

About the example

The example above uses the ThymeleafMessageBuilder. Thymeleaf can be used to provide templated messages. Alternatively, the MessageBuilder can be set to null and api callers can set the Notification.messageBody property.

To apply, the configuration must be component scanned by your application. A typical approach is to add the configurations to SpringBoot’s META-INF/spring.factories file.

Additional Twilio Notes

Broadleaf supports sending media along with the Twilio message. The Notification.smsMediaUrls property, can be used to attach images and other file types to the SMS message.

Additional Twilio features can be added via customization. See `TwilioMessageSender for the out of box implementation.