This package makes it easy to send web push notifications with Laravel.

Overview

Web push notifications channel for Laravel

Latest Version on Packagist Build Status Quality Score Code Coverage Total Downloads

This package makes it easy to send web push notifications with Laravel.

Installation

You can install the package via composer:

composer require laravel-notification-channels/webpush

First add the NotificationChannels\WebPush\HasPushSubscriptions trait to your User model:

use NotificationChannels\WebPush\HasPushSubscriptions;

class User extends Model
{
    use HasPushSubscriptions;
}

Next publish the migration with:

php artisan vendor:publish --provider="NotificationChannels\WebPush\WebPushServiceProvider" --tag="migrations"

Run the migrate command to create the necessary table:

php artisan migrate

You can also publish the config file with:

php artisan vendor:publish --provider="NotificationChannels\WebPush\WebPushServiceProvider" --tag="config"

Generate the VAPID keys (required for browser authentication) with:

php artisan webpush:vapid

This command will set VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEYin your .env file.

These keys must be safely stored and should not change.

If you still want support for Google Cloud Messaging, set the GCM_KEY and GCM_SENDER_ID in your .env file.

Usage

Now you can use the channel in your via() method inside the notification as well as send a web push notification:

use Illuminate\Notifications\Notification;
use NotificationChannels\WebPush\WebPushMessage;
use NotificationChannels\WebPush\WebPushChannel;

class AccountApproved extends Notification
{
    public function via($notifiable)
    {
        return [WebPushChannel::class];
    }

    public function toWebPush($notifiable, $notification)
    {
        return (new WebPushMessage)
            ->title('Approved!')
            ->icon('/approved-icon.png')
            ->body('Your account was approved!')
            ->action('View account', 'view_account')
            ->options(['TTL' => 1000]);
            // ->data(['id' => $notification->id])
            // ->badge()
            // ->dir()
            // ->image()
            // ->lang()
            // ->renotify()
            // ->requireInteraction()
            // ->tag()
            // ->vibrate()
    }
}

You can find the available options here.

Save/Update Subscriptions

To save or update a subscription use the updatePushSubscription($endpoint, $key = null, $token = null, $contentEncoding = null) method on your user:

$user = \App\User::find(1);

$user->updatePushSubscription($endpoint, $key, $token, $contentEncoding);

The $key and $token are optional and are used to encrypt your notifications. Only encrypted notifications can have a payload.

Delete Subscriptions

To delete a subscription use the deletePushSubscription($endpoint) method on your user:

$user = \App\User::find(1);

$user->deletePushSubscription($endpoint);

Browser Compatibility

See the Push API browser compatibility.

Changelog

Please see CHANGELOG for more information about what has changed recently.

Testing

