Integrating Slack With Laravel App

Integrating Slack With Laravel App

A step-by-step guide to integrating Slack to your Laravel applications

In this article, we will learn how to integrate Slack with your Laravel App. This step-by-step guide is split into two parts. In the first part, we shall discuss how to setup an app in the Slack API console, while we shall discuss how to implement the Slack feature to your Laravel app in the second. After following this guide, you will be able to launch Slack on your Laravel application, as well as send notifications.

Let us get started!

Part 1: Setting-up an app in the Slack API console

Login to this link to get started. Initially, we need to create an app/bot which will help us to send the slack notifications.

Follow the steps given below to set-up your app.

Step 1:

Select the option to set up an app from scratch as referenced in the image given below:

Screenshot 2022-04-03 at 12.24.32 PM.png

Step 2:

Once the app is created, we need to go to the Features segment, click on the Functionality option and then select the Bots option given there. Refer to the image given below for clarity:

Screenshot 2022-04-03 at 12.26.41 PM.png

Step 3:

After following the previous step, we will get an option to review scopes and add options, we need to select that as shown below:

Screenshot 2022-04-03 at 12.27.30 PM.png

Step 4:

In this step, we need to add the token scope for the bot as shown below:

Screenshot 2022-04-03 at 12.27.44 PM.png

Step 5:

We can add multiple OAuth Scope options as per our requirements but we need to make sure to add the below scope so that the bot can send the message when it is triggered:

Screenshot 2022-04-03 at 12.28.24 PM.png

Step 6:

Once the scopes have been established, install the app in your workspace. Here, we will get an OAuth token which will be used to send the notification.

Screenshot 2022-04-03 at 12.29.26 PM.png

Part 2: Implement the Slack app to the Laravel App

Step 1:

Let’s create the feature for two jobs to begin with; one to post messages to the channel and one to post messages to the user. Let’s name it PostMessageUserJob and PostMessageChannelJob and enable both will accept three parameters: First UserId or ChannelId, the second message to be sent and the third attachment(or null). Enter the code snippet given below:

dispatch(new PostMessageUserJob("XXXXXXXXXXX","Hello Slack!",null));

Once you have followed the previous step, code the following:

dispatch(new PostMessageChannelJob("XXXXXXXXXXX","Hello Slack!",null));

Step 2:

Let’s make a service class which will be used to send messages in the Slack app. After this, we will call the service class function postMessageToUser and postMessageToChannel to send the message to the user and the channel respectively. The below code can used to send the message to the user:

   public static function postMessageToUser($userId,$message, $data = null)
   {
       $blocks = NULL;
       $attachments = NULL;
       $result = ['status' => false, 'error_code' => '', 'message' => ''];

       if(!empty($data['blocks'])) {
           $blocks = $data['blocks'];
       }else {
           $attachments = $data;
    }

       if (!empty($userId)) {
           try
           {
               if ($attachments != null) {
                   $attachments = json_encode($attachments);
               }

               $responseText = null;

               $client = new Client(['base_uri' => “https://slack.com/api/”]);
               $response = $client->request("POST", "chat.postMessage", [
                   'form_params' => [
                       'token' => BOT_TOKEN_GENERATED,
                       'channel' => '@' . $userId,
                       'text' => $message,
                       'attachments' => $attachments,
                       'blocks' => $blocks,
                       'as_user' => true,
                   ],
               ]);

               $responseText = json_decode($response->getBody());
               \Log::info($response->getBody());              
           } catch (Exception $e) {
        \Log::info($e->getMessage());
           }
       } else {
           \Log::info(“User Not Found!”);
       }
       $result['status'] = true;
       return $result;
   }

The code given below can alternatively be used to send messages to the channel:


public static function postMessageToChannel($channelId,$message,$data = null)
   {
       $blocks = NULL;
       $attachments = NULL;

       if(!empty($data['blocks'])) {
           $blocks = $data['blocks'];
       }else
           $attachments = $data;

       $result = ['status' => false, 'error_code' => '', 'message' => ''];
       try
       {          
           $client = new Client(['base_uri' => “https://slack.com/api/”]);
           $response = $client->request("POST", "chat.postMessage", [
               'form_params' => [
                   'token' => BOT_TOKEN_GENERATED,
                   'channel' => $channelId,
                   'text' => $message,
                   'link_names' => $linkNames,
                   'attachments' => $attachments,
                   'blocks' => $blocks,
               ],
           ]);
           $responseText = json_decode($response->getBody());
       } catch (Exception $e) {
        \Log::info($e->getMessage());       
       }
       $result['status'] = true;
       return $result;
   }
Step 3:

Once we have the Job option ready, we can directly include it anywhere in the controller and a message will be sent to Slack. We can include the same in the Listeners section too, so that a notification can be triggered whenever an event occurs.

Conclusion

After following all the steps given in this guide, you will successfully be able to integrate Slack to your Laravel app. This brings to you a lot of advantages, one of which being that you can trigger notifications directly from the Laravel application itself.

I hope you guys have enjoyed my article about Slack integration with Laravel. I have more articles coming your way about coding on Laravel. Hope to see you in the other instalments.