Install the Package:
composer require namnv609/php-onesignal-sdk
Note: Due to PHP 5.5+ requirement, ensure your Laravel app uses PHP 5.6+ or configure a compatibility layer.
Configure OneSignal:
Add your credentials to .env:
ONESIGNAL_AUTH_KEY=your_auth_key_here
ONESIGNAL_APP_ID=your_app_id
ONESIGNAL_REST_KEY=your_rest_key
Initialize the SDK:
Create a service class (e.g., app/Services/OneSignalService.php):
namespace App\Services;
use NNV\OneSignal\OneSignal;
class OneSignalService
{
protected $client;
public function __construct()
{
$this->client = new OneSignal(
env('ONESIGNAL_AUTH_KEY'),
env('ONESIGNAL_APP_ID'),
env('ONESIGNAL_REST_KEY')
);
}
// Delegate methods (e.g., sendNotification) here
}
Register the Service:
Bind the service in AppServiceProvider:
public function register()
{
$this->app->singleton(OneSignalService::class, function ($app) {
return new OneSignalService();
});
}
First Use Case: Send a test notification:
use App\Services\OneSignalService;
use NNV\OneSignal\API\Notification;
public function sendTestNotification(OneSignalService $service)
{
$notification = new Notification($service->getClient());
$notification->create([
'included_segments' => ['All'],
'contents' => ['en' => 'Hello from Laravel!'],
]);
}
Register a Device:
$player = new Player($service->getClient());
$player->create(\NNV\OneSignal\Constants\DeviceTypes::CHROME_WEBSITE, [
'language' => 'en',
'tags' => ['user_id' => auth()->id()],
]);
Use Case: Track user devices for targeted notifications (e.g., web push, mobile).
Update Device Tags:
$player->update($playerId, [
'tags' => ['new_tag' => 'value'],
]);
Use Case: Dynamic segmentation (e.g., "premium_users").
Send a Scheduled Notification:
$notification = new Notification($service->getClient());
$notification->create([
'included_segments' => ['Active Users'],
'contents' => ['en' => 'Your order is shipping!'],
'send_after' => '2023-12-31 12:00:00', // ISO format
]);
Use Case: Marketing campaigns, order updates.
Cancel a Notification:
$notification->cancel($notificationId);
Use Case: Emergency overrides (e.g., recall a promotional message).
Track Notification Opens:
$notification->trackOpen($notificationId);
Use Case: Measure engagement (e.g., "Did users click the discount notification?").
Export Player Data (CSV):
$player->csvExport(['email', 'created_at']);
Use Case: Audits, user segmentation for CRM.
OrderShipped):
use Illuminate\Support\Facades\Event;
Event::listen(OrderShipped::class, function ($order) {
$service->sendNotification([
'included_segments' => ['user_' . $order->user_id],
'contents' => ['en' => 'Your order #' . $order->id . ' is shipped!'],
]);
});
// In Authenticate.php middleware
public function handle($request, Closure $next)
{
if ($request->user()) {
$player = new Player($service->getClient());
$player->update($request->user()->device_id, [
'tags' => ['authenticated' => 'true'],
]);
}
return $next($request);
}
use Illuminate\Support\Facades\Queue;
Queue::push(new SendOneSignalNotification($data));
Job Class:
class SendOneSignalNotification implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable;
public function handle(OneSignalService $service)
{
$notification = new Notification($service->getClient());
$notification->create($this->data);
}
}
public function getPlayers()
{
$player = new Player($service->getClient());
$response = $player->all();
return response()->json([
'data' => $response->response->players,
'meta' => ['count' => count($response->response->players)],
]);
}
try {
$response = $player->create($deviceType, $data);
if (!$response->status) {
throw new \Exception("OneSignal error: " . $response->code);
}
} catch (\Exception $e) {
\Log::error("OneSignal failed: " . $e->getMessage());
// Retry or notify admins
}
// config/onesignal.php
return [
'auth_key' => env('ONESIGNAL_AUTH_KEY'),
'app_id' => env('ONESIGNAL_APP_ID'),
'rest_key' => env('ONESIGNAL_REST_KEY'),
'default_segment' => 'All',
];
Access via:
config('onesignal.default_segment')
$mock = Mockery::mock(OneSignal::class);
$mock->shouldReceive('create')->andReturn((object) [
'status' => true,
'code' => 200,
'response' => (object) ['id' => 123],
]);
$this->app->instance(OneSignal::class, $mock);
.env for different stages:
# .env.staging
ONESIGNAL_AUTH_KEY=staging_key
ONESIGNAL_APP_ID=staging_app_id
php-compatibility or fork the SDK to update dependencies.HttpClient (see "Tips" below).HttpClient.use Illuminate\Support\Facades\Http;
$response = Http::retry(3, 100)->post('...');
$user->device_id = $player->create(...)->response->id;
$user->save();
send_after timestamps must be in GMT.
$sendAfter = now()->timezone('GMT')->toDateTimeString();
How can I help you explore Laravel packages today?