Slack Laravel

broken image


Utilizes Laravel's notifications to provide logging to slack at various levels. Inspired by Log4j. cr0wst/laravel-slack-log. In this video you'll learn how to send Slack Notifications from your Laravel Application.

You can now send Slack notifications from Your Laravel application! The DreamFactory team has relied on the Laravel framework for more than five years now, starting with the initial release of our namesake API management platform having been built atop Laravel 5.0. In the years since, our reliance on the framework has only increased; in addition to the DreamFactory platform we've built three other fairly complicated applications, two of which are used for internal dashboard purposes and the third being the trial registration and account management site for Genie (https://genie.dreamfactory.com/), our hosted DreamFactory environment.

Search in our massive list of open source packages for Laravel & JavaScript.

Like many companies, we're also heavy Slack users, and rely on automated notifications from a variety of internal and third-party services. As it happens, integrating automated Slack notifications into a Laravel application is an extraordinarily simple process once you understand how the pieces go together. In this blog post I'll walk you through a real-world example explaining how this is accomplished.

Did you know you can generate a full-featured, documented, and secure REST API in minutes using DreamFactory? Sign up for our free 14 day hosted trial to learn how! Our guided tour will show you how to create an API using an example MySQL database provided to you as part of the trial!

Configuring Your Laravel Application (Before sending Slack Notifications)

Before you can start sending Slack notifications from your Laravel application we'll need to install the Slack notification channel package:

You'll also need to install the 'Incoming Webhooks' app in your Slack workspace. By doing so, you'll be able to generate a unique URL which will be used to send messages to a designated Slack channel.

After clicking the 'Add to Slack' button, you'll be taken to the following screen:

Here you're prompted to choose a channel where the incoming messages will be sent. As you can see in the screenshot, I've chosen a channel called #new-trials. If you haven't yet created the channel, clicking the create a new channel link will cause a modal to open where you can create the destination channel.

Finally, click the 'Add Incoming WebHooks Integration' button to generate the unique URL. Once you do, a confirmation notification stating 'added an integration to this channel: incoming-webhook' will immediately be sent to the designated Slack channel. Also, the ensuing screen will present your newly generated webhook URL. Copy this URL to the clipboard (it will begin with https://hooks.slack.com), open your Laravel application's .env file, and assign it to a configuration variable named something like SLACK_NOTIFICATION_WEBHOOK:

Generating the Slack Notification

Next we'll write the code used to send Slack notifications. Fortunately, most of this work is boilerplate, beginning with generation of the notification class which defines the message:

This will generate a boilerplate notification class geared towards e-mail. You'll find the class in your project's app/Notifications directory. We'll need to make a few modifications to this class in order to support Slack, beginning with referencing the SlackMessage class at the top of the file:

Next, change the via method to look like this:

Finally, delete the toMail and toArray methods, and in their place add the following toSlack method:

When finished, the class will look like this:

Firing the Slack Notification

We've generated the Slack notification, however haven't yet tied the notification into our application logic. There are two ways to do this:

  • Notification Trait: You'll use the notification trait when you want to send a notification in conjunction an event associated with a specific model instance, such as a trial or product.
  • Notification Facade: You'll use the notification facade when you want to send multiple notifications associated with a collection, such as multiple trials or products.

For this post we'll focus on the notification trait. Suppose you want to send a Slack notification whenever a new trial is created. A model named Trial houses the application's trial-related logic. Open the Trial model and add a reference to the Notifiable class:

Next add a reference to the Notifiable trait at the top of the class:

Finally, add a new method named routeNotificationForSlack which returns the webhook URL:

You can test the notification by firing up Tinker:

Check your Slack channel and you should see a notification like that presented in the below screenshot:

While this notification confirms a successful integration, it isn't exactly useful. Fortunately we can make some pretty simple modifications to the NewTrial notification class' toSlack method to add some more context:

After making these changes, reload Tinker:

This time, you'll see a Slack notification stating 'Jason Gilmore created a new trial'. We can go even further though! Using a message attachment, we can add even more context:

Return to Tinker one more time to test the results:

In a moment you should see a message similar to the following show up in Slack:

Moving Notification Logic Into Your Application

Of course, in production you won't be executing notifications from Tinker. An ideal location would likely be a trial controller's store method, because that's where data associated with a new trial would be persisted to the database. That store method might look something like this:

Did you know you can generate a full-featured, documented, and secure REST API in minutes using DreamFactory? Sign up for our free 14 day hosted trial to learn how! Our guided tour will show you how to create an API using an example MySQL database provided to you as part of the trial!

Other Useful Laravel Notification Packages

Slack is just one of many available Laravel notification packages. In addition to the notification options described in the Laravel documentation, at the time of this writing there were an additional 52 channels maintained by the Laravel community, including Twitter, Facebook, Twilio, and Microsoft Teams, among others. Head over to the aptly named Laravel Notification Channels website for a complete list.

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

  • PHP environment
  • Composer globally installed

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:

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' totoggle 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:

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:

Update Environment File with Webhook

Open the .env file and add the following code:

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:

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

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:

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

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:

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.

Slack Laravel

Add Twilio Webhook Code

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

Add The Twilio Endpoint

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

Slack Laravel Notification

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:

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.

Slack Laravel

Add Twilio Webhook Code

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

Add The Twilio Endpoint

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

Slack Laravel Notification

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:

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

Slack Laravel

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.

Laravel Slack Integration

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





broken image