How to Send Push Notifications Using One Signal + PHP + Server API
Integrating One Signal into your backend architecture is a straightforward process, but it requires careful handling of authentication and payload construction. The core mechanism relies on HTTP POST requests sent from your server to the One Signal REST API endpoint. When working with PHP, you typically use curl or Guzzle to execute these calls. Before writing any code, ensure you have access to your One Signal application's key IDs: the Application ID is required for all requests, while the REST API Key serves as your authentication token.
Authentication and Security
Security is the first line of defense when interacting with the One Signal API. You must include the API Key in every request header to prevent unauthorized access. A common mistake developers make is appending the key to the URL query string or passing it as a form parameter, which exposes it in server logs or browser history.
In PHP using curl, this looks like:
$url = "https://onesignal.com/api/v1/notifications";
$api_key = "your_rest_api_key_here"; // Replace with actual key from One Signal dashboard
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Basic ' . base64_encode($api_key)
]);
// Note: Some integrations prefer sending the key directly in headers depending on specific One Signal config,
// but standard practice for server-side scripts is often direct header inclusion or query param if specified by dashboard.
// Ensure you are using the correct authentication method documented in your specific One Signal project settings.
Correction: Upon reviewing standard One Signal REST API documentation, the most reliable method for programmatic access without OAuth tokens involves passing the key directly in the Authorization header as a Basic Auth token or, more commonly for the free tier and standard plans, including it in the request headers specifically formatted by their dashboard settings. Many developers find success using the Authorization: Basic method where the API Key is base64 encoded, though some configurations allow direct inclusion in headers depending on the specific integration guide. Always verify the exact header format in your One Signal project settings, as this can change based on plan upgrades or specific enterprise requirements.
Constructing the Notification Payload
The body of your POST request determines how the notification is delivered. The JSON payload must strictly adhere to One Signal's schema. You generally need to specify the device channels you want to target. For Android specifically, you set the android object within the payload.
Here is a practical example of a PHP array structure converted to JSON:
$payload = [
'app_id' => 'YOUR_ONE_SIGNAL_APP_ID',
'headings' => [
'en' => 'New Feature Available',
'es' => 'Nueva funcionalidad disponible'
],
'contents' => [
'en' => 'We have updated our app with exciting new features.',
'es' => 'Hemos actualizado nuestra aplicación con nuevas funciones emocionantes.'
],
'buttons' => [
[
'key' => 'button_1',
'text' => 'View Now',
'action' => 'https://yourdomain.com/new-feature'
]
],
'android' => [
'collapse_key' => 'update_available',
'sound' => 'default',
'icon' => '@ic_notification_icon',
'priority' => 'high'
],
'ios' => [
'badge' => 0,
'sound' => 'default'
]
];
Notice the app_id at the root level. This is mandatory for REST API calls that don't use a specific device token in the request body to identify which application instance should receive the push. If you are targeting a specific user or segment, you would include those fields here instead of relying on a broad broadcast.
Handling Responses and Errors
One Signal returns a JSON response indicating success or failure. A 200 OK status code with an empty body usually signifies success for bulk notifications or those sent to segments. However, if you are sending to specific devices via their unique device tokens, the response will include a list of results detailing exactly which tokens received the notification and which failed.
It is critical to parse these responses in your PHP application to log failures. Common reasons for failure include invalid device tokens, mismatched channel types (e.g., sending an iOS-only payload to an Android token), or exceeding rate limits. One Signal enforces strict rate limits per API key; exceeding these will result in a 429 Too Many Requests response. You should implement exponential backoff logic in your PHP code if you detect consecutive 429 errors to prevent hammering the API and causing temporary bans.
Trade-offs and Best Practices
When deciding between broadcasting to all users versus targeting specific segments, consider the impact on battery life and data usage. Broad broadcasts are efficient for urgent alerts but can be intrusive. Targeted pushes require maintaining accurate user segmentation within your database or One Signal's dashboard, which adds a layer of complexity to your backend logic.
If you are building a Laravel application, leveraging the community ecosystem can simplify this process. While not strictly necessary, using existing packages that wrap the One Signal API can reduce boilerplate code and minimize syntax errors in JSON construction. For instance, exploring resources like LaravelCompany might provide insights into how other developers have structured similar integrations within the Laravel ecosystem, offering patterns for error handling and queue management that ensure reliable delivery even when your server is under heavy load.
Ultimately, the robustness of your push notification system depends on treating these API calls as asynchronous events in production environments. Use message queues like Redis or RabbitMQ to buffer requests, ensuring that a single failed API call doesn't block other notifications from being sent.