Giter Site home page Giter Site logo

php-firebase-cloud-messaging's Introduction

PHP Firebase Cloud Messaging

PHP API for Firebase Cloud Messaging from Google.

Currently this app server library only supports sending Messages/Notifications via HTTP.

See original Firebase docs: https://firebase.google.com/docs/

#Setup Install via Composer:

composer require sngrl/php-firebase-cloud-messaging

Or add this to your composer.json and run "composer update":

"require": {
    "sngrl/php-firebase-cloud-messaging": "dev-master"
}

#Send message to Device

use sngrl\PhpFirebaseCloudMessaging\Client;
use sngrl\PhpFirebaseCloudMessaging\Message;
use sngrl\PhpFirebaseCloudMessaging\Recipient\Device;
use sngrl\PhpFirebaseCloudMessaging\Notification;

$server_key = '_YOUR_SERVER_KEY_';
$client = new Client();
$client->setApiKey($server_key);
$client->injectGuzzleHttpClient(new \GuzzleHttp\Client());

$message = new Message();
$message->setPriority('high');
$message->addRecipient(new Device('_YOUR_DEVICE_TOKEN_'));
$message
    ->setNotification(new Notification('some title', 'some body'))
    ->setData(['key' => 'value'])
;

$response = $client->send($message);
var_dump($response->getStatusCode());
var_dump($response->getBody()->getContents());

#Send message to multiple Devices

...
$message = new Message();
$message->setPriority('high');
$message->addRecipient(new Device('_YOUR_DEVICE_TOKEN_'));
$message->addRecipient(new Device('_YOUR_DEVICE_TOKEN_2_'));
$message->addRecipient(new Device('_YOUR_DEVICE_TOKEN_3_'));
$message
    ->setNotification(new Notification('some title', 'some body'))
    ->setData(['key' => 'value'])
;
...

#Send message to Topic

use sngrl\PhpFirebaseCloudMessaging\Client;
use sngrl\PhpFirebaseCloudMessaging\Message;
use sngrl\PhpFirebaseCloudMessaging\Recipient\Topic;
use sngrl\PhpFirebaseCloudMessaging\Notification;

$server_key = '_YOUR_SERVER_KEY_';
$client = new Client();
$client->setApiKey($server_key);
$client->injectGuzzleHttpClient(new \GuzzleHttp\Client());

$message = new Message();
$message->setPriority('high');
$message->addRecipient(new Topic('_YOUR_TOPIC_'));
$message
    ->setNotification(new Notification('some title', 'some body'))
    ->setData(['key' => 'value'])
;

$response = $client->send($message);
var_dump($response->getStatusCode());
var_dump($response->getBody()->getContents());

#Send message to multiple Topics

See Firebase documentation for sending to combinations of multiple topics.

...
$message = new Message();
$message->setPriority('high');
$message->addRecipient(new Topic('_YOUR_TOPIC_'));
$message->addRecipient(new Topic('_YOUR_TOPIC_2_'));
$message->addRecipient(new Topic('_YOUR_TOPIC_3_'));
$message
    ->setNotification(new Notification('some title', 'some body'))
    ->setData(['key' => 'value'])
    // Will send to devices subscribed to topic 1 AND topic 2 or 3
    ->setCondition('%s && (%s || %s)')
;
...

#Subscribe user to the topic

use sngrl\PhpFirebaseCloudMessaging\Client;

$server_key = '_YOUR_SERVER_KEY_';
$client = new Client();
$client->setApiKey($server_key);
$client->injectGuzzleHttpClient(new \GuzzleHttp\Client());

$response = $client->addTopicSubscription('_SOME_TOPIC_ID_', ['_FIRST_TOKEN_', '_SECOND_TOKEN_']);
var_dump($response->getStatusCode());
var_dump($response->getBody()->getContents());

#Remove user subscription to the topic

use sngrl\PhpFirebaseCloudMessaging\Client;

$server_key = '_YOUR_SERVER_KEY_';
$client = new Client();
$client->setApiKey($server_key);
$client->injectGuzzleHttpClient(new \GuzzleHttp\Client());

$response = $client->removeTopicSubscription('_SOME_TOPIC_ID_', ['_FIRST_TOKEN_', '_SECOND_TOKEN_']);
var_dump($response->getStatusCode());
var_dump($response->getBody()->getContents());

php-firebase-cloud-messaging's People

