Giter Site home page Giter Site logo

push-notifications-php's Introduction

Build Status

PHP SDK for Pusher Beams

PHP server library for publishing notifications through Pusher Beams.

Check https://docs.pusher.com/beams/reference/server-sdk-php for more information.

NOTE: This library requires a PHP version of 8.0 or greater

Installation

Get Composer, then get the pusher/pusher-push-notifications Composer package:

$ composer require pusher/pusher-push-notifications

This SDK depends on the JSON PHP module.

Use

Configuring the SDK for your instance

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

$pushNotifications = new \Pusher\PushNotifications\PushNotifications(array(
  "instanceId" => "YOUR_INSTANCE_ID_HERE",
  "secretKey" => "YOUR_SECRET_HERE",
));

Publishing to Device Interests

You can broadcast notifications to groups of subscribed devices using Device Interests:

$publishResponse = $pushNotifications->publishToInterests(
  ["donuts"],
  [
    "apns" => [
      "aps" => [
        "alert" => "Hello!",
      ],
    ],
    "fcm" => [
      "notification" => [
        "title" => "Hello!",
        "body" => "Hello, world!",
      ],
    ],
  ]
);

echo("Published with Publish ID: " . $publishResponse->publishId . "\n");

Publishing to Device Interests along with data

You can broadcast notifications with some data to groups of subscribed devices using Device Interests:

$publishResponse = $pushNotifications->publishToInterests(
  ["donuts"],
  [
    "apns" => [
      "aps" => [
        "alert" => "Hello!",
      ],
    ],
    "fcm" => [
      "notification" => [
        "title" => "Hello!",
        "body" => "Hello, world!",
      ],
      "data" => [
         "name" => "adam",
         "type" => "user",
      ],
    ],
  ]
);

echo("Published with Publish ID: " . $publishResponse->publishId . "\n");

Publishing to Authenticated Users

Securely send notifications to individual users of your application using Authenticated Users:

$publishResponse = $pushNotifications->publishToUsers(
  ["user-0001"],
  [
    "apns" => [
      "aps" => [
        "alert" => "Hello!",
      ],
    ],
    "fcm" => [
      "notification" => [
        "title" => "Hello!",
        "body" => "Hello, world!",
      ],
    ],
  ]
);

echo("Published with Publish ID: " . $publishResponse->publishId . "\n");

push-notifications-php's People

Contributors

benjamin-tang-pusher avatar binzram avatar jameshfisher avatar jonathanlloyd avatar qasim-nadeem avatar superdj avatar werelds 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

push-notifications-php's Issues

array_key_exists on php 74 and laravel

Hi
In PHP 7.4 the array_key_exists is deprecated and when I user package to send beams this error occurred:
ErrorException: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in C:\dev\app\Xampp\htdocs\www\projects\laravel\mrmmg\vendor\pusher\pusher-push-notifications\src\PushNotifications.php:95
is Any Solution to fix this?

Error

Fatal error: Uncaught Error: Class 'GuzzleHttp\Client' not found in /storage/ssd3/092/4712092/public_html/pusher-push-notifications/src/PushNotifications.php:26 Stack trace: #0 /storage/ssd3/092/4712092/public_html/notify.php(5): Pusher\PushNotifications\PushNotifications->__construct(Array) #1 {main} thrown in /storage/ssd3/092/4712092/public_html/pusher-push-notifications/src/PushNotifications.php on line 26

Laravel 8 pusher/pusher-push-notifications dependency issue with guzzlehttp/guzzle 6.0

Laravel 8 installation error with "pusher-push-notifications"

pusher/pusher-push-notifications 1.1.0 requires guzzlehttp/guzzle ~6.0 -> satisfiable by guzzlehttp/guzzle[6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.2.3, 6.3.0, 6.3.1, 6.3.2, 6.3.3, 6.4.0, 6.4.1, 6.5.0, 6.5.1, 6.5.2, 6.5.3, 6.5.4, 6.5.5, 6.5.x-dev] but these conflict with your requirements or minimum-stability.

Please update to support laravel8.

issues : Failed opening 'src/PushNotifications.php'

i have an issues on live server, but on local is running well.

[Message] include(): Failed opening 'src/PushNotifications.php' for inclusion (include_path='/var/www/dir1/dir2/api/vendor/pear/pear_exception:/var/www/dir1/dir2/api/vendor/pear/net_url2:.:/usr/share/php')

*note : I have installed it via composer

sending notification after, phone does not receive notification

Using the php sdk example pusher-push-notifications, the notification is successfully published, the publishid is returned, and the notification cannot be received on the mobile phone

Example:

require './vendor/autoload.php';

$pusherClient = new \Pusher\PushNotifications\PushNotifications([
    "instanceId" => "xxxxx-xxx-xxx-xxxxxxx,
    "secretKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
]);
$userId = "debug-hello";
$token = $pusherClient->generateToken($userId);

$publishResponse = $pusherClient->publishToInterests(
    array($userId, "hello"),
    array(
        "fcm" => array(
            "notification" => array(
                "title" => "Hi!",
                "body" => "This is my first Fcm Push Notification!"
            ),
            "data" => [
                "put" => "whatever",
                "you" => "need",
                "here" => "✨"
            ]
        ),
        "web" => array(
            "notification" => array(
                "title" => "Hi!",
                "body" => "This is my first Push Notification!"
            )
        )
    ));
