emanate / beem
Laravel package for the Beem Africa SMS, Two-Way SMS, OTP and Multicountry SMS APIs
Requires
- php: ^8.2
- ext-curl: *
- ext-mbstring: *
- guzzlehttp/guzzle: ^7.8|^8.0
- illuminate/support: ^12.0|^13.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.18
- nunomaduro/collision: ^8.6
- orchestra/testbench: ^10.0|^11.0
- phpunit/phpunit: ^11.5|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Beem Africa SMS for Laravel
A Laravel package for the Beem Africa messaging APIs. It covers:
- SMS: send to one or many recipients, schedule, unicode, delivery reports, balance, sender names and templates
- Two-Way SMS: receive inbound messages as Laravel events
- OTP: request and verify one-time PINs
- Multicountry SMS: send international SMS, and receive inbound messages and delivery reports as Laravel events
This is a community package. It is not affiliated with Beem Africa.
Contents
- Requirements
- Installation
- Configuration
- SMS
- Two-Way SMS
- OTP
- Multicountry SMS
- Phone number validation
- Testing
Requirements
- PHP 8.2 or later
- Laravel 12 or 13
- A Beem account with API credentials
Installation
composer require emanate/beem
Publish the config file:
php artisan vendor:publish --tag="beem"
When upgrading, compare your published
config/beem.phpwith the package's copy. New options are added over time.
Configuration
Every option can be set from .env. Only the first three are needed to send SMS:
# SMS API: Beem dashboard > SMS > API Setup BEEM_SMS_API_KEY=your-api-key BEEM_SMS_SECRET_KEY=your-secret-key BEEM_SMS_SENDER_NAME=INFO # Optional: authenticate with an access token instead of the key and secret BEEM_ACCESS_TOKEN= # Optional: message encoding, TLS verification and timeout BEEM_SMS_ENCODING=0 BEEM_SMS_VERIFY_SSL=true BEEM_SMS_TIMEOUT=30 # Optional: endpoint overrides, for example staging (https://dev-sms.beem.africa/v1) BEEM_SMS_SENDING_URL=https://apisms.beem.africa/v1 BEEM_SMS_PUBLIC_API_URL=https://apisms.beem.africa/public/v1 BEEM_SMS_DELIVERY_REPORTS_URL=https://dlrapi.beem.africa/public/v1 # Two-Way SMS BEEM_TWO_WAY_ENABLED=false BEEM_TWO_WAY_PATH=beem/inbound BEEM_TWO_WAY_TOKEN= # OTP (staging: https://dev-otp.beem.africa/v1) BEEM_OTP_APP_ID= BEEM_OTP_URL=https://apiotp.beem.africa/v1 # Multicountry SMS BEEM_MULTICOUNTRY_USERNAME= BEEM_MULTICOUNTRY_PASSWORD= BEEM_MULTICOUNTRY_SOURCE_ADDRESS= BEEM_MULTICOUNTRY_CALLBACK_ENABLED=false BEEM_MULTICOUNTRY_CALLBACK_PATH=beem/multicountry BEEM_MULTICOUNTRY_CALLBACK_TOKEN=
See config/beem.php for the full list, with comments.
Authentication
By default every request uses HTTP Basic auth, with your API key as the username and your secret as the password.
Beem also accepts an access token, sent in the Authorization header without a Bearer prefix. Set BEEM_ACCESS_TOKEN and the token replaces the key and secret everywhere. The key and secret can then be left empty.
You can also set credentials at runtime:
BeemSms::accessToken('your-access-token')->content('Hello')->getRecipients(['255700000000'])->send(); BeemSms::apiKey('other-key')->secretKey('other-secret')->content('Hello')->getRecipients(['255700000000'])->send();
Call withoutAccessToken() to fall back to key and secret auth for a single call.
SMS
Sending
Use the facade or the beem() helper:
use Emanate\BeemSms\Facades\BeemSms; BeemSms::content('Your message here')->loadRecipients(User::all())->send(); beem()->content('Your message here')->loadRecipients(User::all())->send();
There are three ways to add recipients:
// A collection of models. The phone column defaults to 'phone_number'. BeemSms::content('Hello')->loadRecipients(User::all(), 'mobile')->send(); // An array BeemSms::content('Hello')->getRecipients(['255700000000', '255711111111'])->send(); // Variadic arguments BeemSms::content('Hello')->unpackRecipients('255700000000', '255711111111')->send();
Numbers are in international format without the +, for example 255700000000.
Message options
BeemSms::content('Ujumbe wako hapa 😀') ->getRecipients(['255700000000']) ->senderName('SHOP') // registered, active sender ID, max 11 characters ->unicode() // for characters outside the GSM alphabet ->scheduleTime(now()->addHours(2)) // or a 'Y-m-d H:i' string in GMT+0 ->jobName('welcome-sms') // dashboard tracking ->campaignTitle('January onboarding') // dashboard tracking ->send();
scheduleTime()converts anyDateTimeInterfaceto UTC for you.encoding(BeemSms::ENCODING_UNICODE)sets the raw encoding value. The default comes from theencodingconfig option.
Reading the response
send() returns the raw PSR-7 response. sendAndParse() returns the decoded body, and throws when Beem answers with an error code:
use Emanate\BeemSms\Exceptions\BeemApiException; try { $response = BeemSms::content('Hello')->getRecipients(['255700000000'])->sendAndParse(); // $response['request_id'], $response['valid'], $response['invalid'], $response['duplicates'], ... } catch (BeemApiException $e) { // $e->getCode() is Beem's response code, for example 102 for insufficient balance report($e->description()); }
Delivery reports
Beem does not push delivery reports for local SMS. You poll for them using the request_id returned by a send. Wait at least five minutes after sending, so the mobile operator has time to report back:
$report = BeemSms::deliveryReport('255700000000', $response['request_id']); // [['dest_addr' => '255700000000', 'status' => 'DELIVERED', 'request_id' => '31951']]
status is one of PENDING, DELIVERED or UNDELIVERED.
Balance
BeemSms::balance();
Sender names
BeemSms::senderNames(); BeemSms::senderNames(['page' => 1, 'limit' => 20, 'status' => 'active', 'q' => 'SHOP']);
Supported filters: page, limit, sortBy, sortOrder, q, status. Sender IDs are registered in the Beem dashboard; the API only lists them.
Templates
BeemSms::templates(['page' => 1, 'limit' => 20]); $template = BeemSms::createTemplate('Welcome', 'Welcome to our service!'); BeemSms::updateTemplate($template['data']['id'], 'Welcome', 'Welcome aboard!'); BeemSms::deleteTemplate($template['data']['id']);
Error handling
Every method that returns a decoded array throws Emanate\BeemSms\Exceptions\BeemApiException when Beem answers with an error. That covers balance, deliveryReport, senderNames, the template methods and sendAndParse. The exception code is Beem's response code, and BeemApiException::RESPONSE_CODES maps every documented code to its meaning.
Two-Way SMS
Beem POSTs mobile-originated messages to a callback URL that you register on your Two-Way number in the Beem dashboard. Enable the route:
BEEM_TWO_WAY_ENABLED=true BEEM_TWO_WAY_PATH=beem/inbound BEEM_TWO_WAY_TOKEN=a-long-random-string
Register this URL with Beem:
https://your-app.com/beem/inbound?token=a-long-random-string
Then listen for the event:
use Emanate\BeemSms\Events\InboundSmsReceived; class HandleInboundSms { public function handle(InboundSmsReceived $event): void { $message = $event->message; $message->from(); // '255701000000' $message->to(); // your short code or long number $message->text(); // 'STOP please' $message->keyword(); // 'STOP' $message->transactionId(); // use this to stay idempotent $message->timeUtc(); $message->channel(); // 'sms' $message->custom(); // [] $message->currency(); // 'TZS' $message->subscriberPrice(); // '100.00' $message->billingPrice(); // '100.00' $message->toArray(); // the raw payload } }
The route answers with the acknowledgement Beem expects, {"transaction_id": "...", "successful": true}, as soon as the event is dispatched. Do slow work in a queued listener. Beem may retry, so use transactionId() to skip messages you have already processed.
Securing the callback
Every callback is authenticated before the payload is read. Beem's docs do not say which credentials, if any, it sends with the callback, so several are accepted:
?token=on the callback URL, or anAuthorizationheader, equal toBEEM_TWO_WAY_TOKEN(recommended)- an
Authorizationheader equal to youraccess_token - HTTP Basic auth carrying your API key and secret
Comparisons are constant-time, and a Bearer or Token prefix is tolerated. Unauthenticated requests get a 401 and dispatch no event. Your API secret and access token are never accepted in the query string, so they cannot leak into access logs.
If you authenticate the callback elsewhere, for example at an API gateway, set two_way.verify_credentials to false. Leave it on otherwise. With it off, anyone who learns the URL can inject fake messages.
Extra middleware for the route goes in two_way.middleware. The credential check always applies on top.
OTP
The OTP API uses your SMS API key and secret, but runs on its own host. Create an OTP application in the Beem dashboard and set its ID:
BEEM_OTP_APP_ID=1234
use Emanate\BeemSms\Facades\Otp; $response = Otp::request('255700000000'); $pinId = $response['data']['pinId']; // $response['data']['pinExpiryTimeInMinutes'], $response['data']['expiresInSeconds'] Otp::verify($pinId, '1234');
verify() throws Emanate\BeemSms\Exceptions\OtpException when the PIN is wrong, expired, already used, or out of attempts. Use check() if you want a boolean instead:
if (Otp::check($pinId, $request->input('pin'))) { // verified }
OtpException::RESPONSE_CODES maps codes 100–118 to their meanings. The app ID and credentials can be set per call:
Otp::appId(4321)->accessToken('your-access-token')->request('255700000000');
The channel, SMS or WhatsApp, is set on the OTP application in the dashboard.
Request field names. Beem's OTP reference documents the responses and codes, but not the request body. This package sends
appIdandmsisdnto request a PIN, andpinIdandpinto verify one. If Beem expects something else, add any field withparameter():Otp::parameter('channel', 'whatsapp')->request('255700000000');
Multicountry SMS
Multicountry SMS is a separate Beem platform. It has its own host, authenticates with a username and password, and takes uppercase form parameters.
BEEM_MULTICOUNTRY_USERNAME=your-username BEEM_MULTICOUNTRY_PASSWORD=your-password BEEM_MULTICOUNTRY_SOURCE_ADDRESS=MyApp
use Emanate\BeemSms\Facades\MulticountrySms; MulticountrySms::from('MyApp')->to('255650000001')->content('Hello World')->send(); beem_multicountry()->to('255650000001')->content('Hello World')->send();
The platform takes one destination per request. Loop to send to many.
- Alphanumeric senders are limited to 11 GSM characters, and
SOURCEADDRTON=5is set for you. - A leading
+is stripped from the destination. - Unicode is detected by the platform, so no flag is needed.
Binary, UDH and concatenation
MulticountrySms::from('MyApp') ->to('255650000001') ->content('414243') // hex body ->binary() ->userDataHeader('0605040B8423F0') ->ports(9200, 2948) ->concatenated(reference: 42, sequence: 1, total: 3) ->validityPeriod(3600) ->send();
Any other platform parameter can be set directly. The name is uppercased for you:
MulticountrySms::to('255650000001')->content('Hi')->parameter('SOURCEADDRNPI', 1)->send();
Inbound messages and delivery reports
The platform POSTs inbound messages and delivery reports to one callback URL, as form fields. The platform sends no credentials, so the package protects the route with a secret token in the URL. Enable the route:
BEEM_MULTICOUNTRY_CALLBACK_ENABLED=true BEEM_MULTICOUNTRY_CALLBACK_PATH=beem/multicountry BEEM_MULTICOUNTRY_CALLBACK_TOKEN=a-long-random-string
Your callback URL is:
https://your-app.com/beem/multicountry?token=a-long-random-string
- Inbound messages: Beem support registers the callback URL on your account. Email support@beem.africa with it.
- Delivery reports: request them per message:
MulticountrySms::to('255650000001') ->content('Hello World') ->deliveryReport(route('beem.multicountry.callback', ['token' => config('beem.multicountry.callback.token')])) ->send();
Listen for the events. An inbound message listener:
use Emanate\BeemSms\Events\MulticountryInboundSmsReceived; public function handle(MulticountryInboundSmsReceived $event): void { $event->message->from(); // SOURCEADDR $event->message->to(); // DESTADDR, your short code or long number $event->message->text(); // MESSAGE $event->message->keyword(); // KEYWORD, or the first word of the message $event->message->id(); // ID of the message being replied to, if any }
A delivery report listener:
use Emanate\BeemSms\Events\MulticountryDeliveryReportReceived; public function handle(MulticountryDeliveryReportReceived $event): void { $report = $event->report; $report->messageId(); // the msgid returned when you sent the message $report->to(); // DESTADDR $report->status(); // 1–11, see MulticountryDeliveryReport::STATUS_* $report->statusText(); // 'Delivered', 'Failed', 'Expired', ... $report->isDelivered(); $report->isUndeliverable(); // failed, deleted, expired, rejected or canceled $report->isFinal(); }
A request carrying a STATUS field is treated as a delivery report. Anything else is treated as an inbound message. The route answers with the empty HTTP 200 the platform expects. Requests with a missing or wrong token get a 401. If no token is configured, every request gets a 401, so the route is never left open by accident. Set multicountry.callback.verify_token to false only if you authenticate the route some other way.
Balance
MulticountrySms::balance(); // ['account' => 'test', 'balance' => '1234.567']
Error handling
The platform answers HTTP 200 even when a send fails. send() checks the status in the body and throws Emanate\BeemSms\Exceptions\MulticountrySmsException for any non-zero status. The exception code is the platform status, and MulticountrySmsException::STATUS_CODES maps every documented code to its meaning.
Phone number validation
If a number is not in a format Beem accepts, the whole send fails. With validate_phone_addresses set to true (the default), numbers are checked before sending and an exception is thrown for invalid ones.
To use your own rules, point validator_class in the config at a class that implements Emanate\BeemSms\Contracts\Validator.
Testing
composer test
Changelog
See CHANGELOG.
Contributing
Issues and pull requests are welcome at wao1ook/beem. Please run composer test and composer pint before opening a pull request.
Security vulnerabilities
Please review our security policy to report a vulnerability.
Credits
License
The MIT License (MIT). See License File for details.