Create an Incoming Webhook to Forward SMS to Slack with Laravel

December 19, 2018
Written by
Michael Jaroya
Contributor
Opinions expressed by Twilio contributors are their own

forward-twilio-sms-to-slack-cover-photo.png

Introduction

As a business entity, you will always get SMS from customers seeking support, giving you feedback, filing complaints or even sending compliments. Because notifications can become overwhelming, it helps to consolidate all the SMS in one central place for easier reference.

In this tutorial, we will automatically forward SMS sent to a Twilio number to a slack channel using a webhook implemented in Laravel.

Requirements

Set Up a New Laravel Project

If you don't have one already set up, we’ll need to install a fresh Laravel application. A guide on how to set up Laravel can be found in the official Laravel documentation.

We also need to install the Twilio SDK for PHP in our project. In your terminal, navigate to the project directory and run the following command:

$ composer require twilio/sdk

Getting started with Slack Incoming Webhooks

Incoming webhooks enable you to share information from external sources with your slack workspace.

Create a Slack App

Log in to your Slack account and navigate to the create Slack app page. Enter the name of choice, choose a workspace and click Create App.

Enable the Slack Incoming Webhook

After creating the Slack app, you will be redirected to the settings page for the new app. On the page, select “Incoming Webhooks and click “Activate Incoming Webhooks” to toggle and turn on the feature.

Create an Incoming Slack Webhook

After you enable the incoming webhook, the page should refresh and extra options will appear. Click “Add New Webhook to Workspace” button. Select a channel that the app will post to, and then click Authorize to authorize your app.

You’ll be redirected back to the app settings page which should now have a new entry under the “Webhook URLs for Your Workspace with a webhook URL. The webhook URL should look something similar to this:

https://hooks.slack.com/services/T000000000/XXXXXXXXXXX

You now have a new incoming webhook. Let's see how we can use it to post a message to our channel using the Laravel application we set up earlier.

Use Your Incoming Webhook to Post a Message

Require Guzzle dependency

We will use Guzzle to post the message from the application to the webhook. To install Guzzle, navigate to the project directory and run the following command:

$ composer require guzzlehttp/guzzle:~6.0

Update Environment File with Webhook

Open the .env file and add the following code:

SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T000000000/XXXXXXXXXXX

The URL used here should be the one we generated earlier in the app settings page.

The Webhook Model

The next step is to create a model we’ll use to prepare the message that will be sent to our slack webhook. By default, models are found in the app folder. Run the following command to create Webhook model:

$ php artisan make:model Webhook

Open the file app/Webhook.php and add the following code:

<?php

use GuzzleHttp\Client;

class Webhook extends Model
{
    /**
     * post message to slack webhook
     *
     * @param $message
     *
     * @return mixed
     */
    public function postMessage( $message ) {
        
        $client = new Client([
            'headers' => [ 'Content-Type' => 'application/json' ]
        ]);

        $response = $client->post( env( 'SLACK_WEBHOOK_URL' ),
            ['body' => $message]
        );

        $data = json_decode( $response->getBody()->getContents() );

        return $data;
    }
}

 

 

The Webhook Controller

To handle the user inputs and update the model accordingly, we need a controller. By default, controllers are found in app/Http/Controllers. Run the following command in the project directory to create WebhookController:

$ php artisan make:controller WebhookController

Open the file app/Http/Controllers/WebhookController.php and add the following code:

<?php

use App\Webhook;

class WebhookController extends Controller
{
    /**
    * post message to the slack channel
    */
    public function index(){

        $message = "How do I make a comment on the blog?";
        $webhook = new Webhook();
        $data = json_encode( [ 'text' => $message ] );
        echo $webhook->postMessage( $data) ;
    }
}

Create The Endpoint

The final step at this stage is to create a route; an endpoint we’ll hit to send the message to slack. Inside routes/web.php, add this line of code:

<?php
Route::get( '/webhook', 'WebhookController@index' );

This is a get method and we can access it through the URL http://localhost:8000/webhook

You should be able to see this message in your Slack channel when you hit the endpoint.

We have established that our Slack incoming webhook is working. The next step is to integrate the Twilio SMS webhook.

Create the Incoming Twilio Message Webhook

We need an endpoint that will handle the SMS forwarded from the Twilio phone number and send the SMS to the incoming webhook we have created in Slack.

Create Temporary Public URL

To test locally, we need DNS software like ngrok that assigns a local port a publicly accessible URL over the Internet. Once ngrok is set up, run the command below to expose our local web server running on port 8000 to the Internet.

$ /.ngrok http 8000

Add Twilio Webhook Code

In the Controller, app/Http/Controllers/WebhookController.php add the following code:

<?php

use Twilio\Twiml;

/**
 * The slack webhook
 *
 * @return $this
 */
public function forward(){

    $sms_body = $_REQUEST['Body'];
    $from     = $_REQUEST['From'];
    $full     = "From: ".$from." SMS: ".$sms_body;
    $webhook  = new Webhook();
    $data     = json_encode(['text'=>$full]);
       
    $webhook->postMessage( $data );
       
    $response = new Twiml;
    $response->message( $full );
       
    return response( $response, 200 )->header( 'Content-Type', 'application/xml' );
}

Add The Twilio Endpoint

Update the routes file routes/web.php and add this line of code:

<?php
Route::post( '/forward', 'WebhookController@forward' );

Disable CSRF verification

To be able to receive posted data from external source, we need to exclude our webhook from CSRFverification. Inside app/Http/Middleware/VerifyCsrfToken.php, add the following code:

<?php

/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
    'forward',
];

Configure a Phone Number to Reply to Incoming Messages with a webhook

  1. Login into your Twilio account and go to the console numbers page.
  2. Click the plus button to purchase a phone number if you don't already have one.
  3. Click the phone you want to use. You will be redirected to a new page.
  4. Inside of the message section “A MESSAGE COMES IN”, select option, choose “WEBHOOK” and paste the URL to the webhook we created earlier.


Testing a webhook

Finally, Let’s test the completed code. Send an SMS to the Twilio phone number we have just configured above.



You will immediately see the message pop up in the Slack channel as shown below.

Conclusion

You can now make awesome apps to take advantage of the awesome features in both Slack and Twilio. If you can picture it, then you can implement it.

The complete code for the tutorial can be found on Github.