Push Notifications

PHP Push API Walkthrough

0 MIN READ • Mar 10, 2022

PubNub enables real-time Publish/Subscribe for PHP, supporting terminals and web servers like Apache, Nginx, and Lighttpd. With the PubNub PHP Push API, JavaScript browsers can push messages to PHP servers or CLI programs, ensuring instant data exchange.

This walk-through can work on your laptop in a terminal/console. If you don't have a terminal/console, then read the JavaScript Push API.

Our Ruby, JavaScript and C# Push APIs are available on GitHub. Download the PubNub API on GitHub.

PHP developers can push messages to JavaScript Browsers. Read PHP Push API Reference Tutorial for condensed reference API function calls.

Push API Architecture

A production-ready push system consists of a backend push server, a messaging queue, and delivery services. The push server processes events and dispatches them to respective push services. For example, a queue-based system using Redis or RabbitMQ ensures asynchronous message processing:

PHP
$redis->lpush('push_queue', json_encode(['user_id' => 123, 'message' => 'New update available']));

PHP Push API Overview: How it Works

PHP push APIs interact with client applications by maintaining persistent connections or invoking external push services. PHP scripts initiate requests via RESTful APIs, WebSockets, or third-party SDKs like PubNub:

PHP
$pubnub->publish()
    ->channel("notifications")
    ->message(["title" => "New Event", "body" => "A new event has been added"])
    ->sync();

Setting Up a PHP Push Notification Service

A push service in PHP can be implemented using FCM for mobile notifications or WebSockets for real-time web push. A simple WebSocket-based implementation using Ratchet:

PHP
$server = IoServer::factory(new HttpServer(new WsServer(new PushServer())), 8080);
$server->run();

Integrating Push APIs with Mobile and Web Applications

Mobile applications require integration with FCM/APNS, while web clients use Service Workers for push notifications. The backend sends payloads to FCM:

PHP
$payload = json_encode(['to' => $deviceToken, 'notification' => ['title' => 'Hello', 'body' => 'New message']]);
$ch = curl_init('https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

Authentication and Authorization for Secure Push Notifications

Ensuring secure push communication requires token-based authentication, API key validation, and encryption. OAuth2 or JWT can be used for secure push notification delivery:

PHP
$jwt = JWT::encode(['user_id' => 123, 'exp' => time() + 3600], $secretKey, 'HS256');

Handling Push Notification Delivery Status

To track delivery, services like FCM and PubNub provide message status APIs. PHP can process responses to handle failures and retries:

PHP
$response = $pubnub->getMessageActions()->channel('notifications')->sync();

Message Formats and Payloads in PHP Push APIs

Push messages use structured payloads that vary by service. A JSON payload for FCM:

Code
{
  "to": "/topics/news",
  "notification": {
    "title": "Breaking News",
    "body": "Details inside..."
  }
}

Optimizing Push Notifications for Scalability and Performance

Scaling push systems requires load balancing, queueing, and batched deliveries. Using Redis Streams for push event buffering:

PHP
$redis->xadd('push_stream', '*', ['message' => 'New Notification']);

Push Notification Best Practices for Production Environments

Use efficient retry mechanisms, handle expired tokens, and implement rate limiting. Log all push events for debugging and analytics.

Managing Push API Failures and Retrying Strategies

Implement exponential backoff for retries and handle transient failures. Using a retry queue in Laravel:

PHP
dispatch(new SendPushNotification($userId, $message))->delay(now()->addSeconds(10));

This ensures notifications are retried without overloading push services.