DEV Community

Rezaul H Reza
Rezaul H Reza

Posted on

MessageBird Integration with Laravel

Welcome to our tutorial on integrating MessageBird with Laravel!

In this tutorial, we will show you how to install the laravel-notification-channels/messagebird package and set up your environment variables. We will also demonstrate how to test the integration using the PHPUnit framework.

Before we begin, it's important to note that you will need to have an account with MessageBird in order to use their SMS service. If you don't already have an account, you can Sign Up for one at their website.

Now, let's get started.

Installing the Package

The first step in integrating MessageBird with Laravel is to install the laravel-notification-channels/messagebird package. This package provides a MessageBird channel for Laravel's notification system, allowing you to send SMS messages through MessageBird from your Laravel application.

To install the package:

composer require laravel-notification-channels/messagebird

Setting Up Your Environment Variables

Next, you'll need to set up your environment variables. The laravel-notification-channels/messagebird package requires several environment variables in order to connect to the MessageBird API.

First, you'll need to add your MessageBird API key to the .envfile. You can find your API key in the MessageBird dashboard under "API Access (REST)".

MESSAGEBIRD_API_KEY=your-api-key-here

The final version of .env variables should look like this:

rest of the env variables.....

Messagebird

MESSAGEBIRD_ACCESS_KEY=api_key
MESSAGEBIRD_ORIGINATOR=NameOrNumberMessageWillBeSentFrom
MESSAGEBIRD_TEST_RECIPIENT=

In our services.php:

<?php


return [

//..........


'messagebird' => [
        'access_key' => env('MESSAGEBIRD_ACCESS_KEY'),
        'originator' => env('MESSAGEBIRD_ORIGINATOR'),
    ],


];
Enter fullscreen mode Exit fullscreen mode

Implementing and Testing the Integration

Now that you have the laravel-notification-channels/messagebird package installed and your environment variables set up, it's time to implement and test the integration.

Create a notification using

php artisan make:notification MessageCreated

This will now create a new notification class in the app/notifications directory.

The beauty of laravel notifications classes are it’s very easy to send notifications.

The new notification class should look like this.

<?php

namespace App\Notifications\Customers;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use NotificationChannels\Messagebird\MessagebirdChannel;
use NotificationChannels\Messagebird\MessagebirdMessage;

class MessageCreated extends Notification implements ShouldQueue
{
    use Queueable;

    public function via($notifiable)
    {
        return [MessagebirdChannel::class];
    }

    public function toMessagebird($notifiable)
    {
        $message = new MessagebirdMessage("Message Sent!");

        if (app()->environment('local', 'testing')) {
            $message->setRecipients([env('MESSAGEBIRD_TEST_RECIPIENT')]);
        }

        return $message;
    }
}
Enter fullscreen mode Exit fullscreen mode

Time to start integrating them in our application!

For the sake of this example, we are using Livewire.

We will create a component called TestComponent.
`
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Notification;//illuminate/facade
use App\Models\Order;
use App\Notifications\MessageCreated;

class TestComponent extends Component
{

public $order;

public $orderId;

public $name;

public $qty;

public $note;

public $phoneNumber;


public function store()
{

    $this->order = Order::updateOrCreate(['id' => $this->orderId], [
        'name' => $this->name,
        'qty' => $this->qty
        'note' => $this->note ?? '',
        'user_id' =>  auth()->user()->id,

    ]);

    // Notify the user
    $phone = optional($this->phoneNumber ?? '';//phone number must be in international format e.g +4478.....
    if ($phone) {
Enter fullscreen mode Exit fullscreen mode

//this line is responsible to send notification when this method is called.
Notification::route('messagebird', $phone)->notify(new MessageCreated);
}

}


public function render()
{

    return view('livewire.test-component');
}
Enter fullscreen mode Exit fullscreen mode

}
`

Let’s update our view file.

<div>
<div class="flex flex-col">
    <label class="block font-bold mb-2 text-gray-700" for="name">
        Name
    </label>
    <input 
        class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" 
        id="name"
        wire:model="name"
        type="text" 
        placeholder="Enter your name"
    >
    <label class="block font-bold mb-2 text-gray-700" for="qty">
        Quantity
    </label>
    <input 
        class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" 
        id="qty"
        wire:model="qty"
        type="number" 
        placeholder="Enter the quantity"
    >
    <label class="block font-bold mb-2 text-gray-700" for="note">
        Note
    </label>
    <textarea
        class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" 
        id="note"
        wire:model="note"
        placeholder="Enter a note"
    ></textarea>
    <label class="block font-bold mb-2 text-gray-700" for="phoneNumber">
        Phone number
    </label>
    <input
        class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" 
        id="phoneNumber"
        wire:model="phoneNumber"
        type="tel"
        placeholder="Enter your phone number"
    >
    <button
        class="bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
        wire:click="store"
    >
        Submit
    </button>
</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Now that we have created the component, it’s time to test the integration.

To do this, we'll use the PHPUnit.

First, add the following line to your phpunit.xml file:

<envname="MESSAGEBIRD_TEST_RECIPIENT"value="+447000000000" />

This will define a test recipient phone number that you can use in your tests. The reason we are including it here because we don’t want our production data to be in the test file.

Next, in your test file, make sure to use the Notification::fake() method at the top of your test or in the setup method. This will prevent any real SMS messages from being sent during your tests.

protected function setUp(): void
{
parent::setUp();
// Make sure we don't send real SMS texts
Notification::fake();
}

After performing the action that should trigger an SMS message, you can use the Notification::assertSentTo() method to perform an assertion. This method takes three arguments: the notifiable entity, the notification class, and a callback function that should return true if the assertion should pass.

Here's an example of how you might use this method in a test:

function test_order_notification_is_sent()
 {

   protected function setUp(): void
 {
     parent::setUp();

     // Make sure we don’t send real SMS texts
     Notification::fake();
 }

     Livewire::actingAs($user)
         ->test(TestComponent::class)

         ->set(‘property ’, ‘property value)

         ->call(‘method’);//method to call i.e ‘submit’

     Notification::assertSentTo(
         new AnonymousNotifiable(),
         MessageCreated::class,
         function ($notification, $channels, $notifiable) {
             return $notifiable->routes[‘messagebird’] === ‘+447000000000’;
         }
     );
 }
Enter fullscreen mode Exit fullscreen mode

Also, we need to change our AppServiceProvider. The integration will not work if guzzlecannot verify the

<?php

namespace App\Providers;

use GuzzleHttp\Client;
use NotificationChannels\Messagebird\MessagebirdClient;
use NotificationChannels\Messagebird\MessagebirdChannel;
use NotificationChannels\Messagebird\Exceptions\InvalidConfiguration;



public function boot()
{
          // Override Messagebird service provider to instruct Guzzle not to verify their API SSL certificate
        $this->app->when(MessagebirdChannel::class)
            ->needs(MessagebirdClient::class)
           ->give(function () {
                $config = config('services.messagebird');

                if (is_null($config)) {
                    throw InvalidConfiguration::configurationNotSet();
               }

                return new MessagebirdClient(new Client(['verify' => false]), $config['access_key']);
                });
}
Enter fullscreen mode Exit fullscreen mode

Run the test and it should pass.
phpunit

That's it! You should now have a working integration between MessageBird and Laravel, and you can send message to your customers or users very easily.

If you have any questions or need further assistance, you can refer to the documentation for the laravel-notification-channels/messagebird package or the MessageBird documentation. You are also welcomed to leave a comment if you have any queries regarding the integration.

I also post awesome free and premium components and articles on my website. You can find some amazing content there.

Thanks

Top comments (0)