Search by

gp10devhts / laravel-ugsms

gp10devhts

A Laravel package providing a clean, developer-friendly integration with the UGSMS SMS API v2.

Package info

github.com/GP10DevHTS/laravel-ugsms

pkg:composer/gp10devhts/laravel-ugsms

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-12-02 13:43 UTC

This package is not auto-updated.

Last update: 2026-12-02 20:07:34 UTC


README

A Laravel package providing a clean, developer-friendly integration with the UGSMS SMS API v2.

It wraps the documented UGSMS v2 endpoints with typed request methods, typed response objects, specific exceptions, Laravel HTTP Client transport, configuration publishing, service-container bindings, and a facade.

use GP10DevHTS\UgSms\Facades\UgSms;

$response = UgSms::send(
    to: '256702913454',
    message: 'Your appointment has been confirmed.'
);

$response->successful();      // true
$response->transactionId();   // e.g. "ORDER-84721-SMS-01"
$response->remainingBalance(); // e.g. 965.0

Table of contents

Introduction

The package targets UGSMS API v2 at https://www.ugsms.com/api/v2. It implements only operations documented by UGSMS:

  • Sending SMS to one or more recipients.
  • Personalized bulk SMS.
  • SMS transaction status lookup.
  • Account balance.
  • Account usage statistics.
  • Mobile money payment initiation.
  • The documented sandbox variants for sending SMS, bulk SMS, and account balance.

The package does not add undocumented endpoints or infer undocumented behavior. Where the UGSMS documentation is ambiguous, the ambiguity is called out in Documentation notes and API limitations.

Features

  • Send the same message to one or many Ugandan mobile numbers.
  • Send personalized bulk messages in a single request.
  • Optional duplicate protection with your own SMS transaction ID.
  • Optional Idempotency-Key header for bulk requests.
  • SMS transaction status lookup.
  • Account balance and usage statistics.
  • Mobile money payment initiation with an optional callback URL.
  • Sandbox URL selection for the three documented sandbox endpoints.
  • Typed, immutable response objects with convenient accessors.
  • Specific exceptions for authentication, validation, balance, conflict, rate limit, server, connection, configuration, and sandbox errors.
  • API keys are sent only in the documented X-API-Key header and are redacted from exception messages.
  • Retries are disabled by default and, when enabled, apply only to safe GET requests. SMS and payment POST requests are never retried.
  • Laravel auto-discovery, configuration publishing, container bindings, dependency injection, and a facade.
  • No database dependency and no third-party runtime dependencies beyond Laravel components.

Requirements

  • PHP 8.2 or newer.
  • Laravel 11, 12, or 13.
  • A UGSMS account and API key.
  • Composer.

Laravel 11 is past its upstream security-support window. New applications should use Laravel 12 or 13; see Laravel compatibility.

Installation

Install the package with Composer:

composer require gp10devhts/laravel-ugsms

The package is a Laravel library. It does not require a database migration or a service registration step in applications using Laravel package auto-discovery.

Laravel auto-discovery

The package declares its provider and alias in composer.json:

  • Provider: GP10DevHTS\UgSms\UgSmsServiceProvider
  • Alias: UgSms → GP10DevHTS\UgSms\Facades\UgSms

No manual provider registration is required in modern Laravel applications.

If you disable package auto-discovery, register the provider in bootstrap/providers.php (Laravel 11+) or config/app.php:

GP10DevHTS\UgSms\UgSmsServiceProvider::class,

Publishing configuration

Publish the configuration file:

php artisan vendor:publish --tag=ugsms-config

This creates config/ugsms.php. The configuration file can also be used without publishing because the package merges its defaults.

Environment configuration

Add the following values to your .env file:

UGSMS_API_KEY=your-api-key
UGSMS_BASE_URL=https://www.ugsms.com/api/v2
UGSMS_SENDER_ID=UGSMS
UGSMS_TIMEOUT=30
UGSMS_CONNECT_TIMEOUT=10
UGSMS_RETRY_TIMES=0
UGSMS_RETRY_DELAY=200
UGSMS_SANDBOX=false
Variable Default Description
UGSMS_API_KEY none Required API key generated from the UGSMS dashboard.
UGSMS_BASE_URL https://www.ugsms.com/api/v2 Live API v2 base URL. Sandbox mode derives /sandbox from this URL.
UGSMS_SENDER_ID null Optional default sender ID, maximum 11 characters. A per-call sender ID overrides it.
UGSMS_TIMEOUT 30 Total request timeout in seconds. Must be positive.
UGSMS_CONNECT_TIMEOUT 10 Connection timeout in seconds. Must be positive.
UGSMS_RETRY_TIMES 0 Retries for safe GET requests only. 0 disables retries.
UGSMS_RETRY_DELAY 200 Delay between GET retries, in milliseconds.
UGSMS_SANDBOX false Enables documented sandbox endpoints.

