PHP code example of yashcli / onesignal-notifier

1. Go to this page and download the library: Download yashcli/onesignal-notifier library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yashcli / onesignal-notifier example snippets


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,
        ],
    ],
];

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();

use YashCli\OneSignalNotifier\OneSignalFacade;

$result = OneSignalFacade::setContent(['en' => 'Hello!'])
    ->setHeading(['en' => 'Test'])
    ->setSubscriptionIds(['subscription_id_1'])
    ->send();

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',
            ],
        ];
    }
}

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();

// 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 ['

// 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!
    ];
}

$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',
]);

$oneSignal->setPriority(10) // High priority
    ->setTtl(3600); // 1 hour TTL

$oneSignal->setIosInterruptionLevel('time-sensitive')
    ->setIosSound('default')
    ->setIosBadgeType('Increase')
    ->setIosBadgeCount(1)
    ->setIosCategory('message')
    ->setTargetContentIdentifier('message_123')
    ->setThreadId('chat_456')
    ->setIosRelevanceScore(5);

$oneSignal->setAndroidAccentColor('#FF0000')
    ->setAndroidChannelId('default')
    ->setAndroidGroup('chat_messages');

$oneSignal->setHuaweiChannelId('huawei_channel')
    ->setHuaweiCategory('message')
    ->setHuaweiMsgType('data')
    ->setHuaweiBiTag('tag1')
    ->setHuaweiAccentColor('#FF0000');

$oneSignal->setSubscriptionIds(['subscription_id_1', 'subscription_id_2']);

$oneSignal->setExternalUserIds(['user_123', 'user_456']);

$oneSignal->setOneSignalIds(['1589641e-bed1-4325-bce4-d2234e578884']);

$oneSignal->setPlayerIds(['player_id_1', 'player_id_2']);

$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',
    ],
]);

$oneSignal->setSendAfter(date('c', strtotime('+1 hour'))) // Send after 1 hour
    ->setDelayedOption('timezone') // or 'last-active'
    ->setDeliveryTimeOfDay('9:00AM');

// Add filters
$oneSignal->addFilter('first_session', 'first_session', '>', '1')
    ->addFilter('country', 'country', '=', 'US');

// Set segments
$oneSignal->setIncludedSegments(['Subscribed Users'])
    ->setExcludedSegments(['Inactive Users']);

$oneSignal->setCustomData([
    'message_id' => '12345',
    'sender' => 'John Doe',
    'type' => 'chat',
]);

$oneSignal->setData([
    'silent' => true,
    'action' => 'refresh',
]);

$oneSignal->setUrl('https://yourapp.com/messages/12345')
    ->setAppUrl('yourapp://messages/12345')
    ->setWebUrl('https://yourapp.com/web/messages/12345');

$oneSignal->setContentAvailable(true)
    ->setData(['silent' => true, 'action' => 'refresh']);

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";
}
bash
php artisan vendor:publish --tag=onesignal-notifier-config