Git Product home page Git Product logo

pusher-push-notifications's Introduction

Pusher Beams push notifications channel for Laravel 8.x & 9.x

Latest Version on Packagist Software License Build Status StyleCI SensioLabsInsight Quality Score Code Coverage Total Downloads

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

Please note that this notification channel should not be confused with Pusher Channels.

Also please note that prior to version 2.0, this package integrated with Pusher's beta push notifications service that was part of Pusher Channels. Please see Pusher's migration guide for more information.

Contents

Installation

You can install the package via composer:

composer require laravel-notification-channels/pusher-push-notifications

Setting up your Pusher account

Before using this package you should set up a Pusher Beams account. Here are the steps required.

  • Login to https://dash.pusher.com/
  • Select the "Beams" product.
  • Select your instance from the list or create a new instance.
  • Click on the "Settings" tab.
  • Upload your APNS Certificate and/or add your FCM Server key.
  • Now select the "Keys" tab.
  • Copy your Instance Id, and Secret Key.
  • Add a new entry to in your config/services.php file:
    'pusher' => [
        'beams_instance_id' => 'Your Instance Id',
        'beams_secret_key' => 'Your Secret Key',
    ],
  • You're now good to go.

Usage

Now you can use the channel in your via() method inside the Notification class.

use NotificationChannels\PusherPushNotifications\PusherChannel;
use NotificationChannels\PusherPushNotifications\PusherMessage;
use Illuminate\Notifications\Notification;

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

    public function toPushNotification($notifiable)
    {
        return PusherMessage::create()
            ->iOS()
            ->badge(1)
            ->sound('success')
            ->body("Your {$notifiable->service} account was approved!");
    }
}

Available Message methods

  • platform(''): Accepts a string value of iOS, Android or web.
  • iOS(): Sets the platform value to iOS.
  • android(): Sets the platform value to Android.
  • web(): Sets the platform value to web.
  • link(): Accepts a string value which will lead to URI specified on notification click.
  • title(''): Accepts a string value for the title.
  • body(''): Accepts a string value for the body.
  • sound(''): Accepts a string value for the notification sound file. Notice that if you leave blank the default sound value will be default.
  • icon(''): Accepts a string value for the icon file. (Android Only)
  • badge(1): Accepts an integer value for the badge. (iOS Only)
  • setOption($key, $value): Allows you to set any value in the message payload. See the request body section of the Pusher Beam docs for more information.

Sending to multiple platforms

You can send a single message to an iOS device and an Android device at the same time using the withiOS() and withAndroid() method:

public function toPushNotification($notifiable)
{
    $message = "Your {$notifiable->service} account was approved!";

    return PusherMessage::create()
        ->iOS()
        ->badge(1)
        ->body($message)
        ->withAndroid(
            PusherMessage::create()
                ->title($message)
                ->icon('icon')
        );
}
  • Notice that iOS is the default platform, which means you don't have to call ->iOS().
  • When using withAndroid(), withiOS() or withWeb() you don't have to define the platform, it's done behind the scenes for you.

Routing a message

By default, the pusher "interest" messages will be sent to will be defined using the {notifiable}.{id} convention, for example App.User.1, however you can change this behaviour by including a routeNotificationFor() in the notifiable class.

I.e. if you are pushing notification on User model, you can go to App\Models\User class and implement method:

public function routeNotificationForPusherPushNotifications($notification): string
{
    return 'your.custom.interest.string';
}

PusherPushNotifications() in the notifiable class method returns the interest name.

Publish to users

You can publish to users in the same way that you publish to interests but you must add the following variable to the notifiable model:

class Client extends Model
{
    use Notifiable;

    public $pushNotificationType = 'users';
}

Changelog

Please see CHANGELOG for more information 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.

pusher-push-notifications's People

Contributors

andreaselia avatar atymic avatar casperboone avatar freekmurze avatar fwartner avatar jessarcher avatar laravel-shift avatar mpociot avatar norgul avatar oyed avatar scybulski avatar sebastiandedeyne avatar stevethomas avatar superdj avatar themsaid avatar wanghanlin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pusher-push-notifications's Issues

Custom options not included in the payload

Hi,