Contributors

johann59 avatar sngrl 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  avatar  avatar

php-firebase-cloud-messaging's Issues

loading client in controller throws and error

loading client in controller throws an error on live server and don't send notifications, while it send notifications normally locally and on staging server. any clue?

here's the live server error:
request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\ClassNotFoundException: "Attempted to load class "Client" from namespace "sngrl\PhpFirebaseCloudMessaging". Did you forget a "use" statement for e.g. "Symfony\Component\HttpKernel\Client", "Symfony\Component\BrowserKit\Client", "Symfony\Bundle\FrameworkBundle\Client" or "GuzzleHttp\Client"?" at /var/www/ibus/src/AppBundle/Controller/DriverController.php line 207 {"exception":"[object](Symfony\Component\Debug\Exception\ClassNotFoundException%28code: 0%29: Attempted to load class "Client" from namespace "sngrl\PhpFirebaseCloudMessaging".nDid you forget a "use" statement for e.g. "Symfony\Component\HttpKernel\Client", "Symfony\Component\BrowserKit\Client", "Symfony\Bundle\FrameworkBundle\Client" or "GuzzleHttp\Client"? at /var/www/ibus/src/AppBundle/Controller/DriverController.php:207)"} []

Directions need a little clarity

So I installed everything and your directions show code on how to interact, but are these code abstracts that you provided supposed to be put into Client.php, or do I need to create individual files and include the code there, or do I just add $server_key = 'hjahfh'; to the client.php file?

Token Suscripcion not response

Hello, I using the lib, but when suscribe a client to a topic, this dont reply any.

$response=$client->addTopicSubscription('GROUP' . $user->getGrupo()->getId(), [$user->getToken()]);

$user->getGrupo()->getId()=2
[$user->getToken()] = [dGi1kW52if8:APA91bFQ3LfgDr6ogK_2412Vfwytyn_q....]

I get this reply

Response Code = 200
Response Reply = {"results":[{}]}

Stability

Is there a particular reason the stability of this repo is dev, rather than stable?

Background android notification

If I sent the notification to an individual devices as shown in the documentation, if the app is background and we click on it in the noitification section the app does not open.

I have tried everything, please help!

How can I add custom cURL options?

Hi.

I need add CURLOPT_SSL_VERIFYPEER option

How can I do it in this code:

$client = new Client();
$client->setApiKey($server_key);
$client->injectGuzzleHttpClient(new \GuzzleHttp\Client());

I found this in the Guzzle documentation but I can not apply it

$client->request('GET', '/', [
    'curl' => [
        CURLOPT_INTERFACE => 'xxx.xxx.xxx.xxx'
    ]
]);

Thank you!!!

IOS Mutable Content

To control the push in IOS you need the firebase added support for a new parameter.

mutable-content = true

How do I send this parameter?

is it possible to update with support for this parameter?

Token Infos

Hi all

Possible to add something like this? That gives you information about a token...

public function tokenInfos($token) {
$url = 'https://iid.googleapis.com/iid/info/' . $token . '?details=true';

return $this->guzzleClient->get(
  $url,
  [
    'headers' => [
      'Authorization' => sprintf('key=%s', $this->apiKey),
      'Content-Type' => 'application/json'
    ],
    'body' => ''
  ]
);

}

Thank you for your answer

composer error

[InvalidArgumentException]
Could not find package sngrl/php-firebase-cloud-messaging at any version for your minimum-stability (stable). Check
the package spelling or your minimum-stability

Add version tags?

What about adding version tags? Composer advises avoid using master branches and I strongly agreed with this.

How to get push notification from website subscribing topic?

Hi, thanks a lot for such a great package. It is really a very helpful one. I want to use this package to send fcm cloud message from my website to android and ios device and also to website.

I have found addRecipient message method to send message to topic and addTopicSubscription client method to subscribe the topic but this method also asking recipients_tokens. But I don't want to pass any recipients token just want to subscribe the topic so that devices and web site can get notification, is it possible? and if recipient tokens required how can I manage for website and devices?

Cannot install php-firebase-cloud-messaging?

This is my composer.json

{
        "require": {
                "snglr/php-firebase-cloud-messaging":"dev-master"
        }
}

When I ran composer update, I got:

Problem 1
- The requested package snglr/php-firebase-cloud-messaging could not be found in any version, there may be a typo in the package name.

Potential causes:

setSound is not working

