1. Go to this page and download the library: Download esanj/notification-client library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
esanj / notification-client example snippets
return [
'base_url' => env('NOTIFICATION_SERVICE_URL', 'http://localhost'),
'client_id' => env('NOTIFICATION_CLIENT_ID'),
'client_secret' => env('NOTIFICATION_CLIENT_SECRET'),
'token' => [
'cache_store' => env('NOTIFICATION_TOKEN_CACHE_STORE', null),
'cache_key' => env('NOTIFICATION_TOKEN_CACHE_KEY', 'esanj_notification_access_token'),
'buffer_seconds' => 60, // refresh token 60 seconds before actual expiry
'encrypt' => env('NOTIFICATION_TOKEN_ENCRYPT', false),
],
'retry' => [
'attempts' => 3, // total attempts including the first
'sleep_ms' => 1000, // base delay; doubles per attempt, half of it randomised
],
'idempotency' => [
'enabled' => env('NOTIFICATION_IDEMPOTENCY', false), // service honours `Idempotency-Key`
],
'timeout' => 30,
'logging' => [
'channel' => env('NOTIFICATION_LOG_CHANNEL', null),
],
];
use Esanj\NotificationClient\Contracts\NotificationClientInterface;
class OrderService
{
public function __construct(
private readonly NotificationClientInterface $notifier
) {}
}
use Esanj\NotificationClient\Facades\Notifier;
Notifier::send($data);
use Esanj\NotificationClient\DTOs\SendNotificationData;
use Esanj\NotificationClient\DTOs\Payloads\SmsPayload;
$notification = $notifier->send(new SendNotificationData(
recipient: '+989123456789',
payload: SmsPayload::fromMessage('Your OTP is 1234'),
channel: 'sms',
priority: 'high',
));
echo $notification->uuid; // "550e8400-e29b-..."
echo $notification->status; // "pending"
$filter = new NotificationFilter(perPage: 50);
do {
$result = $notifier->listNotifications($filter);
// ... use $result->items
$filter = $filter->nextPage();
} while ($result->hasMorePages());
// List batches
$result = $notifier->listBatches(perPage: 10, page: 1);
// Get single batch
$batch = $notifier->getBatch('batch-uuid');
echo $batch->progressPercentage() . '%';
echo $batch->isCompleted() ? 'Done' : 'In progress';
// Every configured provider — the endpoint is paginated, and this walks all of it
$providers = $notifier->listProviders();
foreach ($providers as $provider) {
echo "{$provider->providerName} ({$provider->providerChannel})" . PHP_EOL;
}
// One page, with the pagination metadata (per_page is capped at 100 by the service)
$page = $notifier->listProvidersPage(perPage: 25, page: 2);
echo "{$page->total} providers in total";
// List available tags
$tags = $notifier->listTags(perPage: 50);
foreach ($tags->items as $tag) {
echo "{$tag->name}: used {$tag->usedCount} times" . PHP_EOL;
}
use Esanj\NotificationClient\Exceptions\ApiException;
use Esanj\NotificationClient\Exceptions\AuthenticationException;
use Esanj\NotificationClient\Exceptions\NotificationClientException;
use Esanj\NotificationClient\Exceptions\RateLimitException;
try {
$notification = $notifier->send($data);
} catch (RateLimitException $e) {
// The OAuth token endpoint is throttled (10/min per IP) — the credentials are fine
$this->release($e->retryAfter ?? 60);
} catch (AuthenticationException $e) {
// OAuth credentials are invalid or the service is unreachable
Log::critical('Notification auth failed', ['error' => $e->getMessage()]);
} catch (ApiException $e) {
if ($e->isClientInputError()) {
// 400 or 422 — the service can't act on what was sent. Fix the request, don't retry.
$errors = $e->getErrors(); // 422 only: ['recipient' => ['The recipient format is invalid.']]
$reason = $e->getMessage(); // 400: "No active provider found for this client and channel."
}
if ($e->isRateLimited()) {
// Still throttled after backing off — come back later instead of hammering
$this->release($e->retryAfter ?? 60);
}
Log::error('Notification API error', [
'status' => $e->statusCode,
'response' => $e->responseBody,
]);
} catch (NotificationClientException $e) {
// Catch-all for any package exception
}
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Esanj\NotificationClient\Auth\TokenManager;
use Esanj\NotificationClient\Http\ApiClient;
use Esanj\NotificationClient\NotificationClient;
$mock = new MockHandler([
// 1st call: token endpoint
new Response(200, [], json_encode([
'access_token' => 'test-token',
'token_type' => 'Bearer',
'expires_in' => 3600,
])),
// 2nd call: send notification
new Response(202, [], json_encode([
'data' => [
'uuid' => 'test-uuid',
'status' => 'pending',
'channel' => 'sms',
'recipient' => '+989123456789',
'batch_uuid' => null,
'sent_at' => null,
'created_at' => now()->toIso8601String(),
'updated_at' => now()->toIso8601String(),
],
])),
]);
$client = new Client(['handler' => HandlerStack::create($mock)]);
// Build dependencies manually
$tokenManager = new TokenManager(
httpClient: $client,
cache: app(\Illuminate\Contracts\Cache\Repository::class),
logger: app(\Psr\Log\LoggerInterface::class),
clientId: 'test-id',
clientSecret: 'test-secret',
tokenEndpoint: 'http://test/api/v1/oauth/token',
cacheKey: 'test_token',
bufferSeconds: 60,
);
$apiClient = new ApiClient(
httpClient: $client,
tokenManager: $tokenManager,
logger: app(\Psr\Log\LoggerInterface::class),
baseUrl: 'http://test',
retryAttempts: 3,
retrySleepMs: 0,
);
$notifier = new NotificationClient($apiClient);