Using Laravel and sending out a push notification like this:
PusherMessage::create()
->iOS()
->badge($this->post->user->notificationBadge())
->sound('success')
->title('New like')
->setOption('loc-key', 'test')
->setOption('loc-args', 'test')
->body('test');

The message is successfully sent, but the options are not included in the payload. Is this a bug or a problem with the above implementation?

Add scheduling

Need to add message scheduling before a 1.0.0 release

BadMethodCallException routeNotificationFor()

Hi, when i try to send my push notification i got this error:

Call to undefined method Illuminate\Database\Query\Builder::routeNotificationFor()

In my notification i have tried to insert

    use Notifiable;

    public function routeNotificationForPusherPushNotifications()
    {
        return 'interest_name';
    }

but the result it's the same.

Options is missing

Hi, I'm using setOptions method to send options to my app, but in my app I don't receive the field of options, how can this be solved?

heres my code in react native:

const handleNotification = notification => {
    console.log(notification, 'notification')
}

and here is the laravel part:

public function via($notifiable)
{
    return [PusherChannel::class];
}
public function toPushNotification($notifiable)
{
    $message = "You have a new message << {$this->title} >>";
    if ($this->date == now()->format('Y-m-d'))
    {
        $body = json_encode(some json);
    }else{
        $body = json_encode(some other json);
    }
    $d = PusherMessage::create()
        ->iOS()
        ->icon(url(public_path('img/icons/Messages.png')))
        ->badge(1)
        ->title($message)
        ->sound('success')
        ->setOption('id',1)
        ->body($body)->withAndroid(
            PusherMessage::create()
                ->setOption('id',1)
                ->body($body)
                ->title($message)
                ->icon(url(public_path('img/icons/Messages.png')))
        );
    dd($d);
}

Push Notification is not working when app is closed

Push Notification is not working when app is closed, is there something wrong with my code? because it doesn't work when the app is closed in recent apps.

public function toPushNotification($notifiable): PusherMessage
    {
        $interest = 'user-ali.' . $notifiable->id;

        $fcmPayload = [
            'notification' => [
                'title' => $this->adminNews->title,
                'body' => $this->adminNews->notes,
            ],
            'data' => [
                'click_action' => $this->adminNews->onclick_url,
            ],
        ];

        $apnsPayload = [
            'aps' => [
                'alert' => [
                    'title' => $this->adminNews->title,
                    'body' => $this->adminNews->notes,
                ],
                'badge' => 1,
                'sound' => '',
            ],
        ];

        $message = PusherMessage::create()
            ->title($this->adminNews->title)
            ->body($this->adminNews->notes)
            ->icon(public_path('svg/symbol.svg'))
            ->link($this->adminNews->onclick_url)
            ->setOption('interests', [$interest]);

        $messageAndroid = $message->setOption('fcm', $fcmPayload);

        return PusherMessage::create()
            ->iOS()
            ->badge(1)
            ->withAndroid($messageAndroid)
            ->withWeb($message)
            ->sound('')
            ->setOption('interests', [$interest])
            ->setOption('apns', $apnsPayload);
    }

Unauthorized: Incorrect Secret Key

i wrote a test,but every time execute it,i got same error,here is my code,

$users = [];
$beamsClient = new PushNotifications(array(
"instanceId" => config('services.pusher.beams_instance_id'),
"secretKey" => config('services.pusher.beams_secret_key'),
));
$tmp = User::where('role', 'client')->pluck('id')->toArray();
foreach ($tmp as $t){
$users[] = (string)$t;
}
$publishResponse = $beamsClient->publishToUsers(
$users,
array(
"fcm" => array(
"notification" => array(
"title" => "Test",
"body" => "This is a test"
),
"data" => array(
"key" => "This is a test"
)
),
"apns" => array("aps" => array(
"alert" => array(
"title" => "Test",
"body" => "This is a test"
)
))
));

    return ok($publishResponse,200);

how to solve it?

Error while installing !

Your requirements could not be resolved to an installable set of packages.

Problem 1
- laravel-notification-channels/pusher-push-notifications 1.0.1 requires pusher/pusher-php-server 2.5.0-rc4 -> satisfiable by pusher/pusher-php-server[v2.5.0-rc4] but these conflict with your requirements or minimum-stability.

