spits-online / laravel-bird-api
This package allows you to connect to Bird's API using Laravel
Requires
- php: ^8.1
- illuminate/contracts: ^10.0||^11.0||^12.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^2.9
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^9.0.0||^8.22.0
- pestphp/pest: ^2.34
- pestphp/pest-plugin-arch: ^2.7
- pestphp/pest-plugin-laravel: ^2.3
- phpstan/extension-installer: ^1.3
- phpstan/phpstan-deprecation-rules: ^1.1
This package is not auto-updated.
Last update: 2025-09-08 09:02:20 UTC
README
Bird.com API Support for Laravel
Overview
The Laravel Bird Package simplifies integrating the powerful MessageBird API into your Laravel applications. It provides a user-friendly way to manage contacts and send notifications via SMS, WhatsApp, email, and more. This package is designed to make communication between Laravel and Bird (AKA MessageBird) seamless and efficient.
Why This Package?
- Ease of Use: Straightforward methods to interact with Bird's API.
- Multi-Channel Support: Send notifications via SMS, WhatsApp, Email, Telegram, and more.
- Contact Management: Create, update, retrieve, or delete contacts in Bird directly from your application.
- Error Handling: Built-in exception classes for better debugging and recovery.
Installation
Prerequisites
Before installing this package, ensure your system meets the following requirements:
- PHP: Version
^8.3
- Laravel: Version
^10.0
,^11.0
,^12.0
- Bird Account
Step-by-Step Installation
- Add the package to your Laravel project using Composer:
composer require spits-online/laravel-bird-api
- Once installed, the package will automatically register the
BirdServiceProvider
using Laravel's package auto-discovery. - Run the following command to publish the package configuration:
php artisan vendor:publish --tag="bird-config"
This will create aconfig/bird.php
file in your application.
Configuration
The config/bird.php
file contains all configurable options, including:
- API Access Key: Set your Bird.com API access key via
BIRD_ACCESS_KEY
in the .env file. - Workspace ID: Define your workspace using the
BIRD_WORKSPACE_ID
environment variable. - Channel IDs: Specify channel IDs (e.g., SMS, WhatsApp, Email) for notifications in your .env file:
BIRD_ACCESS_KEY={your-bird-access-key} BIRD_SMS_CHANNEL_ID={your-sms-channel-id}
For detailed configuration options, refer to the comments within the config/bird.php file.
Usage
1. Contact Management
This package provides functionality for managing contacts via the Bird API. Below are the key actions you can perform with the ContactService
.
Retrieve Contacts
You can retrieve a list of contacts using the index()
method. This allows you to specify the number of contacts to retrieve and whether to reverse the order of the results.
To be able to retrieve the contacts, make sure you have specified your BIRD_WORKSPACE_ID
in you .env
file.
use Spits\Bird\Services\ContactService; $birdContacts = app(new ContactService())->index(limit: 20, reverse: true);
Parameters:
limit
: The number of contacts to retrieve (default is 10).reverse
: Set totrue
to retrieve contacts in reverse order.nextPageToken
: Use for pagination when retrieving the next set of results.
Retrieving a single contact
You can also retrieve a single contact using the show()
method. This allows you to get only one contact by specifying its id.
use Spits\Bird\Services\ContactService; $birdContact = app(new ContactService())->show('bird-contact-id-123');
Parameters:
contactId
: The id of the contact
Create or Update Contacts
You can create or update a contact by passing a Contact
object to the createOrUpdate()
method.
This method requires the contact's identifier (phone number or email address)
to determine whether to create a new contact or update an existing one.
use Spits\Bird\Models\Contact; use Spits\Bird\Enums\IdentifierKey; use Spits\Bird\Services\ContactService; $contact = (new Contact()) ->displayName('John Doe') ->phoneNumber('+12345678901') ->emailAddress('johndoe@mail.com'); $response = (new ContactService())->createOrUpdate($contact, IdentifierKey::PHONE_NUMBER);
Parameters:
Contact
: TheContact
object containing the contact information.IdentifierKey
: The identifier type used to identify the contact (eitherPHONE_NUMBER
orEMAIL_ADDRESS
).
Delete Contacts
To delete a contact, simply call the delete()
method with the contact's ID.
use Spits\Bird\Services\ContactService; $response = (new ContactService())->delete('contact-id-123'); if ($response === true) { // Successfully deleted the contact dd('Contact deleted successfully.'); } else { // Handle error dd($response); }
Parameters:
contactId
: The unique ID of the contact to be deleted.
Return Values:
- Returns
true
if the deletion was successful. - Returns an error response if the deletion failed.
Contact Model Overview
The Contact
model provides an easy-to-use interface for building
and manipulating contact records before sending them to the Bird API.
Example Contact Creation
use Spits\Bird\Models\Contact; $contact = (new Contact()) ->displayName('Jane Doe') ->phoneNumber('+98765432103') ->emailAddress('jane@example.com') ->attribute('company', 'Acme Corp'); // The contact can then be passed to the `ContactService` for API interaction
Contact Methods:
displayName(string $name)
: Sets the display name of the contact.phoneNumber(string $number)
: Sets the phone number of the contact.emailAddress(string $email)
: Sets the email address of the contact.attribute(string $attribute, mixed $value)
: Adds additional attributes to the contact.toArray()
: Converts the contact into an array for sending to Bird API.
Ensure to validate the phone number using the regex defined in the configuration
(bird.phone_number_regex
) before sending it to the API.
2. Sending Notifications
This package supports a variety of notification channels, including SMS, WhatsApp, email, and more. Below are the details on using the SMS channel for sending notifications, leveraging predefined templates, and handling advanced use cases.
Supported Notification Channels
Currently, we only support the SMS channel. This is not going to be the case soon though, as we are planning on adding support for WhatsApp, facebook and telegram notification channels.
Example: Sending SMS Notifications
The SMSChannel
allows you to send SMS notifications by leveraging Laravel notification system.
Make sure you are allowed to send SMS notifications using Bird.
You need to configure an SMS channel before you can send SMS notifications.
Notification Class Example
Define a custom notification class implementing the toSMS
method.
use Illuminate\Notifications\Notification;use Spits\Bird\Channels\SMSChannel;use Spits\Bird\Messages\SMSMessage; class OrderNotification extends Notification { public function via(): array { return [ SMSChannel::class ]; } public function toSMS($notifiable): SMSMessage { $contact = (new Contact()) ->displayName('Jane Doe') ->phoneNumber('+98765432103') ->emailAddress('jane@example.com') ->attribute('company', 'Acme Corp'); return (new SMSMessage()) ->text('Your order has been shipped!') ->toContact($contact); } }
Sending the Notification
You can send the notification using Laravel's Notification
facade or the notify
method.
config
In the bird.php
config file you'll see templates
array and in there the empty whatsapp
key.
Follow the example below to add the keys belonging to your template.
Recommended way is to place the keys in your .env
'whatsapp' => [ 'foo_template' => [ 'template_project_id' => `template_project_id`, 'template_version' => `template_version`, 'template_locale' => `template_locale`, ], ]
usage
To send a message through WhatsApp create you own Notification class.
That should then use our WhatsappMessage
class. Example below
Whatsapp messages either require template
or body
to be send.
The example below utilises our MessageTemplate
support class, which enforces certain attributes needed when using message templates.
When using the body
parameter refer to the Bird docs for the needed array keys
<?php namespace App\Notifications; use App\Support\MessageTemplate; use Boilerplate\Notifications\BaseNotification; use Carbon\Carbon; use Spits\Bird\Channels\WhatsappChannel; use Spits\Bird\Messages\WhatsappMessage; class WhatsappNotification extends BaseNotification { public function __construct() { $this->setChannels([ WhatsappChannel::class ]); } public function toWhatsapp($notifiable): WhatsappMessage { $message = new WhatsappMessage( receiver: $notifiable->phone_number, template: new MessageTemplate( projectId: config('bird.templates.whatsapp.foo_template.template_project_id') version: config('bird.templates.whatsapp.foo_template.template_version'), locale: config('bird.templates.whatsapp.foo_template.template_locale') variables: [ 'receiverFirstName' => $notifiable->first_name, 'senderFullName' => 'Foo bar', ]), ); return $message; } }
Then in your controller you can a message as following
public function sendWhatsappMessage(NotificationRequest $request) { //Make sure you send the correct contact identifiers // Default is phonenumbers for the WhatsappChannel $users = User::all(); try { Notification::send($users, new WhatsappNotification()); } catch (Exception $exception) { Log::info($exception->getMessage()); } } }
Advanced Usage
You can also override the MessageTemplate
class so you can set defaults for the constructor params
In the example below we gave default values for a Whatsapp Template.\
Simultaneously setting variables
as a required param.
These variables should correlate with the variables placed in the template created in your Bird environment
<?php namespace App\Support; use Spits\Bird\Support\MessageTemplate; class WhatsappOverrideTemplate extends MessageTemplate { public function __construct( array $variables, ?string $projectId = null, ?string $version = null, ?string $locale = null, ) { parent::__construct( projectId: $projectId ?? config('bird.templates.whatsapp.test_message.template_project_id'), version: $version ?? config('bird.templates.whatsapp.test_message.template_version'), locale: $locale ?? config('bird.templates.whatsapp.test_message.template_locale'), variables: $variables ); } }
Exception Handling
The package uses custom exceptions to handle errors:
InvalidParameterException
: Thrown when a parameter is invalid.ConnectionException
: Thrown when there is a connection error with the API.NotAnSmsMessageException
: Thrown when the provided message is not an instance ofSMSMessage
.NotificationNotSent
: Thrown when the notification could not be sent.
Make sure to catch these exceptions in your code to handle errors gracefully.
Contributing
Please submit issues and pull requests to the GitHub repository.
License
This package is open-sourced software licensed under the MIT license.
Contact
For any inquiries or support, please contact Spits.