$ composer test

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • max execution time

    max execution time

    I'm sending lots of push messages at one (around 5.000) and I'm getting the error: Symfony\Component\Debug\Exception\FatalErrorException: Maximum execution time of 120 seconds exceeded in vendor/mdanter/ecc/src/Math/GmpMath.php:34

    Any idea how I can solve that?

    opened by iamgoodbytes 16
  • Send additional data / payload

    Send additional data / payload

    Is it possible to send additional data with the push message, besides the following five attributes?

    return WebPushMessage::create()
                // ->id($notification->id)
                ->title( $this->notification_data['push_title'] )
                ->icon( $this->notification_data['push_icon'] )
                ->body( $this->notification_data['push_body'] );
    //            ->action('View account', 'view_account');
    

    What I'm trying to do is send a user picked URL to the push notification, so that I can respond by opening up that specific URL when a user clicks on the notification.

    Thanks again for the great job you did with this library!

    opened by iamgoodbytes 13
  • Rows Deleted

    Rows Deleted

    Hi, I have an issue, when I send the notification to all users some rows deleted in the push_subscriptions table without any reason, including my mobile maybe I was turning off the internet when the notification sent , and when I compare users table and push_subscriptions table I found more than 80 records missing, please how can I disable the deletion procedures in push_subscriptions?

    enhancement 
    opened by ahmedalmulki 9
  • 403 Forbiden on Apple Safari

    403 Forbiden on Apple Safari

    Hello, I've been testing implementing this package in a project that implements an SPA and API. It works well until we test on Safari.

    The error I receive: POST https://web.push.apple.com/IDENTIFIERresulted in a403 Forbidden` response: {"reason":"BadJwtToken"}

    I've researched into the reasons Apple provide for such here, yet I am not able to find a reason for it not to work :/

    // env keys
    VAPID_SUBJECT='http://localhost:8080' # Frontend URL for testing Service workers
    VAPID_PUBLIC_KEY="MY-PUBLIC-KEY"
    VAPID_PRIVATE_KEY="MY-PRIVATE-KEY"
    

    According to a comment with the underlying library it should work without any changes. Read here.

    Is someone able to help out?

    Regards, Rodrigo

    opened by imrodrigoalves 8
  • In ECKey.php line 148:    Unable to create the key  -> php artisan webpush:vapid

    In ECKey.php line 148: Unable to create the key -> php artisan webpush:vapid

    getting error:

    $ php artisan webpush:vapid
    
       RuntimeException  : Unable to create the key
    
      at E:\laravel-webpush\vendor\web-token\jwt-core\Util\ECKey.php:148 
        144|             'curve_name' => self::getOpensslCurveName($curve),
        145|             'private_key_type' => OPENSSL_KEYTYPE_EC,
        146|         ]);
        147|         if (false === $key) {
      > 148|             throw new RuntimeException('Unable to create the key');
        149|         }
        150|         $result = openssl_pkey_export($key, $out);
        151|         if (false === $result) {
        152|             throw new RuntimeException('Unable to create the key');
    
      Exception trace:
    
      1   Jose\Component\Core\Util\ECKey::createECKeyUsingOpenSSL("P-256")
          E:\laravel-webpush\vendor\web-token\jwt-core\Util\ECKey.php:110
      2   Jose\Component\Core\Util\ECKey::createECKey("P-256", [])
          E:\laravel-webpush\vendor\web-token\jwt-key-mgmt\JWKFactory.php:75
    

    when running php artisan webpush:vapid.

    Laravel Framework 6.18.0

    opened by metalsadman 8
  • Chrome displays

    Chrome displays "Site updated in background" unless payload is wrapped in a "notification" property

    I was having issues where my notifications wouldn't display if my site was in the background. It would just display "This site has updated in the background."

    I made the following changes to WebPushChannel.php and it started working as expected:

    Lines 37-38

    $payload = ['notification' => $notification->toWebPush($notifiable, $notification)->toArray()];
    $payload = json_encode($payload);
    
    opened by Mattnmoore 8
  • \Safe\Resource error when installing package

    \Safe\Resource error when installing package

    PHP : 8.1 Laravel 9

    When installing, I'm getting the followig warning and error

    PHP Warning: "resource" is not a supported builtin type and will be interpreted as a class name. Write "\Safe\resource" or import the class with "use" to suppress this warning in D:\xampp\htdocs\rland\vendor\thecodingmachine\safe\generated\sockets.php

    integer" will be interpreted as a class name. Did you mean "int"? Write "\Safe\integer" or import the class with "use" to suppress this warning

    opened by dkvhin 7
  • Call to undefined method Brick\\Math\\BigInteger::getX()

    Call to undefined method Brick\\Math\\BigInteger::getX()

    Pushing notification gives Error log:

    "message": "Call to undefined method Brick\\Math\\BigInteger::getX()",
        "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
        "file": "E:\\laravel-web-push-demo\\vendor\\minishlink\\web-push\\src\\Encryption.php",
        "line": 99,
    ...
    

    https://github.com/web-push-libs/web-push-php/issues/295 Laravel Framework 6.18.0 webpush: latest

    opened by metalsadman 7
  • Laravel 6 Missing

    Laravel 6 Missing "subscribable_id"

    Hello,

    I've installed webpush 5.0 and I got this error : "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'push_subscriptions.subscribable_id'"

    It seems the column is not in the migration file. Did I miss something?

    Thank you

    opened by BriBarthelemy 7
  • Problem with notification content

    Problem with notification content

    Hi, I'm having a problem with notifications.

    Be aware that I'm using Lumen, not Laravel. I installed and configured anything I needed to make this library working with Lumen (at least I think so)

    What works:

    • Subscriptions are correctly saved in the Database.
    • When I do $user->pushSubscriptions on a test user, it shows me the correct data.
    • Notifications are SENT, i receive them on chrome desktop or chrome android.

    Problem : BUT, I have no content in the notifications. The only infos I have in the notifications are:

    • app url
    • "This site has been updated in the background" message

    It looks like to me that no content is added on the payload, and maybe that's why chrome just display a default message

    NotificationController.php send() function (my entry point in the router to send my test notifications):

    public function send()
        {
            $user = User::find('2');
            $user->notify(new PushNotification);
            return response()->json('test', 201);
        }
    

    PushNotification class (some parts of it):

    public static function via($notifiable)
    {
        return [WebPushChannel::class];
    }
    
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'title' => 'Hello from Laravel!',
            'body' => 'Thank you for using our application.',
            'action_url' => 'https://laravel.com',
            'created' => Carbon::now()->toIso8601String()
        ];
    }
    
    /**
     * Get the web push representation of the notification.
     *
     * @param  mixed  $notifiable
     * @param  mixed  $notification
     * @return \Illuminate\Notifications\Messages\DatabaseMessage
     */
    public function toWebPush($notifiable, $notification)
    {
        return (new WebPushMessage)
            ->title('Approved!')
            ->icon('/approved-icon.png')
            ->body('Your account was approved!')
            ->action('View account', 'view_account');
        // ->data(['id' => $notification->id])
        // ->badge()
        // ->dir()
        // ->image()
        // ->lang()
        // ->renotify()
        // ->requireInteraction()
        // ->tag()
        // ->vibrate()
    }
    

    As you can see, I tried to do exactly like in the example.

    I have been spending hours trying to make it work, with no success. Any help would be greatly appreciated.

    opened by AlexandreVaudelin 7
  • When generating VAPID keys getting an error

    When generating VAPID keys getting an error

    When trying to generate VAPID keys on the terminal, I got an error: "Unable to create the key". error

    Using: Laravel: 8.x, PHP: 7.4 Any suggestions?

    opened by DomantasDielektrik 6
  • Warnings when running on Laravel 9.x and PHP 8

    Warnings when running on Laravel 9.x and PHP 8

    This is a warning that I get when I run php artisan while having this package:

    
    PHP Warning:  "resource" is not a supported builtin type and will be interpreted as a class name. Write "\Safe\resource" or import the class with "use" to suppress this warning in /var/www/html/vendor/thecodingmachine/safe/generated/sockets.php on line 797
    PHP Warning:  "integer" will be interpreted as a class name. Did you mean "int"? Write "\Safe\integer" or import the class with "use" to suppress this warning in /var/www/html/vendor/thecodingmachine/safe/generated/swoole.php on line 17
    

    When I remove laravel-notification-channels/webpush the warnings stop.

    It's caused by this package: web-token/jwt-util-ecc on version 2.x

    opened by Al-bambino 2
  • iOS implementation ❓

    iOS implementation ❓

    Hi, i tried this package with Chrome and Firefox for PC / Android and it works fine, but for iOS (Safari, Chrome or Firefox) there is not even the pop up to ask for puhs notifications. How can I solve?

    opened by MaxRomagnoli 1
  • action function ❓

    action function ❓

    Hi, how ->action('View account', 'view_account') supposed to work? In Laravel notification should be a url, but if I try it the button appears but does nothing

    opened by MaxRomagnoli 1
  • Allow to set WebPush automatic padding in config

    Allow to set WebPush automatic padding in config

    To support Firefox Android, automatic padding applied by WebPush has to be disabled: https://github.com/web-push-libs/web-push-php#how-can-i-disable-or-customize-automatic-padding

    This PR just applies the default 3052 bytes but you can set automatic_padding to false to support Firefox Android

    Fix for https://github.com/laravel-notification-channels/webpush/issues/103#issuecomment-1205132556

    opened by goaround 1
  • Error Message: ReportHandlerInterface is not instantiable while building WebPushChannel

    Error Message: ReportHandlerInterface is not instantiable while building WebPushChannel

    I followed the steps described on documentation to send notifications in an API Controller with webpush, but I keep receiving this message output:

    "message": "Target [NotificationChannels\WebPush\ReportHandlerInterface] is not instantiable while building [NotificationChannels\WebPush\WebPushChannel].", "exception": "Illuminate\Contracts\Container\BindingResolutionException", "file": "/web/htdocs/www.sglive.it/home/apidev/project/vendor/laravel/framework/src/Illuminate/Container/Container.php", "line": 1087,

    Any idea on how to solve this?

    opened by Raylis 0