even after installing Pusher PHP Library ^2.6
still get the same error message every time run 'composer require laravel-notification-channels/pusher-push-notifications'. any help ?

New Release?

Hey @themsaid,
Would you be able to get a new release tagged for this library so we can stop manually requiring an outdated version of the Pusher PHP Server library? I see you've already merged a commit updating the requirement to v2.6, but Packagist is still pulling the version requiring v2.5.0-RC4.

Thanks!

Error: Call to a member function create() on string in file vendor\laravel\framework\src\Illuminate\Notifications\Channels\DatabaseChannel.php on line 19

When adding this function to User model as descriped in your documentation here

   public function routeNotificationFor($channel)
{
    if($channel === 'PusherPushNotifications'){
        return 'your.custom.interest.string';
    }

    $class = str_replace('\\', '.', get_class($this));

    return $class.'.'.$this->getKey();
}

the error above comes by ๐Ÿ˜‘

and this is my via method in my notification

 public function via($notifiable)
    {
        return [PusherChannel::class , 'database'];
    }
    

Laravel 10 support

I recently worked with this package but not working in laravel v10.
The notification is not showing up.

Notifying Users

For the last days i have been trying to use this SDK to notify, for now, only one user that i hardcode the ID when i start the beams instance. Everything goes well when i notify the user id from the debug console on pusher beams.

The problem is, that i try to use this SDK in my notification process that is already sending email notifications, and the workflow goes in the public function toPushNotification($notifiable) but i never get a notification. I followed all the steps and i am only trying for web notification with this simple code:

image

Any help you can give me to make this work?

Push Notification is not working when app is closed (Android).

Push Notification is not working when app is closed.

According to Pusher Beams:

When your application is in the background, this service will not be called unless there is only a data payload in the notification. The notification key cannot be used.

But there is no way to send just data using this package. The 'notification' key always goes in 'fcm'.
Is there any way i can make the push notification work in background using this package?

How to get this working for guests?

I've been trying for a couple of hours now to send push messages to guests of our website, but no matter what I do it seems to run afoul of the way Laravel wants to work - that being, using some sort of Notifiable class, such as User.

Anyone have suggestions as to how to make this work?

Please add support for Android FCM client

I'd like to pushing to my Android FCM client
example use [pusher/pusher-php-server]

// Install the server library with:
//   composer require pusher/pusher-php-server

require __DIR__ . '/vendor/autoload.php';

$pusher = new Pusher\Pusher('APP_KEY', 'APP_SECRET', 'APP_ID', array('cluster' => 'APP_CLUSTER'));

$pusher->notify(
  array("donuts"),
  array(
    'fcm' => array(
      'notification' => array(
        'title' => 'hello world',
        'icon' => 'androidlogo'
      ),
    ),
  )
);

setOption key/value for APS's thread-id

I'm attempting to append a the payload reference key of "thread-id" Apple recommends as the remote equivalent to the local threadIdentifer (see here)

However, in attempting to string this together using the PusherMessage class, I am unable to see the thread-id make it's way to Pusher's debug console. I'm assuming I'm doing something wrong?

public function toPushNotification($notifiable) { return PusherMessage::create() ->iOS() ->badge(1) ->sound('default') ->setOption('thread-id', "id") ->body("the message"); }

toPushNotification not trigger

I'm trying to use pusher-push-notifications in Laravel 11, with a Vue 3 SPA, in a separate project. If I try to make the call with a Curl or an Http request, the notification is successful. The problem arises when I try to use the pusher-push-notifications functionalities.

`
$user = \App\Models\User::find(136);
$notifica = 'notifica';
try {
// $user->notify( new TestNotification($notifica));
\Illuminate\Support\Facades\Notification::send(User::all(), new TestNotification($notifica));

} catch (\Exception $e) {
    dd($e->getMessage());
}

notifica = $notifica; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return [PusherChannel::class ]; } public function toPushNotification($notifiable) { return PusherMessage::create() ->web() ->link(env('SPA_URL')) ->title('Titolo notifica') ->sound('success') ->body("Your {$notifiable->service} account was approved!"); } } ` Basically, the notification's via() method doesn't lead me to the next toPushNotification and therefore doesn't send the notification. Does anyone have any solutions?