The package validates the configuration when the service is first resolved. A missing API key, invalid base URL, or non-positive timeout raises GP10DevHTS\UgSms\Exceptions\InvalidConfigurationException.

API key setup

  1. Log in to the UGSMS dashboard.
  2. Open Settings → API Settings.
  3. Generate an API key.
  4. Store it in UGSMS_API_KEY.

The same key is used for live and sandbox requests, as documented by UGSMS. Never commit the key to version control or place it in client-side code.

Sending an individual SMS

use GP10DevHTS\UgSms\Facades\UgSms;

$response = UgSms::send(
    to: '256702913454',
    message: 'Your appointment has been confirmed.'
);

if ($response->successful()) {
    $transactionId = $response->transactionId();
    $status = $response->status();          // accepted, pending, sent, failed, ...
    $cost = $response->estimatedCost();     // UGX
    $balance = $response->remainingBalance();
}

Sender ID

Set a default sender ID in configuration:

UGSMS_SENDER_ID=CLINIC

Or override it for one request:

$response = UgSms::send(
    to: '256702913454',
    message: 'Your appointment has been confirmed.',
    senderId: 'CLINIC'
);

UGSMS documents a maximum sender ID length of 11 characters. The package validates this before sending.

Duplicate protection with a transaction ID

UGSMS supports an optional transaction_id for safe retries. Provide a stable value of 8–128 characters using letters, numbers, dots, underscores, colons, or hyphens:

$response = UgSms::send(
    to: '256702913454',
    message: 'Your order 84721 is ready for collection.',
    transactionId: 'ORDER-84721-SMS-01'
);

Store the transaction ID. If the first response is lost, send the same number, message, and transaction ID again. UGSMS returns HTTP 200 with duplicate: true and does not resend the SMS or deduct balance again.

if ($response->isDuplicate()) {
    // The original SMS was not resent.
}

Reusing the same transaction ID with a different phone number or message returns HTTP 409 and raises ConflictException.

If you omit the transaction ID, UGSMS generates one and may return it in the response. The package does not generate a transaction ID automatically because duplicate protection is only useful when the caller stores and reuses its own value.

Message length and cost

UGSMS calculates cost as recipients × message segments × price per segment, where message segments are based on 160-character segments. The package does not truncate or rewrite your message. Keep messages under 160 characters to avoid extra segments.

Sending to multiple recipients

Pass an array of numbers to send the same message to multiple recipients:

$response = UgSms::send(
    to: [
        '256702913454',
        '256776913451',
    ],
    message: 'Your account has been updated.'
);

The package joins the numbers into the comma-separated numbers field documented by UGSMS. Empty entries are ignored; an empty list raises ValidationException. Numbers are passed through to UGSMS without rewriting or validating Ugandan phone formats locally.

Bulk SMS

Use bulk sending when each recipient needs a different message:

use GP10DevHTS\UgSms\Facades\UgSms;

$response = UgSms::bulk(
    messages: [
        [
            'number' => '256702913454',
            'message_body' => 'Hello John!',
        ],
        [
            'number' => '256776913451',
            'message_body' => 'Hello Jane!',
        ],
    ],
    reference: 'CAMPAIGN-001'
);

Each message must contain a non-empty number and message_body. The package forwards only those two fields for each message, matching the documented message-object format.

Bulk response and partial failures

Bulk requests can return HTTP 200 with success: false when some messages fail. The response object exposes the summary and per-recipient failures instead of throwing an exception:

if ($response->failed()) {
    foreach ($response->failedMessages() as $failure) {
        // $failure['index'], $failure['number'], $failure['error']
    }
}

$response->successfulCount();
$response->failedCount();
$response->totalContacts();
$response->totalCost();
$response->currentBalance();

The package does not retry bulk POST requests automatically.

Bulk idempotency key