Releases(7.0.0)
Owner
Laravel Notification Channels
A collection of custom notification drivers for Laravel
Laravel Notification Channels
A PHP Library to easily send push notifications with the Pushwoosh REST Web Services.

php-pushwoosh A PHP Library to easily send push notifications with the Pushwoosh REST Web Services. First sample, creating a Pushwoosh message // Crea

gomoob 63 Sep 28, 2022
WebPush can be used to send notifications to endpoints which server delivers Web Push

WebPush can be used to send notifications to endpoints which server delivers Web Push notifications as described in the Web Push protocol. As it is standardized, you don't have to worry about what server type it relies on.

null 1.5k Jan 7, 2023
Larafirebase is a package thats offers you to send push notifications or custom messages via Firebase in Laravel.

Introduction Larafirebase is a package thats offers you to send push notifications or custom messages via Firebase in Laravel. Firebase Cloud Messagin

Kutia Software Company 264 Jan 7, 2023
Send Firebase push notifications with Laravel php framework.

FCM Notification Channel for Laravel Send Firebase push notifications with Laravel php framework. Installation You can install this package via compos

Ankur Kumar 23 Oct 31, 2022
Send push notifications to apple devices (iPhone, iPad, iPod).

Apple Apn Push Send push notifications to apple devices (iPhone, iPad, iPod). Support authenticators: Certificate Json Web Token Supported protocols:

Vitaliy Zhuk 157 Dec 1, 2022
Standalone PHP library for easy devices notifications push.

NotificationPusher Standalone PHP library for easy devices message notifications push. Feel free to contribute! Thanks. Contributors Cédric Dugat (Aut

Cédric Dugat 1.2k Jan 3, 2023
Standalone PHP library for easy devices notifications push.

NotificationPusher Standalone PHP library for easy devices message notifications push. Feel free to contribute! Thanks. Contributors Cédric Dugat (Aut

Cédric Dugat 1.2k Jan 3, 2023
Laravel package to enable sending push notifications to devices

Laravel Push Notification Package to enable sending push notifications to devices Installation Update your composer.json file to include this package

Davi Nunes 1.2k Sep 27, 2022
Push Notifications using Laravel

laravel-push-notification Push Notifications using Laravel PushNotification::send(['deviceToken1', 'deviceToken2',..], 'Notification Message', 'Action

Webelight Solutions 26 Jul 22, 2022
Takes care of Apple push notifications (APNS) in your PHP projects.

Notificato Notificato takes care of push notifications in your PHP projects. Italian: notificato è: participio passato English: notified Why use Notif

Mathijs Kadijk 223 Sep 28, 2022
Push notifications Library for PHP

Push notifications Library for PHP Supported Protocols Protocol Supported Driver Options APNs (Token Based) ✓ APNs\Token APNs\Token\Option APNs (Certi

Norifumi SUNAOKA 3 Dec 14, 2022
Takes care of Apple push notifications (APNS) in your PHP projects.

Notificato Notificato takes care of push notifications in your PHP projects. Italian: notificato è: participio passato English: notified Why use Notif

Mathijs Kadijk 223 Sep 28, 2022
This package allows you to send notifications to Microsoft Teams.

Teams connector This package allows you to send notifications to Microsoft Teams. Installation You can install the package using the Composer package

skrepr 20 Oct 4, 2022
:computer: Send notifications to your desktop directly from your PHP script

About JoliNotif JoliNotif is a cross-platform PHP library to display desktop notifications. It works on Linux, Windows or MacOS. Requires PHP >= 7.2 (

JoliCode 1.2k Dec 29, 2022
Notifications in PHP (notify-send, growl, etc) like that.

#Nod Notifications in PHP (notify-send, growl, etc) like that. ##Examples Letting Nod figure out the best Adapter to use (not recommend ATM, only work

Filipe Dobreira 51 Mar 26, 2019
Service that helps you to send notifications for a series of failed exceptions.

Laravel Failure Notifier This package helps you to track your exceptions and do what you want to do with them such as sending an SMS or and Email. You

Kamyar Gerami 7 Nov 26, 2022
It's Pimcore Bundle to send notifications to Google Chat, Slack or Email from admin panel inside Pimcore

Send notifications to Discord, Google Chat, Slack and more from Pimcore It's Pimcore Bundle to send notifications to Discord, Google Chat, Slack, Tele

LemonMind.com 6 Aug 31, 2022
ApnsPHP: Apple Push Notification & Feedback Provider

ApnsPHP: Apple Push Notification & Feedback Provider A full set of open source PHP classes to interact with the Apple Push Notification service for th

Immobiliare Labs 1.4k Nov 16, 2022
Send SMS with easy using BEEM

beem-sms-api Send SMS with easy using BEEM Installation You must be using composer to be able to use this library. If composer 1.x is installed, make

Hosanna Higher Technologies 4 Dec 24, 2021