var_dump($publishResponse);

getting error when use method

Fatal error: Uncaught Error: Call to undefined method Pusher\PushNotifications\PushNotifications::publishToInterests()

array_key_exists() expects parameter 2 to be array

I get following error when sending a notification

ErrorException: array_key_exists() expects parameter 2 to be array, null given in /var/www/EtenNewWeb/vendor/pusher/pusher-push-notifications/src/PushNotifications.php:59

my code:

public static function sendNotification($interest, $title, $body)
{
	try {
		$pushNotifications = new PushNotifications([
  			'instanceId' => env('PUSHER_PUSH_INSTANCE', null),
  			'secretKey' => env('PUSHER_PUSH_SECRET_KEY', null),
		]);

		$publishResponse = $pushNotifications->publish([$interest], [
			'apns' => [
				'aps' => [ 'alert' => $body ]
			],
			'fcm' => [
				'notification' => [
					'title' => $title,
					'body' => $body
				]
			]
		]);
	} catch (\Exception $e) {
		Log::error($e);
	}
}

Update:

Error was caused by an invalid instance-id. When I updated my code with correct instance-id it went away. But when instance-id is invalid it's easy if you can add a proper error message so it's easy to identify the error.
Thank You

Laravel - Queueing PushNotification gives Error (Serialization of 'Closure' is not allowed)

Hi,

when using the PushNotifications SDK (importing from Pusher\PushNotifications\PushNotifications) I can send web notifications to users with this code in a function of a route:

Route::get('test-notification', function() {
    $beamsClient = new PushNotifications(array(
        "instanceId" => env('PUSHER_BEAMS_INSTANCE_ID'),
        "secretKey" => env('PUSHER_BEAMS_SECRET_KEY')
    ));

    $publishId = $beamsClient->publishToUsers(
        array("user-3"),
        array(
            "web" => array(
                "notification" => array(
                    "title" => "New information in the app available",
                    "body" => "go to the app for more infor...",
                    "icon" => "https://app.familyportal.be/img/icons/favicon-32x32.png",
                    "deep_link" => "https://localhost:8080/#/news"
                )
            )
        )
    );
});

However when I put the same code in a Job and call that job with the dispatch function I get an error: Serialization of 'Closure' is not allowed.

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Pusher\PushNotifications\PushNotifications;

class SendNotification implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    public $retryAfter = 450;

    public function __construct()
    {
        $this->beamsClient = new PushNotifications(array(
            "instanceId" => env('PUSHER_BEAMS_INSTANCE_ID'),
            "secretKey" => env('PUSHER_BEAMS_SECRET_KEY')
        ));
    }

    public function handle()
    {
        $this->beamsClient->publishToUsers(
            array("user-3"),
            array(
                "web" => array(
                    "notification" => array(
                        "title" => "New information in the app available",
                        "body" => "go to the app for more infor...",
                        "icon" => "https://app.familyportal.be/img/icons/favicon-32x32.png",
                        "deep_link" => "https://localhost:8080/#/news"
                    )
                )
            )
        );
    }
}

Could be not totally related to this package (since it works in the first codeblock inside my routes/web.php') but I can't figure out why this is not working.

Updated composer.json to support firebase/php-jwt ^6

Version 6 of PHP-JWT is now released and the recommended version, is it possible to get this tested and bumped up as was done with Guzzle? We are currently unable to use due to a conflict.

pusher/pusher-push-notifications[1.1.1, ..., 1.1.2] require firebase/php-jwt ^5.0 -> found firebase/php-jwt[v5.0.0, ..., v5.5.1] but it conflicts with your root composer.json require (^6.0).

Android not receiving push notifications

Android is not receiving any notifications from php or the pusher dashboard debug console.
The login on android is a success but no notifications come through.
This is my server code

$beamsClient = new \Pusher\PushNotifications\PushNotifications(
  array(
    "instanceId" => "Instance_Id",
    "secretKey" => "Secret_Key",
  )
);

$beamsClient->publishToUsers(
  array("User_Id"),
  array(
    "fcm" => array(
      "notification" => array(
        "title" => "Hi!",
        "body" => "This is my first Push Notification!"
      )
    )
  )
);

This is my client code

PushNotifications.start(this, "Instance_Id")
        val tokenProvider = BeamsTokenProvider(
            "My_Server_Url",
            object: AuthDataGetter {
                override fun getAuthData(): AuthData {
                    return AuthData(
                        headers = hashMapOf(
                            "Authorization" to token
                        ),
                        queryParams = hashMapOf()
                    )
                }
            }
        )
        PushNotifications.setUserId(
            Firebase.auth.currentUser?.uid!!,
            tokenProvider,
            object : BeamsCallback<Void, PusherCallbackError> {
                override fun onFailure(error: PusherCallbackError) {
                    Log.e("BeamsAuth", "Could not login to Beams: ${error.message}")
                }

                override fun onSuccess(vararg values: Void) {
                    Log.i("BeamsAuth", "Beams login success")
                }
            }
        )

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.