UGSMS shows an optional Idempotency-Key header in its bulk cURL example. The header is not listed in the bulk request-parameter table, so the package supports it as an optional header without assuming additional semantics:

$response = UgSms::bulk(
    messages: $messages,
    reference: 'CAMPAIGN-001',
    idempotencyKey: 'BATCH-2026-0001'
);

SMS transaction status

Look up a transaction using the same transaction ID supplied when sending:

$response = UgSms::status('ORDER-84721-SMS-01');

$response->transactionId();
$response->messageId();
$response->status();          // accepted, pending, sent, failed, ...
$response->responseMessage();

A missing transaction returns HTTP 404 and raises NotFoundException.

Account balance

use GP10DevHTS\UgSms\Facades\UgSms;

$balance = UgSms::account()->balance();

$balance->balance();      // 1000.5
$balance->currency();     // "UGX"
$balance->apiKey();       // masked key returned by UGSMS
$balance->apiKeyExpires();
$balance->lastApiUsed();

Account usage statistics

$usage = UgSms::account()->usage();

$usage->userId();
$usage->accountBalance();
$usage->messagePricePerSegment();
$usage->apiVersion();
$usage->timestamp();

UGSMS does not document a sandbox variant for usage statistics. Calling usage() while sandbox mode is enabled raises SandboxNotSupportedException rather than silently hitting the live endpoint.

Payments

Initiate a mobile money top-up:

use GP10DevHTS\UgSms\Facades\UgSms;

$payment = UgSms::payments()->create(
    amount: 5000,
    phoneNumber: '256702913454',
    callbackUrl: 'https://example.com/ugsms/payment-callback'
);

$payment->transactionId(); // UGSMS payment transaction ID
$payment->status();        // "pending"
$payment->amount();        // 5000.0
$payment->phoneNumber();

The documented minimum amount is 5,000 UGX. The package validates the minimum before making a request. A successful API response means the payment request was created and the phone prompt was sent; it does not mean the customer has completed the payment.

UGSMS returns the payment object at the top level of the response rather than inside data. PaymentResponse handles this: both payment() and data() return the payment object.

Payment callbacks

If you provide callbackUrl, UGSMS posts a notification after the payment is confirmed and your account is credited. The package does not create a callback route for you.

UGSMS documents these callback headers:

  • X-UGSMS-Event
  • X-UGSMS-Transaction-ID

The documentation does not describe a callback signature or secret-verification mechanism. Treat callback content as untrusted input and reconcile it against your own payment records before fulfilling an order.

UGSMS does not document a payment-status lookup endpoint or a sandbox payment endpoint. The package therefore supports payment initiation only, and rejects payments()->create() while sandbox mode is enabled.

Sandbox mode

Enable sandbox mode:

UGSMS_SANDBOX=true

The same API key is used. The package changes the URL, not the request or response format, as documented:

Operation Live endpoint Sandbox endpoint
Send SMS /api/v2/sms/send /api/v2/sandbox/sms/send
Send bulk SMS /api/v2/sms/send/bulk /api/v2/sandbox/sms/send/bulk
Account balance /api/v2/account/balance /api/v2/sandbox/account/balance

Sandbox responses include sandbox: true where documented. Response objects expose this through isSandbox() and note().

$response = UgSms::send(
    to: '0702913454',
    message: 'Sandbox test'
);

$response->isSandbox(); // true
$response->note();      // "Switch /sandbox/sms/send to /sms/send to go live"

UGSMS documents no sandbox variants for SMS transaction status, account usage, or payments. In sandbox mode those operations raise SandboxNotSupportedException without making a request.

If UGSMS_BASE_URL already ends with /sandbox, the package does not append a second /sandbox.

Error handling

All package exceptions extend GP10DevHTS\UgSms\Exceptions\UgSmsException:

Exception Typical cause
InvalidConfigurationException Missing API key, invalid base URL, or invalid timeout/retry settings.
AuthenticationException HTTP 401: invalid, missing, or expired API key.
ValidationException Local input validation failure, or HTTP 400/422 from UGSMS.
InsufficientBalanceException HTTP 402: not enough balance.
NotFoundException HTTP 404: transaction or resource not found.
ConflictException HTTP 409: transaction ID reused with different content.
RateLimitException HTTP 429: rate limit exceeded.
ServerException HTTP 5xx from UGSMS.
ApiException Another undocumented HTTP error status.
ConnectionException Network or connection failure.
UnexpectedResponseException A successful response that is not a JSON object.
SandboxNotSupportedException A non-sandboxed endpoint was called in sandbox mode.
use GP10DevHTS\UgSms\Exceptions\InsufficientBalanceException;
use GP10DevHTS\UgSms\Exceptions\RateLimitException;
use GP10DevHTS\UgSms\Exceptions\UgSmsException;
use GP10DevHTS\UgSms\Facades\UgSms;