How can i send a Notification to a specific User

Iยดm wondering how i can send Notifications to a specific User. The Auth Process is completely working and if i send a Notification from the Debug Console in the Pusher Backend it is also working but if i do the following:

Notification::send(User::all(), new ExampleNotification);

and the ExampleNotification looks like this:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\PusherPushNotifications\PusherChannel;
use NotificationChannels\PusherPushNotifications\PusherMessage;

class ExampleNotification extends Notification
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [PusherChannel::class];
    }

    
    public function toPushNotification($notifiable)
    {
        return PusherMessage::create()
            ->web()
            ->title("Test")
            ->body("Test");
    }

}

I do not receive a Notification on the registered Device and in the Pusher Debug Console it says Notification triggered to Users with Devices: 0 and Users: 0.

What exactly am i doing wrong?

Build isn't really passing

The builds at https://travis-ci.org/laravel-notification-channels/pusher-push-notifications show that the project is passing CI, but in actual fact the tests aren't being run!

No tests executed!

There are some warnings about the configuration file not passing validation, but I'm not sure if that's the actual cause for them not running.

I've checked out the project locally and run the tests, and found two of them are failing.

I'm looking at updating the library to use the Pusher Beams SDK, so I will try to fix these issues, but it's starting to look like a lot more more work than I'd anticipated.

'instanceId' must be a string

[2022-04-08 09:48:15] production.ERROR: 'instanceId' must be a string {"userId":35,"exception":"[object] (Exception(code: 0): 'instanceId' must be a string at /home/admin/myhost/vendor/pusher/pusher-push-notifications/src/PushNotifications.php:39)

I encountered this even after following the instructions to the later

production.ERROR: Driver [NotificationChannels\PusherPushNotifications\PusherChannel] not supported.

Hi,
I installed this package, it worked well on my local machine.

But after i deployed it to my server online and tried executing it.

It displays this error:

production.ERROR: Driver [NotificationChannels\PusherPushNotifications\PusherChannel] not supported. {"userId":20,"exception":"[object] (InvalidArgumentException(code: 0): Driver [NotificationChannels\\PusherPushNotifications\\PusherChannel] not supported. at */public_html/vendor/laravel/framework/src/Illuminate/Support/Manager.php:119)

Please help

Make PusherChannel::defaultName public static

I propose we make the defaultName function public static. That way we can use it to generate the beams token.

I want to use it like in the example below (I would place it inside my UserController).

    /**
     * Generate a Pusher Beams auth token to allow a user to associate their device with their user id.
     * The token is valid for 24 hours.
     *
     * @throws Exception
     *
     * @return array
     */
    public function generateBeamsToken()
    {
        $beamsClient = new PushNotifications([
            'instanceId' => Config::get('services.pusher.beams_instance_id'),
            'secretKey' => Config::get('services.pusher.beams_secret_key'),
        ]);

        return $beamsClient->generateToken(PusherChannel::defaultName(Auth::user()));
    }

Would that be ok? Can I submit the PR?

Or maybe there is another way of accomplishing this?

Will it work on Android/iOS when app is closed on mobile ?

Thanks guys for great package!

I have a question!
On web-app I can send and receive notifications while web-page is active.
But In mobile, I want to get notifications even if mobile app is closed. Will it work ? Or I will have to use pusher beams for that ?

How to get instance of beamsClient in route

I would like to ask you, how right get beamsClient in route for generating token.

At this moment, my implementation looks like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Pusher\PushNotifications\PushNotifications;

class BeamsController extends Controller
{

    protected $beamsClient;

    public function __construct()
    {

        $this->middleware('auth');

        $config = config('services.pusher');

        $this->beamsClient = new PushNotifications([
            'instanceId' => $config['beams_instance_id'],
            'secretKey' => $config['beams_secret_key'],
        ]);
    }

    public function index()
    {
        $user = Auth::user();
        $beamsToken = $this->beamsClient->generateToken('App.User.' . $user->id);
        return response()->json($beamsToken);
    }
}

I think, that Pusher\PushNotifications\PushNotifications should be registered in the Service provider to get instance with configurations. But, there is just booting. But, I'm not sure how exactly the Service provider in Laravel works.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.