authbucket/push-php
PHP library for sending push notifications to mobile devices. Includes a Silex AuthBucketPushServiceProvider for demos/tests, with configurable models and model managers. Install via Composer (authbucket/push-php) and extend for Symfony2/Drupal wrappers.
Installation Add the package via Composer:
composer require authbucket/push-php
For Laravel, ensure compatibility by checking the Symfony components version (Laravel 5.5+ uses Symfony 4.x, while this package may rely on older versions).
Basic Setup
Register the AuthBucketPushServiceProvider in your Silex app (if using Silex) or integrate the core AuthBucket\Push components directly. For Laravel, manually instantiate the required services:
use AuthBucket\Push\Push;
use AuthBucket\Push\Provider\AuthBucketPushServiceProvider;
$push = new Push();
First Use Case Send a push notification to a device token:
$push = new Push();
$push->setProvider('apns'); // or 'gcm' for Android
$push->setToken('device_token_here');
$push->setMessage('Hello from Laravel!');
$push->send();
AuthBucket\Push\Push for sending notifications.AuthBucket\Push\Provider\ApnsProvider and AuthBucket\Push\Provider\GcmProvider for platform-specific logic.Platform-Specific Providers
Use ApnsProvider for iOS and GcmProvider for Android:
$push = new Push();
$push->setProvider('apns')
->setCertificatePath('/path/to/cert.pem')
->setToken('ios_device_token')
->setMessage('iOS Notification')
->send();
Batch Sending Send notifications to multiple devices:
$push->setProvider('gcm')
->setTokens(['token1', 'token2', 'token3'])
->setMessage('Batch Notification')
->send();
Custom Payloads Extend payloads with additional data (e.g., deep links, custom keys):
$push->setPayload([
'alert' => 'Custom Alert',
'badge' => 1,
'sound' => 'default',
'custom_key' => 'custom_value'
]);
Error Handling Wrap sending in a try-catch block to handle failures:
try {
$push->send();
} catch (\Exception $e) {
Log::error('Push failed: ' . $e->getMessage());
}
Token Management
Store device tokens in a database (e.g., users_devices table) and fetch them when sending notifications:
$tokens = DB::table('users_devices')->where('user_id', $userId)->pluck('device_token');
$push->setTokens($tokens->toArray());
Event-Based Triggers
Dispatch notifications via Laravel events (e.g., OrderShipped):
event(new OrderShipped($order));
// In listener:
$tokens = $order->user->devices->pluck('device_token');
$push->setTokens($tokens)->setMessage('Your order is shipped!')->send();
Queueing Notifications Use Laravel queues to avoid timeouts for large batches:
dispatch(new SendPushNotification($tokens, 'Hello!'))->onQueue('push');
Laravel Service Provider
Bind the Push class in AppServiceProvider:
$this->app->singleton('push', function () {
return new \AuthBucket\Push\Push();
});
Configuration
Store provider-specific settings (e.g., API keys, certificate paths) in config/push.php:
'providers' => [
'apns' => [
'certificate_path' => env('APNS_CERT_PATH'),
'passphrase' => env('APNS_PASSPHRASE'),
],
'gcm' => [
'api_key' => env('GCM_API_KEY'),
],
];
Middleware for Auth Protect push endpoints with Laravel middleware:
Route::post('/push', 'PushController@send')->middleware('auth:api');
Symfony Component Version Mismatch
composer.json or use a wrapper like spatie/symfony-messenger for compatibility.Certificate Management for APNs
env() for certificate paths and validate them on boot:
if (!file_exists(env('APNS_CERT_PATH'))) {
throw new \RuntimeException('APNs certificate not found.');
}
Token Expiry Device tokens can become invalid (e.g., app uninstalled). Implement retry logic or token validation:
$push->setProvider('apns')
->setToken($token)
->setMessage('Test')
->send();
if ($push->getResponse()->getStatusCode() === 400) {
// Token invalid; remove from DB
DB::table('users_devices')->where('device_token', $token)->delete();
}
Rate Limiting APNs and GCM have rate limits. Implement exponential backoff or queue delays:
$push->setProvider('apns')->setMessage('Rate-limited test')->send();
if ($push->getResponse()->getStatusCode() === 429) {
sleep(10); // Retry after 10 seconds
}
Enable Verbose Logging Configure Monolog to log push responses:
$push->setProvider('gcm')->setDebug(true);
// Logs will include raw responses and errors.
Test with Sandbox Environments Use APNs sandbox for development:
$push->setProvider('apns')
->setEnvironment('sandbox') // Default is 'production'
->setCertificatePath('/path/to/sandbox_cert.pem');
Validate Payloads
Ensure payloads comply with platform specs (e.g., APNs requires aps key for alerts):
$push->setPayload([
'aps' => [
'alert' => 'Invalid without this key!',
'sound' => 'default',
],
]);
Custom Providers
Extend AuthBucket\Push\Provider\AbstractProvider for unsupported platforms (e.g., Firebase Cloud Messaging):
class FirebaseProvider extends AbstractProvider {
public function send() {
// Custom Firebase logic
}
}
Model Managers Replace the default in-memory token manager with Doctrine or Eloquent:
$app->bind('authbucket_push.model_manager.factory', function () {
return new \AuthBucket\Push\Model\Manager\DoctrineManager(
$this->get('doctrine')->getManager()
);
});
Event Dispatching Trigger Laravel events after sending:
$push->send();
if ($push->getResponse()->isSuccessful()) {
event(new PushSent($push->getTokens(), $push->getMessage()));
}
Use Laravel Queues for Reliability Offload push sending to queues to handle failures gracefully:
Queue::push(new SendPushJob($tokens, $message));
Monitor Delivery Status Log responses and track delivery metrics (e.g., success/failure rates):
$response = $push->send();
Log::info('Push response', [
'status' => $response->getStatusCode(),
'tokens' => $push->getTokens(),
]);
Secure API Keys
Never hardcode API keys. Use Laravel's .env:
GCM_API_KEY=your_key_here
APNS_CERT_PATH=/path/to/cert.pem
Batch Size Optimization Test batch sizes to avoid timeouts (APNs recommends ≤ 200 tokens per request):
$batchSize = 100;
foreach (array_chunk($tokens, $batchSize) as $chunk) {
$push->setTokens($chunk)->send();
}
How can I help you explore Laravel packages today?