try {
    UgSms::send(
        to: '256702913454',
        message: 'Your appointment has been confirmed.',
        transactionId: 'ORDER-84721-SMS-01'
    );
} catch (InsufficientBalanceException $exception) {
    // Top up the UGSMS account.
} catch (RateLimitException $exception) {
    $seconds = $exception->retryAfter(); // from Retry-After, when provided
} catch (UgSmsException $exception) {
    report($exception);
}

Useful exception accessors:

$exception->getMessage();   // safe package message with the API key redacted
$exception->httpStatus();   // 401, 402, 404, 409, 429, 500, ... or null
$exception->apiMessage();   // message from UGSMS, when available
$exception->errors();       // field errors from UGSMS, when available

HTTP errors versus success: false

  • Non-2xx HTTP responses throw the mapped exception.
  • A 2xx response is returned as a response object even when its top-level success flag is false. This is necessary because bulk requests can report partial success in the body.
  • Check successful() / failed() and the endpoint-specific fields for these responses.

Retries

Automatic retries are disabled by default. When UGSMS_RETRY_TIMES is greater than zero:

  • Only GET requests (balance, usage, status) are retried.
  • Retries occur on connection failures, HTTP 429, and HTTP 5xx responses.
  • For HTTP 429, the Retry-After header is respected when present.
  • POST requests (SMS, bulk SMS, payments) are never retried, because a retry could duplicate an SMS delivery or payment request.

For safe SMS retries, reuse your own transaction ID as described in Duplicate protection with a transaction ID.

Credential safety

  • The API key is sent only in the X-API-Key header.
  • API keys are never added to URLs, request bodies, logs, or response objects.
  • If UGSMS echoes the API key in an error message, the package redacts it before exposing the exception.

Response objects

All responses extend GP10DevHTS\UgSms\DTOs\Response and expose:

$response->successful();
$response->failed();
$response->message();
$response->data();
$response->raw();         // complete decoded response body
$response->toArray();     // alias of raw()
$response->httpStatus();
$response->isSandbox();
$response->note();

Endpoint-specific responses:

  • SmsResponse: transaction ID, message ID, status, status enum, response message, recipients, segments, estimated cost, remaining balance, API version, timestamp, duplicate flag.
  • BulkSmsResponse: summary, counts, costs, current balance, successful messages, failed messages, failure flag.
  • BalanceResponse: balance, currency, masked API key, expiry, last use, sandbox price per SMS, API version.
  • UsageResponse: user ID, account balance, price per segment, API version, timestamp.
  • PaymentResponse: top-level payment object, amount, status, payment transaction ID, phone number, timestamps, payment message.

Status values can be compared as strings or via the documented enums:

use GP10DevHTS\UgSms\Enums\MessageStatus;
use GP10DevHTS\UgSms\Enums\PaymentStatus;

$response->statusEnum() === MessageStatus::Sent;
$payment->statusEnum() === PaymentStatus::Pending;

UGSMS describes SMS statuses as “typical”, so unknown status strings keep their raw value in status() and return null from statusEnum().

Dependency injection

The facade is convenient, but the package is fully container-bound. Type-hint GP10DevHTS\UgSms\UgSms or a specific service:

use GP10DevHTS\UgSms\UgSms;

final class SendAppointmentReminder
{
    public function __construct(private readonly UgSms $ugSms)
    {
    }

    public function __invoke(string $phoneNumber): void
    {
        $this->ugSms->send(
            to: $phoneNumber,
            message: 'Your appointment has been confirmed.'
        );
    }
}

Specific services are also bound:

use GP10DevHTS\UgSms\Services\AccountService;
use GP10DevHTS\UgSms\Services\PaymentService;
use GP10DevHTS\UgSms\Services\SmsService;

public function __construct(
    private readonly SmsService $sms,
    private readonly AccountService $account,
    private readonly PaymentService $payments,
) {
}

