yashcli/onesignal-notifier
最新稳定版本:v1.0.0
Composer 安装命令:
composer require yashcli/onesignal-notifier
包简介
A comprehensive OneSignal notification package for Laravel
关键字:
README 文档
README
A comprehensive Laravel package for sending push notifications through OneSignal with support for all features including images, priority, player_id, subscription_id, and more.
Features
- ✅ Complete OneSignal API Support - All features from the OneSignal API documentation
- ✅ Image Support - Set images for different platforms (big_picture, chrome_web_image, etc.)
- ✅ Priority Control - Set notification priority levels
- ✅ Multiple Targeting Options - Support for player_id, subscription_id, external_user_id, OneSignal ID
- ✅ Platform-Specific Features - iOS, Android, Huawei, Web push specific settings
- ✅ Scheduling - Send notifications at specific times
- ✅ Filters & Segments - Advanced targeting with filters and segments
- ✅ Buttons & Actions - Interactive notifications with buttons
- ✅ Custom Data - Attach custom data to notifications
- ✅ Laravel Integration - Works seamlessly with Laravel notifications
- ✅ Error Handling - Comprehensive error handling with custom exceptions
- ✅ Facade Support - Easy access through Laravel facades
Requirements
- PHP: 8.0 or higher
- Laravel: 8.0, 9.0, 10.0, 11.0, or 12.0
Installation
1. Install the package
composer require yashcli/onesignal-notifier
2. Publish the configuration file
php artisan vendor:publish --tag=onesignal-notifier-config
3. Configure your OneSignal credentials
Add your OneSignal credentials to your .env file:
ONESIGNAL_APP_ID=your-app-id ONESIGNAL_REST_API_KEY=your-rest-api-key ONESIGNAL_API_URL=https://api.onesignal.com/notifications
Configuration
The configuration file config/onesignal-notifier.php contains all the settings:
return [ 'app_id' => env('ONESIGNAL_APP_ID'), 'rest_api_key' => env('ONESIGNAL_REST_API_KEY'), 'api_url' => env('ONESIGNAL_API_URL', 'https://api.onesignal.com/notifications'), 'defaults' => [ 'priority' => 10, 'ttl' => 259200, // 3 days in seconds 'ios_sound' => 'default', 'android_sound' => 'default', 'android_channel_id' => null, 'ios_badge_type' => 'Increase', 'ios_badge_count' => 1, ], 'platforms' => [ 'ios' => [ 'enabled' => true, 'interruption_level' => 'active', ], 'android' => [ 'enabled' => true, 'accent_color' => '#FF0000', ], 'web' => [ 'enabled' => true, ], ], ];
Usage
Basic Usage
use YashCli\OneSignalNotifier\OneSignal; $oneSignal = new OneSignal(); $result = $oneSignal ->setContent(['en' => 'Hello! This is a test notification.']) ->setHeading(['en' => 'Test Notification']) ->setSubscriptionIds(['subscription_id_1', 'subscription_id_2']) ->send();
Using the Facade
use YashCli\OneSignalNotifier\OneSignalFacade; $result = OneSignalFacade::setContent(['en' => 'Hello!']) ->setHeading(['en' => 'Test']) ->setSubscriptionIds(['subscription_id_1']) ->send();
Laravel Notifications
Create a notification class:
use Illuminate\Notifications\Notification; use YashCli\OneSignalNotifier\Channels\OneSignalChannel; class TestNotification extends Notification { public function via($notifiable): array { return [OneSignalChannel::class]; } public function toOneSignal($notifiable): array { return [ 'content' => ['en' => 'You have a new message!'], 'heading' => ['en' => 'New Message'], 'subscription_ids' => ['subscription_id_1'], 'priority' => 10, 'images' => [ 'big_picture' => 'https://example.com/image.jpg', ], 'custom_data' => [ 'message_id' => '12345', 'sender' => 'John Doe', ], ]; } }
Creating a Client with Custom Credentials
If you need to send notifications using a different OneSignal App ID and REST API Key (for example, to support multiple OneSignal apps), you can create a client instance with custom credentials:
use YashCli\OneSignalNotifier\OneSignal; $client = OneSignal::createClient('your-app-id', 'your-rest-api-key'); $result = $client ->setContent(['en' => 'Hello from a custom client!']) ->setHeading(['en' => 'Custom Client']) ->setSubscriptionIds(['subscription_id_1']) ->send();
You can also specify a custom API URL as the third argument if needed.
Recipient Resolution with routeNotificationForOneSignal
You can define a routeNotificationForOneSignal method on your notifiable model (e.g., User) to automatically resolve recipient IDs for notifications. This allows you to avoid specifying player IDs, subscription IDs, or external user IDs in every notification class.
How to use:
Add the method to your notifiable model:
// In your User model (or any Notifiable model) public function routeNotificationForOneSignal() { // Return a single player ID (deprecated) // return 'PLAYER_ID'; // Return an array of player IDs (deprecated) // return ['PLAYER_ID_1', 'PLAYER_ID_2']; // Return subscription IDs (recommended) // return ['subscription_id_1', 'subscription_id_2']; // Return external user IDs // return ['include_external_user_ids' => [$this->id]]; // Return email for OneSignal syncHashedEmail feature // return ['email' => $this->email]; // Return tags for advanced targeting // return ['tags' => ['key' => 'device_uuid', 'relation' => '=', 'value' => $this->device_uuid]]; }
How it works:
- If you do not specify recipient IDs in your notification class, the package will automatically use the value from
routeNotificationForOneSignalon the notifiable model. - This works for player IDs, subscription IDs, external user IDs, email, and tags.
Example:
// User model public function routeNotificationForOneSignal() { return ['subscription_id_1', 'subscription_id_2']; } // Notification class (no need to specify recipient IDs) public function toOneSignal($notifiable): array { return [ 'content' => ['en' => 'You have a new message!'], 'heading' => ['en' => 'New Message'], // No subscription_ids needed here! ]; }
Advanced Features
Images and Icons
$oneSignal->setImages([ 'big_picture' => 'https://example.com/image.jpg', 'chrome_web_image' => 'https://example.com/web-image.jpg', 'huawei_big_picture' => 'https://example.com/huawei-image.jpg', 'adm_big_picture' => 'https://example.com/amazon-image.jpg', ]); $oneSignal->setIcons([ 'small_icon' => 'https://example.com/small-icon.png', 'large_icon' => 'https://example.com/large-icon.png', 'chrome_web_icon' => 'https://example.com/web-icon.png', 'firefox_icon' => 'https://example.com/firefox-icon.png', ]);
Priority and TTL
$oneSignal->setPriority(10) // High priority ->setTtl(3600); // 1 hour TTL
Platform-Specific Settings
iOS Settings
$oneSignal->setIosInterruptionLevel('time-sensitive') ->setIosSound('default') ->setIosBadgeType('Increase') ->setIosBadgeCount(1) ->setIosCategory('message') ->setTargetContentIdentifier('message_123') ->setThreadId('chat_456') ->setIosRelevanceScore(5);
Android Settings
$oneSignal->setAndroidAccentColor('#FF0000') ->setAndroidChannelId('default') ->setAndroidGroup('chat_messages');
Huawei Settings
$oneSignal->setHuaweiChannelId('huawei_channel') ->setHuaweiCategory('message') ->setHuaweiMsgType('data') ->setHuaweiBiTag('tag1') ->setHuaweiAccentColor('#FF0000');
Targeting Options
Subscription IDs (Recommended)
$oneSignal->setSubscriptionIds(['subscription_id_1', 'subscription_id_2']);
External User IDs
$oneSignal->setExternalUserIds(['user_123', 'user_456']);
OneSignal IDs
$oneSignal->setOneSignalIds(['1589641e-bed1-4325-bce4-d2234e578884']);
Player IDs (Deprecated)
$oneSignal->setPlayerIds(['player_id_1', 'player_id_2']);
Buttons and Actions
$oneSignal->setButtons([ [ 'id' => 'accept', 'text' => 'Accept', 'icon' => 'https://example.com/accept-icon.png', ], [ 'id' => 'decline', 'text' => 'Decline', 'icon' => 'https://example.com/decline-icon.png', ], ]); $oneSignal->setWebButtons([ [ 'id' => 'view', 'text' => 'View Details', 'url' => 'https://yourapp.com/details', ], ]);
Scheduling
$oneSignal->setSendAfter(date('c', strtotime('+1 hour'))) // Send after 1 hour ->setDelayedOption('timezone') // or 'last-active' ->setDeliveryTimeOfDay('9:00AM');
Filters and Segments
// Add filters $oneSignal->addFilter('first_session', 'first_session', '>', '1') ->addFilter('country', 'country', '=', 'US'); // Set segments $oneSignal->setIncludedSegments(['Subscribed Users']) ->setExcludedSegments(['Inactive Users']);
Custom Data
$oneSignal->setCustomData([ 'message_id' => '12345', 'sender' => 'John Doe', 'type' => 'chat', ]); $oneSignal->setData([ 'silent' => true, 'action' => 'refresh', ]);
URLs and Deep Linking
$oneSignal->setUrl('https://yourapp.com/messages/12345') ->setAppUrl('yourapp://messages/12345') ->setWebUrl('https://yourapp.com/web/messages/12345');
Silent Notifications
$oneSignal->setContentAvailable(true) ->setData(['silent' => true, 'action' => 'refresh']);
Error Handling
The package provides comprehensive error handling:
use YashCli\OneSignalNotifier\Exceptions\OneSignalException; try { $result = $oneSignal->send(); } catch (OneSignalException $e) { echo "OneSignal Error: " . $e->getMessage() . "\n"; if ($e->hasInvalidAliases()) { echo "Invalid Aliases: " . json_encode($e->getInvalidAliases()) . "\n"; } if ($e->hasInvalidPlayerIds()) { echo "Invalid Player IDs: " . json_encode($e->getInvalidPlayerIds()) . "\n"; } echo "Errors: " . json_encode($e->getErrors()) . "\n"; }
API Reference
Core Methods
| Method | Description |
|---|---|
setContent(array $content) |
Set notification content for different languages |
setHeading(array $heading) |
Set notification heading for different languages |
setSubtitle(array $subtitle) |
Set notification subtitle for different languages |
setName(string $name) |
Set notification name/template name |
setTemplateId(string $templateId) |
Set template ID |
setCustomData(array $data) |
Set custom data |
setData(array $data) |
Set additional data |
setPriority(int $priority) |
Set notification priority |
setTtl(int $ttl) |
Set TTL (Time To Live) in seconds |
setCollapseId(string $collapseId) |
Set collapse ID for grouping notifications |
Targeting Methods
| Method | Description |
|---|---|
setSubscriptionIds(array $ids) |
Set subscription IDs (recommended) |
setExternalUserIds(array $ids) |
Set external user IDs |
setOneSignalIds(array $ids) |
Set OneSignal IDs |
setPlayerIds(array $ids) |
Set player IDs (deprecated) |
setIncludeAliases(array $aliases) |
Set include aliases |
Platform-Specific Methods
| Method | Description |
|---|---|
setIosInterruptionLevel(string $level) |
Set iOS interruption level |
setIosSound(string $sound) |
Set iOS sound |
setIosBadgeType(string $type) |
Set iOS badge type |
setIosBadgeCount(int $count) |
Set iOS badge count |
setAndroidAccentColor(string $color) |
Set Android accent color |
setAndroidChannelId(string $channelId) |
Set Android channel ID |
setHuaweiChannelId(string $channelId) |
Set Huawei channel ID |
Image and Icon Methods
| Method | Description |
|---|---|
setImages(array $images) |
Set images for different platforms |
setIcons(array $icons) |
Set icons for different platforms |
setIosAttachments(array $attachments) |
Set iOS attachments |
Action Methods
| Method | Description |
|---|---|
setButtons(array $buttons) |
Set buttons for mobile apps |
setWebButtons(array $buttons) |
Set web buttons |
Filter and Segment Methods
| Method | Description |
|---|---|
setFilters(array $filters) |
Set filters for targeting |
addFilter(string $field, string $key, string $relation, string $value) |
Add a filter |
setIncludedSegments(array $segments) |
Set included segments |
setExcludedSegments(array $segments) |
Set excluded segments |
Scheduling Methods
| Method | Description |
|---|---|
setScheduling(array $scheduling) |
Set scheduling options |
setSendAfter(string $dateTime) |
Set send after date/time |
setDelayedOption(string $option) |
Set delayed option |
setDeliveryTimeOfDay(string $time) |
Set delivery time of day |
Utility Methods
| Method | Description |
|---|---|
send() |
Send the notification |
getPayload() |
Get the current payload |
reset() |
Reset the payload to initial state |
System Requirements
- PHP: 8.0 or higher
- Laravel: 5.*, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, or 12.0
- GuzzleHTTP: 7.0 or higher
License
This package is open-sourced software licensed under the MIT license.
Support
For support, please open an issue on GitHub or contact the maintainer.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-30