Hi,
I'm trying to change the sound but it does not work.
I think it only works the 'default':

1°) $notif->setSound('default');
2°) $notif->setSound('ringtone');
3°) $notif->setSound('siren');

I am using PHP 5.6

Deprecated: Return type Message::jsonSerialize()

Hi, I use your example to send a notification to a device but I get this error, could you help me? Thanks!

Deprecated: Return type of sngrl\PhpFirebaseCloudMessaging\Message::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in \vendor\sngrl\php-firebase-cloud-messaging\src\Message.php on line 160.

Code:

use sngrl\PhpFirebaseCloudMessaging\Client;
use sngrl\PhpFirebaseCloudMessaging\Message;
use sngrl\PhpFirebaseCloudMessaging\Recipient\Topic;
use sngrl\PhpFirebaseCloudMessaging\Notification;

$defaults = array(
    "title"        => "Mi titulo",
    "body_message" => "Mi mensaje",
    "priority"     => "normal",
    "device_token" => "1234567890",
);

extract($defaults);
require __DIR__.'/vendor/autoload.php';

$client = new Client();
$client->setApiKey($server_key);
$client->injectGuzzleHttpClient(new \GuzzleHttp\Client());

$message = new Message();
$message->setPriority($priority);
$message->addRecipient(new Device($device_token));
$message->setNotification(new Notification($title, $body_message));
$message->setData(array(
    "title" => $title,
    "body"  => $body_message,
));
try {
    $response = $client->send($message);
} catch (Exception $e) {
    echo $e->getMessage();
}

how to use fcm_options.link ?

Hi,
Nice composer lib :)
I want just to ask you how can I customize the message with a link, image and some details.
I couldn't find any reference in the documentation.

Thanks in advance,

Android sound Android O+

For android 26+ setting sound doesn't work anymore. We need to create a channel on android.
So, this code not gonna work on newer versions of android.
$notification->setSound('police.wav');
this will
$notification->setSound('police.wav'); //old versions of android and ios $notification->setJsonKey('android_channel_id', 'noti_push_app_1'); //new android
Maybe, we could have something like
$notification->setSound('police.wav', 'noti_push_app_1' /*this part not been required*/);
or
$notification->setChannelId('noti_push_app_1');

Set message priority=high in readme

I spent a fair amount of time trying to determine why my messages were not being delivered to my device. $response->getStatusCode() always returned status 200, but messages would not show up. I finally discovered that setting $message->setPriority('high') resolved my testing issues. I would suggest highlighting the priority setting within the sample code in README.md. I'm happy to submit a PR for the text change if you prefer.

Send to all user from the app segment

Hi! This is a great and awesome simple package.. thank you!
I want to send notifications to all users from an app, using the app segmentation.. How can i do this?

How to send an Image through notification or data message type?

I have tried the following code.

$message = new Message();
$message->setPriority('high');
$message->addRecipient(new Device('DEVICE_TOKEN'));
$message
->setNotification(new Notification('Notification Title', 'Notification Body',"Image_URL"));
//->setData(['key' => 'value']);
$response = $client->send($message);

Token problem

Hi,

I've got this error when I try to send a push notification :

JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.

I don't see how to fix it

Thanks

time_to_live - how do you set it?

Hi,

Thanks for the amazing plugin, it's really helped in us implementing FCM through PHP.

I'm trying to look at a way to set 'time_to_live' through the options but can't seem to get it working through
$message->setJsonKey('time_to_live', 0);

Also i have some messages having content_available with setJsonKey, can we do
$message->setJsonKey(array("content_available" => true, "time_to_live" => 0));
??

I couldn't seem to see any reference for setJsonKey in any documentation for this repo but i know it's within FCM docs.

Thanks,

Lew.

Body of notification not sent

In Notification::jsonSerialize there is an error, causing "body" not to be added to jsonData if there is no title set

public function jsonSerialize()
    {
...
        if ($this->title) {
            $jsonData['body'] = $this->body;
        }

status received success but not received notification on mobile device

I have followed all the steps, as you suggested in read me file to send 'Send message to device' message. System responded as

"{"multicast_id":3140234907049917302,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1598431478755153%27e9163c27e9163c"}]}"

but i did not receive any notification on my mobile device which device token i set in configuration.

Is message delivered immediately or it takes time as per message queue on server up to 4 weeks by default? Please suggest what is the issue? 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.