The low-level transport contract is GP10DevHTS\UgSms\Contracts\UgSmsClientInterface and is bound to GP10DevHTS\UgSms\Http\UgSmsClient.

Testing

Run the package test suite:

composer test

or directly:

vendor/bin/phpunit

The test suite uses Orchestra Testbench and Laravel HTTP fakes. It never sends a real SMS, makes a real payment, or contacts UGSMS.

Example of faking the API in an application test:

use Illuminate\Support\Facades\Http;

Http::fake([
    'https://www.ugsms.com/api/v2/sms/send' => Http::response([
        'success' => true,
        'message' => 'Message sent successfully via v2 API',
        'data' => [
            'recipients' => 1,
            'number_of_messages' => 1,
            'estimated_cost' => 35,
            'remaining_balance' => 965,
            'api_version' => 'v2',
            'status' => 'pending',
            'transaction_id' => 'ORDER-84721-SMS-01',
        ],
    ]),
]);

$response = UgSms::send(
    to: '256702913454',
    message: 'Test message.',
    transactionId: 'ORDER-84721-SMS-01'
);

Http::assertSent(fn ($request) => $request->hasHeader('X-API-Key', 'test-api-key'));

API reference

Base URL: https://www.ugsms.com/api/v2
Authentication: X-API-Key: your_api_key
Rate limit: 60 requests per minute per API key

Operation Method Endpoint Package method Sandbox
Send SMS POST /sms/send UgSms::send() Yes
SMS status GET /sms/status/{transaction_id} UgSms::status() Not documented
Bulk SMS POST /sms/send/bulk UgSms::bulk() Yes
Balance GET /account/balance UgSms::account()->balance() Yes
Usage GET /account/usage UgSms::account()->usage() Not documented
Payment initiation POST /payments UgSms::payments()->create() Not documented

UGSMS also supports GET for /sms/send, but this package uses the documented POST form only.

Laravel compatibility

Laravel PHP Package support Notes
13.x 8.3+ Yes Current major version.
12.x 8.2+ Yes Supported by the package.
11.x 8.2+ Yes Composer-compatible; Laravel 11 is past upstream security support.
10.x and older — No Not targeted by this package.

The package test suite in this repository was run on Laravel 13.45 with PHP 8.4 and PHPUnit 12.5. Composer constraints allow Laravel 11, 12, and 13; the code uses only APIs available across those versions.

Documentation notes and API limitations

The package intentionally does not guess at undocumented behavior. The following points come from the official v2 documentation or from inconsistencies within it:

  • Sandbox coverage is partial. UGSMS documents sandbox URLs only for SMS send, bulk SMS, and account balance. Status lookups, usage, and payments raise SandboxNotSupportedException in sandbox mode.
  • No payment status endpoint. The documentation describes payment initiation and a success callback, but no API endpoint for polling payment status. There is also no sandbox payment endpoint.
  • No callback signature documented. UGSMS documents X-UGSMS-Event and X-UGSMS-Transaction-ID headers but no signing secret. Treat callbacks as untrusted until reconciled.
  • Payment response shape differs. Payment responses place the payment object at the top level, not inside data. The package normalizes this in PaymentResponse.
  • Bulk sandbox example inconsistency. The bulk endpoint documents a messages array, but the sandbox bulk example shows numbers and message_body. The package follows the documented bulk request contract (messages) for both live and sandbox bulk requests.
  • Bulk Idempotency-Key is example-only. It appears in the bulk cURL example but not in the request-parameter table. It is supported as an optional header.
  • Bulk response example duplicate key. The documented bulk response example repeats total_messages inside summary with different values, which cannot occur in valid JSON. The package simply exposes the actual summary object returned by the API.
  • Error body schema is not fully specified. The package maps exceptions by HTTP status and exposes message and errors when present.
  • Phone formats are delegated to UGSMS. UGSMS documents formats such as 0702913454 and +256702913454. The package passes numbers through without rewriting them and relies on the API for phone validation.
  • Sender ID and transaction ID constraints are validated locally. Sender ID is limited to 11 characters; transaction ID is limited to 8–128 characters from the documented character set.
  • SMS POST retries are unsafe. The package never retries SMS or payment POST requests automatically. Use your own transaction ID for safe SMS retries.

Contributing

Contributions are welcome. See CONTRIBUTING.md.

License

The MIT License (MIT). See LICENSE.