Giter Site home page Giter Site logo

edujugon / pushnotification Goto Github PK

View Code? Open in Web Editor NEW
476.0 16.0 153.0 173 KB

PHP and Laravel Package to send push notifications to Android and IOS devices.

License: MIT License

PHP 100.00%
laravel pushnotification push-notifications gcm fcm apns notification-channel laravel-notification-channels

pushnotification's Introduction

PushNotification Package

Build Status Total Downloads Latest Stable Version License

This is an easy to use package to send push notification.

Push Service Providers Available:

  • GCM
  • FCM
  • APN

Installation

Laravel version below 5.8

type in console:

composer require "edujugon/push-notification:^v3.0.0"

Laravel 5.8/6 and higher

type in console:

composer require edujugon/push-notification

The package will automatically register its service provider.

Publish the package's configuration file to the application's own config directory

php artisan vendor:publish --provider="Edujugon\PushNotification\Providers\PushNotificationServiceProvider" --tag="config"

Go to laravel facade sample directly.

Configuration

After publishing the configuration, you can find the Push service config in config/pushnotification.php

The default configuration parameters for GCM and FCM are :

  • priority => normal
  • dry_run => false
  • apiKey => Your ApiKey

You can dynamically update those values or adding new ones calling the method setConfig like so:

$push->setConfig([
    'priority' => 'high',
    'dry_run' => true,
    'time_to_live' => 3
]);

The default configuration parameters for APN are:

  • certificate => __DIR__ . '/iosCertificates/yourCertificate.pem'
  • passPhrase => 'MyPassPhrase'
  • passFile => __DIR__ . '/iosCertificates/yourKey.pem' //Optional
  • dry_run => false

(Make sure to set dry_run to true if you're using development *.pem certificate, and false for production)

Also you can update those values and add more dynamically

$push->setConfig([
    'passPhrase' => 'NewPass',
    'custom' => 'MycustomValue',
    'dry_run' => true
]);

Even you may update the url of the Push Service dynamically like follows:

$push->setUrl('http://newPushServiceUrl.com');

Not update the url unless it's really necessary.

You can specify the number of client-side attempts to APN before giving up. The default amount is 3 attempts. You can override this value by specifying connection_attempts in setConfig() assoc-array. Keep in mind the default number of requested attempts is 3.

If you prefer to retry indefinitely, set connection_attempts to zero.

$push->setConfig([
    'passPhrase' => 'NewPass',
    'custom' => 'MycustomValue',
    'connection_attempts' => 0,
    'dry_run' => true
]);

Usage

$push = new PushNotification;

By default it will use GCM as Push Service provider.

For APN Service:

$push = new PushNotification('apn');

For FCM Service:

$push = new PushNotification('fcm');

Now you may use any method that you need. Please see the API List.

API List

Only for Gcm and Fcm

Only for Fcm

Go to Usage samples directly.

setService

setService method sets the push service to be used, which you pass the name through parameter as a string.

Syntax

object setService($name)

setMessage

setMessage method sets the message parameters, which you pass the values through parameter as an array.

Syntax

object setMessage(array $data)

setApiKey

Only for gcm and fcm

setApiKey method sets the API Key of your App, which you pass the key through parameter as a string.

Syntax

object setApiKey($api_key)

setDevicesToken

setDevicesToken method sets the devices' tokens, which you pass the token through parameter as array or string if it was only one.

Syntax

object setDevicesToken($deviceTokens)

send

send method sends the notification.

Syntax

object send()

getFeedback

getFeedback method gets the notification response, which you may use it chaining it to send method or call it whenever after sending a notification.

Syntax

object getFeedback()

getUnregisteredDeviceTokens

getUnregisteredDeviceTokens method gets the devices' tokens that couldn't receive the notification because they aren't registered to the Push service provider. You may use it chaining it to send method or call it whenever after sending a notification.

Syntax

array getUnregisteredDeviceTokens()

setConfig

setConfig method sets the Push service configuration, which you pass the name through parameter as an array.

Syntax

object setConfig(array $config)

setUrl

setUrl method sets the Push service url, which you pass the name through parameter as a string.

Syntax

object setUrl($url)

Not update the url unless it's really necessary.

sendByTopic

Only for fcm

sendBytopic method sends a message by topic. It also accepts the topic condition. more details here

If isCondition is true, $topic will be treated as an expression

Syntax

object sendByTopic($topic,$isCondition)

Usage samples

You can chain the methods.

GCM sample:

$push->setMessage([
        'notification' => [
                'title'=>'This is the title',
                'body'=>'This is the message',
                'sound' => 'default'
                ],
        'data' => [
                'extraPayLoad1' => 'value1',
                'extraPayLoad2' => 'value2'
                ]
        ])
        ->setApiKey('Server-API-Key')
        ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...]);

APN sample:

$push->setMessage([
            'aps' => [
                'alert' => [
                    'title' => 'This is the title',
                    'body' => 'This is the body'
                ],
                'sound' => 'default',
                'badge' => 1

            ],
            'extraPayLoad' => [
                'custom' => 'My custom data',
            ]
        ])
    ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...]);

or do it separately

$push->setMessage([
       'notification' => [
               'title'=>'This is the title',
               'body'=>'This is the message',
               'sound' => 'default'
               ],
       'data' => [
               'extraPayLoad1' => 'value1',
               'extraPayLoad2' => 'value2'
               ]
       ]);
$push->setApiKey('Server-API-Key');
$push->setDevicesToken(['deviceToken1'
    ,'deviceToken2',
    'deviceToken3'
]);

If you want send the notification to only 1 device, you may pass the value as string.

$push->setDevicesToken('deviceToken');

Send the Notification

Method send() can be also chained to the above methods.

$push->setMessage([
       'notification' => [
               'title'=>'This is the title',
               'body'=>'This is the message',
               'sound' => 'default'
               ],
       'data' => [
               'extraPayLoad1' => 'value1',
               'extraPayLoad2' => 'value2'
               ]
       ])
    ->setApiKey('Server-API-Key')
    ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...])
    ->send();

Send the Notification by Topic (FCM only)

$push = new PushNotification('fcm');
$response = $push->setMessage(['message'=>'Hello World'])
            ->setApiKey('YOUR-API-KEY')
            ->setConfig(['dry_run' => false])
            ->sendByTopic('dogs');

or with a condition:

$push = new PushNotification('fcm');
$response = $push->setMessage(['message'=>'Hello World'])
            ->setApiKey('YOUR-API-KEY')
            ->setConfig(['dry_run' => false])
            ->sendByTopic("'dogs' in topics || 'cats' in topics",true);

Understanding Gcm and Fcm Message Payload

Notification Message

Add a notification key when setting the message in setMessage method. like follows:

$push->setMessage([
           'notification' => [
                   'title'=>'This is the title',
                   'body'=>'This is the message',
                   'sound' => 'default'
                   ]
           );

You may add some extra payload adding a data key when setting the message in setMessage method.

$push->setMessage([
           'notification' => [
                   'title'=>'This is the title',
                   'body'=>'This is the message',
                   'sound' => 'default'
                   ],
           'data' => [
                   'extraPayLoad1' => 'value1',
                   'extraPayLoad2' => 'value2'
                   ]
           ]);

Data Message

By default, this package sends the notification as Data Message. So no need to add a data key.

$push->setMessage([
           'title'=>'This is the title',
           'body'=>'This is the message',
           'myCustomVAlue' => 'value'
       ]);

The above example is like you were sending the following:

$push->setMessage([
           'data' => [
                   'title'=>'This is the title',
                  'body'=>'This is the message',
                  'myCustomVAlue' => 'value'
                   ]
           ]);

For more details, have a look at gcm/fcm notification paypload support and the concept options

Getting the Notification Response

If you want to get the push service response, you can call the method getFeedback:

    $push->getFeedback();

Or again, chain it to the above methods:

    $push->setMessage(['body'=>'This is the message','title'=>'This is the title'])
                        ->setApiKey('Server-API-Key')
                        ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...])
                        ->send()
                        ->getFeedback();

It will return an object with the response.

APN Server Feedback and package Feedback

Any time you send a notification, it will check if APN server has any feedback for your certificate. If so, the responses are merged to our feedback like below:

class stdClass#21 (4) {
  public $success =>
  int(0)
  public $failure =>
  int(1)
  public $tokenFailList =>
  array(1) {
    [0] =>
    string(64) "c55741656e6c3185f3474291aebb5cf878b8719288e52bf4c497292b320312c5"
  }
  public $apnsFeedback =>
  array(1) {
    [0] =>
    class stdClass#16 (3) {
      public $timestamp =>
      int(1478272639)
      public $length =>
      int(32)
      public $devtoken =>
      string(64) "c55741656e6c3185f3474291aebb5cf878b8719288e52bf4c497292b320312c5"
    }
  }
}

Get Unregistered Devices tokens

After sending a notification, you may retrieve the list of unregistered tokens

$push->getUnregisteredDeviceTokens();

This method returns an array of unregistered tokens from the Push service provider. If there isn't any unregistered token, it will return an empty array.

Laravel Alias Facade

After register the Alias Facade for this Package, you can use it like follows:

PushNotification::setService('fcm')
                        ->setMessage([
                             'notification' => [
                                     'title'=>'This is the title',
                                     'body'=>'This is the message',
                                     'sound' => 'default'
                                     ],
                             'data' => [
                                     'extraPayLoad1' => 'value1',
                                     'extraPayLoad2' => 'value2'
                                     ]
                             ])
                        ->setApiKey('Server-API-Key')
                        ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...])
                        ->send()
                        ->getFeedback();

It would return the Push Feedback of the Notification sent.

Notification channels

Formatting Push Notifications

If a notification supports being sent as an push message, you should define toApn and/or toFcm/toGcm methods on the notification class. This method will receive a $notifiable entity and should return a Edujugon\PushNotification\Messages\PushMessage instance:

public function toApn($notifiable)
{
    return new PushMessage('Hello world');
}

Customizing The Title and Body

public function toApn($notifiable)
{
    return (new PushMessage)
        ->title('Hello world')
        ->body('...');
}

Customizing The Notification Sound

public function toApn($notifiable)
{
    return (new PushMessage)
        ->body('Hello world')
        ->sound('default');
}

Customizing The Badge Number

public function toApn($notifiable)
{
  return (new PushMessage)
        ->body('Hello world')
        ->sound('default')
        ->badge(7);
}

Passing Service Config

public function toApn($notifiable)
{
    return (new PushMessage)
        ->body('Hello world')
        ->config(['dry_run' => false]);
}

Add it to the notification channels

public function via($notifiable)
{
    return [ApnChannel::class];
}

Don't forget the use statement at the top of the class

Routing Push Notifications

Just define routeNotificationForApn and/or routeNotificationForFcm/routeNotificationForGcm methods on the entity

/**
 * Route notifications for the Apn channel.
 *
 * @return string|array
 */
public function routeNotificationForApn()
{
    return $this->ios_push_token;
}

pushnotification's People

Contributors

alvibd avatar ammardev avatar cs-couture avatar csabex94 avatar dunice avatar edujugon avatar eliyas5044 avatar ghecho avatar jenky avatar jeroen-van-dijk avatar jkirow avatar klimov-paul avatar laravel-shift avatar matanyadaev avatar pascalvgemert avatar pultho avatar sevrugin avatar varin6 avatar xheinrich 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  avatar

pushnotification's Issues

ErrorException

array_key_exists(): The first argument should be either a string or an integer

in PushNotification.php (line 52)

I am getting the issue. please help to solve this

Error in APN

when I try to send a push by apn I get this error
ErrorException in Apn.php line 283:
stream_socket_client(): Unable to set private key file

I was looking and the error is due to missing

captura de pantalla_2016-10-19_18-11-25

that solution is good?

Call to undefined method - ERROR

Hi Edu, great job.
I have a small problem and I can not solve.
The error message is:
Call to undefined method Edujugon\PushNotification\Facades\PushNotification::setMessage()

My Cod to try is
$push = new PushNotification('fcm'); $push->setMessage(['body'=>'This is the message','title'=>'This is the title']); $push->setDevicesToken(['ehsOBEniA6E:APA91bEogPTT0CiRZmsiI8s7CmvR-QybIgt1rD0Kark0K-L-_zllVmBsuC-JOLgyvnunqVSghKPJraE0A4MQ7d3BAA9P2oalhWyNZzBqoyw-l0jUV6M0sXKN5j1p4XpVzu3DFo--ZP4B']); $push->send();

app.conf
My Service Provider:
Edujugon\PushNotification\Providers\PushNotificationServiceProvider::class,
and
'PushNotification' => Edujugon\PushNotification\PushNotification::class,

pushnotification.php
'fcm' => [
'priority' => 'normal',
'dry_run' => false,
'apiKey' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
]

I really do not know how to solve

Can't send the pushnotification for iOS

I've used this for push notification in my project.
it works for Android.
But it doesn't work for iOS
I've got this error when I try to send push notification.

ErrorException: fwrite(): send of 253 bytes failed with errno=10054 An existing connection was forcibly closed by the remote host.
 in file E:\xampp\htdocs\playdate\vendor\edujugon\push-notification\src\Apn.php on line 314
Stack trace:
  1. ErrorException->() E:\xampp\htdocs\playdate\vendor\edujugon\push-notification\src\Apn.php:314
  2. fwrite() E:\xampp\htdocs\playdate\vendor\edujugon\push-notification\src\Apn.php:314
  3. Edujugon\PushNotification\Apn->send() E:\xampp\htdocs\playdate\vendor\edujugon\push-notification\src\PushNotification.php:163
  4. Edujugon\PushNotification\PushNotification->send() E:\xampp\htdocs\playdate\app\Http\Controllers\ApiController.php:1865
  5. App\Http\Controllers\ApiController->send_notification_apple() E:\xampp\htdocs\playdate\app\Http\Controllers\ApiController.php:1774
  6. App\Http\Controllers\ApiController->send_notification() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
  7. call_user_func_array() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
  8. Illuminate\Routing\Controller->callAction() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45
  9. Illuminate\Routing\ControllerDispatcher->dispatch() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Route.php:212
 10. Illuminate\Routing\Route->runController() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Route.php:169
 11. Illuminate\Routing\Route->run() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Router.php:658
 12. Illuminate\Routing\Router->Illuminate\Routing\{closure}() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php:30
 13. Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php:41
 14. Illuminate\Routing\Middleware\SubstituteBindings->handle() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:149
 15. Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}() E:\xampp\htdocs\playdate\vendor\laravel\framework\src\Ill...

This is my config file

'apn' => [
'certificate' => DIR . '/iosCertificates/DevMPD.pem',
'passPhrase' => '@love@', //Optional
'passFile' => DIR . '/iosCertificates/DevMPD.pem', //Optional
'dry_run' => true
]

This is my function for sending pushnotification

$push = new PushNotification('apn');
$extraNotificationData = ["message" => $msg, "user_name" =>$own_name, "user_id"=>$own_id];
$push->setMessage([
'aps' => [
'alert' => [
'title' => 'Development Push',
'body' => 'This is the testing for PRINCE'
],
'sound' => 'default',
'badge' => 1
],
'extraPayLoad' => [
'custom' => $extraNotificationData,
]
])
->setDevicesToken(['c0223b2a800ff6e975e3eef9ac6a484929d7e8ee05610a816b05910b20f0467b']);
$push->send();

Please help me now.
Thanks

.p12 instead of .pem

Not an issue per-se just a feature request. Is there any way you could modify this to use .p12 or .pem files?

It would just remove the extra step of generating the .pem

400 Bad Request response: "registration_ids" field cannot be empty

This error is shown when trying to send a notification with the following code:

$push = new PushNotification;
$push->setMessage([
'notification' => [
'title'=>'This is the title',
'body'=>'This is the message',
'sound' => 'default',
]
])
->setApiKey('AIzaSyBJalCHbX')
->send();

Can't send in iOS

I've succeeded in sending notifications before but now I can't seem to make it work.

If I test it here: http://www.pushwatch.com/apns/ with my PEM file and a token, I successfully receive it. But using this package I can't.
There's no $push->feedback->error and the function getFeedback() also shows success.

My config

'apn' => [
      'certificate' => __DIR__ . '/iosCertificates/certificate.pem',
      'passPhrase'  => '',
      'dry_run'     => true
  ]

Sending:

$push = new PushNotification('apn');

        $push->setMessage([
                    'aps' => [
                        'alert' => [
                            'title' => $data['title'],
                            'body'  => $data['description']
                        ],
                        'sound' => 'default'
                    ],
                    'extraPayLoad' => [
                        'type' => $data['type'],
                        'id'   => $data['id'],
                        'body' => $data['description']
                    ],
                ])
            ->setDevicesToken([$devicetoken])
            ->send();


        if(isset($push->feedback->error)){
            \Log::info('ERRO notificação ios - ' . $push->feedback->error);
        } else {
             \Log::info('Enviado com sucesso - ' . $devicetoken);
        }

My PEM file doesn't have a passPhrase, I tryed with and without the passPhrase line.

Am I missing something?

ErrorException

stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14094415:SSL routines:ssl3_read_bytes:sslv3 alert certificate expired in /vendor/edujugon/push-notification/src/Apn.php:184

Unable to set private key

Hi Edu and congrats x your package;

I m getting this error "response": {
"success": false,
"error": "Connection problem: stream_socket_client(): Unable to set private key file `/var/www/html/ws/config/iosCertificates/aps_development.pem'\n"
}

The path to the to cert is ok.
The file has 644 permissions.

Thanks in advance.

Sending Notification from FCM to IOS

I am trying to send notification using FCM service to ios app. ON Android using the same code works fine, but not on IOS. I am receiving the data in the foreground and printing it but can't show the badge alert. And in the background nothing is received.
I have tested the IOS part using the FCM notification composer and it is working fine.

this is the data I receive in IOS from my server and using FCM notification composer

My Server
[AnyHashable("from"): 1084873256575, AnyHashable("title"): Event happing near you, AnyHashable("id"): 88, AnyHashable("body"): Nobis et libero temporibus mollitia voluptatem on 2018, Thu 12 Apr 00:00 AM - 00:00 AM, AnyHashable("type"): App\Notifications\UpcomingEvent]
FCM Server

[AnyHashable("google.c.a.c_l"): Test 7, AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1523508749, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.n.e"): 1, AnyHashable("aps"): {
    alert = "Hello World again 2";
}, AnyHashable("google.c.a.c_id"): 3140898793034192784, AnyHashable("gcm.message_id"): 0:1523508749727331%c4ec4979c4ec4979]

This is the data that I am sending

[
      'type' => 'App\Notifications\UpcomingEvent',
      "id" => $event->id,
      "title" => 'Event happing near you',
      "body" =>  $event->title . ' on ' . event_date($event),
      "thumbnail" => $event->cover ? event_picture_url($event->cover, 'thumbnail') : null,
   ];

this is the notification code ::

// getting the data showing above
$event_data = $this->eventService->transformNotification($event);

sending the request
$push = new PushNotification('fcm');
$tokens = DB::table('device_tokens')->pluck('token')->toArray();
$push->setMessage([ 'data' => $event_data ])->setDevicesToken($tokens)->send();  

Out of memory

Hello @Edujugon,

I getting Out Of Memory error sending push to iOS.

image

I tried with develop and production url of Apple, but is always same error.

PHP v5.6.30
edujugon/push-notification: v2.2.0

GCM push notification is not receiving

Hi,
I am first time using this package and this is perfect when am using push notification using APN, But now am trying with GCM added api token and device id but response seems there is no error. But not yet i dont receive any push.

use Edujugon\PushNotification\PushNotification;
Controller
$push = new PushNotification();
$push->setMessage([
'notification' => [
'title'=> 'Nithin push kittumbo para - android',
'body'=> 'Nithin push kittumbo para - android',
'sound' => 'default'
],
'data' => [
'extraPayLoad1' => 'value1',
'extraPayLoad2' => 'value2'
]
])
->setApiKey('AAAAzNWar6k:APA91bFifq79w9hjoEnuwDv1swLhG0GM0_bim2gfDoJZmg0gwKwqmH6byd5fUcAwfPwWsfJJ4Vy0JO2Ajf0d6c-hW5y70SIelBr5POAJOUDuHWesz_Bt5HOsBoe3Kum')
->setDevicesToken(['APA91bGN-Ng4CaQyWqMfzcmu21kU-HWyLwIS8yoR2U7K_ZYRF6MS8ARqSkb3encMr2sxft8wtmZUbkrTUwZP0P8UURLwVgsLe3DU7UD-CjSvkPWMabKMGUXviTEjjfq4QLmqf7GtH6d5'])

            ->send();

pushnotification.php

return [
'gcm' => [
'priority' => 'normal',
'dry_run' => true,
'apiKey' => 'AAAAzNWar6k:APA91bFifq79w9hjoEnuwDv1swLhG0GM0_bim2gfDoJZmg0gwKwqmH6byd5fUcAwfPwWsfJJ4Vy0JO2Ajf0d6c-hW5y70SIelBr5POAJOUDuHWesz_Bt5HOsBoe3Kum',
],
'fcm' => [
'priority' => 'normal',
'dry_run' => false,
'apiKey' => 'My_ApiKey',
],
'apn' => [
'certificate' => DIR . '/iosCertificates/SprightlyPushCert.pem',
'passPhrase' => '1234', //Optional
'passFile' => DIR . '/iosCertificates/yourKey.pem', //Optional
'dry_run' => false
]
];

stream_socket_client() error

Hi, i have question about APNS connection

ERROR
"success": false
"error": "Connection problem: stream_socket_client(): Unable to set local cert chain file `C:\xampp\htdocs\application_name\config/iosCertificates/aps_development.cer'; Check that your cafile/capath settings include details of your certificate and its issuer\r\n"

Thanks in Advance, please mention if irrelevant to package

Feature: add exception with missed config

Hi there!
I found that missed config for apn throws an exception:
Undefined index 'apn' on PusherService.php line 69.
I think it will be great to add an exception with message like Config 'apn' missed in pushnotifications.php

setMessage not defined

Hi I am getting the following error:

Call to undefined method Edujugon\PushNotification\Facades\PushNotification::setMessage()

This is my code:

$push = new PushNotification('apn');
        $push->setMessage([
            'aps' => [
                'alert' => [
                    'title' => 'This is the title',
                    'body' => 'This is the body'
                ],
                'sound' => 'default'

            ],
            'extraPayLoad' => [
                'custom' => 'My custom data',
            ]
        ])
        ->setDevicesToken(['DEVICE_TOKEN_HERE']);
$push->send();

Also if I use the facade I get success code but no notifications received, any ideas?

Laravel 5.4 publishing config file error

publishing the config file ends with error in laravel 5.4 as Illuminate\Foundation\Application::share() been deprecated.

vendor/edujugon/push-notification/src/Providers/PushNotificationServiceProvider.php on line 32

 [Symfony\Component\Debug\Exception\FatalErrorException]              
  Call to undefined method Illuminate\Foundation\Application::share()

deviceToken array fails if deviceToken not found

I have the following:

        $push->setDevicesToken(
            [
                '507e3adaf433ae3e6234f35c82f8a43ad0d84218bff08f16ea7be0869f066c03',
                '507e3adaf433ae3e6234f35c82f8a43ad0d84218bff08f16ea7be0869f066c04',
                '507e3adaf433ae3e6234f35c82f8a43ad0d84218bff08f16ea7be0869f066c03',

            ]);

The script only sends the first one (which is a correct deviceToken, I have purposely changed the middle one). If you change the loop in Apn.php it works. Is it valid to write more than one device token at a time to Apple?

If all three are the same, i.e none fail it shows 3 times, which is correct.

Confusion about FCM apiKey

I am confused
I use FCM and i need to add apiKey to config
Is it Web API Key or Server key or Legacy server key ?
I found the 3 keys in my app account, which one i must use ?

Error : Please, add your APN certificate to the iosCertificates folder

Hi,

I am using Laravel 5.2

I am getting below error while trying to sent push notification on IOS device using APN

{#596 ▼
+"success": false
+"error": "Please, add your APN certificate to the iosCertificates folder.\n"
}

I have added the APN certificate. Still I am getting this error.

'apn' => [
'certificate' => DIR . '/iosCertificates/pushcertdev.pem',
'passPhrase' => '1234', //Optional
//'passFile' => DIR . '/iosCertificates/yourKey.pem', //Optional
'dry_run' => false
]

Not Compatible with Laravel 5.0/5.1

Is this package meant to not be compatible with 5.0 or 5.1?

I see that you request for minimum version of illuminate/support to be 5.2 which should mean Laravel 5.2 and above?

Problem 1
- Conclusion: remove laravel/framework v5.1.45
- Conclusion: don't install laravel/framework v5.1.45
- edujugon/push-notification v2.1.0 requires illuminate/support ^5.2 -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.4].
- edujugon/push-notification v2.1.2 requires illuminate/support ^5.2 -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.4].
- edujugon/push-notification v2.1.3 requires illuminate/support ^5.2 -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.4].
- edujugon/push-notification v2.1.4 requires illuminate/support ^5.2 -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.4].
- edujugon/push-notification v2.1.5 requires illuminate/support ^5.2 -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.4].
- edujugon/push-notification v2.1.6 requires illuminate/support ^5.2 -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.4].
- don't install illuminate/support v5.2.0|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.19|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.21|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.24|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.25|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.26|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.27|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.28|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.31|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.32|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.37|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.43|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.45|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.6|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.2.7|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.3.0|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.3.16|don't install laravel/framework v5.1.45
- don't install illuminate/support v5.3.4|don't install laravel/framework v5.1.45
- Installation request for laravel/framework (locked at v5.1.45, required as 5.1.*) -> satisfiable by laravel/framework[v5.1.45].
- Installation request for edujugon/push-notification ^2.1 -> satisfiable by edujugon/push-notification[v2.1.0, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6].

Sleeping process

I'm using PushNotification in a Laravel 5.2 Artisan Console.

I have PushNotification in a common Helper and works fine, but when I execute in console "push:send", I recieve push notifications in my phone, but console process never completes. My push:send command code is:

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\PushQueue;
use Edujugon\PushNotification\Facades\PushNotification;

class SendPush extends Command
{
    protected $signature = 'push:send';

    protected $description = 'Send Push';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $queue = PushQueue::where('send', 0)->get();
        
        if($queue)
        {
            foreach($queue as $push)
            {
                # iOS
                if($push->type == 2)
                {
                    $result = PushNotification
                        ::setService('apn')
                        ->setUrl(env('PUSH_IOS_URL'))
                        ->setMessage( [ 'aps' => json_decode($push->config) ] )
                        ->setDevicesToken( json_decode($push->token) )
                        ->send()
                        ->getFeedback()
                    ;
                    
                    echo "iOS\n";
                    print_r($result);
                    echo "/iOS\n";
                }
            }
        }
    }
}

My SetUrl value is ssl://gateway.push.apple.com:2195 and I'm using production certificates.
Console never do the "echo" lines

Fake Message ID error

I am new to Laravel and Pushnotification as well, I am using below code t send push notification

$respone = PushNotification::setService('fcm')
->setMessage([
'notification' => [
'title'=>'Sheep App notofication',
'body'=>'A user try to contact you',
'sound' => 'default'
]])
->setApiKey('AAAAxO2N17Q:APA91bGS5s7qy0larSwA0SOnz-5hv-Ls62hKJI3A5Q1ReKfgicl-aT2kB4hW-wpKt3sOV_q1rPGaWJRaKRv8tZ2rq99DTCq1ffqujKhsxOqObXjHTCGdzr2y8aBH_N9TZ874Mmx7IZux')
->setDevicesToken(['ewGx_pBcDzI:APA91bH1JQIpQyqsik5RM_wtAAkrCb035Vkh8DQxSuv6X2qr3QlooVb5-b_y1lB9x3Jk1i9URC9LjA2UgbrVWQmlYu82rrwKzfTNrDt7qGfkbR60lr3lNk3alAUWoANIQWe60linN96i'])
->send()
->getFeedback();

I am getting fake_message_id Error Please help me to solve the Issue.

FCM/GCM Usage

Sorry for having to create another issue so quick but i can't seem to utilise the package if I declare an instance of the facade.

$push = new PushNotification('fcm');

$push->setMessage([
    'notification' => [
        'title'=>'This is the title',
        'body'=>'This is the message',
        'sound' => 'default'
    ],
    'data' => [
        'extraPayLoad1' => 'value1',
        'extraPayLoad2' => 'value2'
    ]
])
->setDevicesToken('token'); 

Having the above code will throw the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to undefined method Edujugon\PushNotification\Facades\PushNotification::setMessage()

Unable to set local cert chain file

Hi, I'm getting this error consistently.
Connection problem: stream_socket_client(): Unable to set local cert chain file `/var/www/public_html/niggle/config/iosCertificates/niggle_push.pem'; Check that your cafile/capath settings include details of your certificate and its issuer.

I can connect to apns server when I add -CAfile entrust-2048-ca.cer to the open ssl command on my local environment.Please help.

certificate issue

{"success":false,"error":"cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)"}

$push= PushNotification::setService('fcm')
->setMessage([
'notification' => [
'title'=>'This is the title',
'body'=>'This is the message',
'sound' => 'default'
],
'data' => [
'extraPayLoad1' => 'value1',
'extraPayLoad2' => 'value2'
]
])
// ->setApiKey('Server-API-Key')
->setDevicesToken(['dGwMZ7AiI-k:APA91bFBbw_gX48VYJGSw2MpEtz4hEZUd2occkvkzeR3NKMqNVipYxB4oWEBOlOU_aZU5IFnoPiN-pfZSv4VIUwIuL0eAt7UYl4wmz-LXTwJOmyvVztq7Fn0s6sTuil1_LcA82YKCE0-'])
->send()
->getFeedback();

ErrorException in Gcm.php line 112:

trying to send push and got error, any idea why?

"Use of undefined constant ARRAY_FILTER_USE_KEY - assumed 'ARRAY_FILTER_USE_KEY'"

$push->setMessage([ "notification" => [ "title" => $me->name, "body" => $message, ], "data" => [ "user_id" => 1, "chat_room_id" => 2, "text" => $message, "name" => $me->name, "time" => "momend ago", ] ]) ->setApiKey('api-key') ->setDevicesToken($token) ->send() ->getFeedback();

Send to iOS asks for pass phrase in console

I have a Certificate with a pass phrase and when I use it it asks for pass phrase in the console:
Enter PEM pass phrase:

My configuration:

  'apn' => [
      'certificate' => __DIR__ . '/iosCertificates/certificate2.pem',
      'passPhrase'  => '1234', //Optional
      //   'passFile'    => __DIR__ . '/iosCertificates/yourKey.pem', //Optional
      'dry_run'     => true
  ]

My code:

$push = new PushNotification('apn');

        $push->setMessage([
                    'aps' => [
                        'alert' => [
                            'title' => $data['title'],
                            'body'  => $data['description']
                        ],
                        'sound' => 'default'

                    ],
                    'extraPayLoad' => [
                        'type' => $data['type'],
                        'id'   => $data['id'],
                    ]
                ])
            ->setDevicesToken([$devicetoken])
            ->send();

After writing 1234 in the console it sends the notification. Am I missing something?

Is it a deliberate choice that the format of feedback varies by failure cause?

With app notifications, getFeedback() provides data in two different formats.

When a push fails for connection reasons, the format of getFeedback() is:

['success' => bool, 'error' => string]

e.g., https://github.com/Edujugon/PushNotification/blob/master/src/Apn.php#L175

If it passes, or fails on Apple's side, then the format of getFeedback() is:

['success' => int, 'failure' => int, 'tokenFailList' => [int], $apnsFeedback => [stuff]]

e.g., https://github.com/Edujugon/PushNotification/blob/master/src/Apn.php#L405

I was expecting the getFeedback() result to have the same structure, albeit with different values.

Was this a deliberate choice? Would a pull request to make them return in a single format be welcome? It would obviously be a potentially breaking change.

If it would be welcome, I would think of making the first case return ints for success and failure, with the appropriate number given how far it got before the fail, and adding an error string field to the second case which would say "Apple provided feedback" or some such if there was a fail from Apple, or nothing otherwise.

Feedback when using as notification channel

How are you able receive feedback, when using a notification channel with ShouldQueue?

I've tried called getFeedback and getUnregisteredDeviceTokens after the request finished. But I receive either [] or NULL.
The notification is sent and received. I am using both a valid token and an invalid one.

TestController file:
image

NewMessage file:
image

Should I be calling getFeedback/getUnregisteredDeviceTokens another place?

about fcm sending message

hello, could you help me ?
my laravel application running perfectly with apn.
but i got some problem with fcm

PushNotification::setService('fcm') ->setMessage([ 'notification' => [ 'title'=>'This is the title', 'body'=>'This is the message', 'sound' => 'default' ], 'data' => [ 'extraPayLoad1' => 'value1', 'extraPayLoad2' => 'value2' ] ]) ->setApiKey('Server-API-Key') ->setDevicesToken(['deviceToken1']) ->send() ->getFeedback();

after i sending message, it shows
{#309
+"success": false
+"error": "cURL error 51: SSL: certificate verification failed (result: 5) (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)"
}

i don't know how to fix it, could you help me?

apns getFeedback parse error

First of all, thanks for this lib.
One problem here, when I try to send apns notification its delivered successfully but seems like apns getFeedback method is failing with following error: stream_socket_client(): unable to connect to (Failed to parse address "")
Config is regular, just cert and passPhrase added.
Stack trace:

Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'stream_socket_c...', '/var/www/html/v...', 294, Array)
#1 /var/www/html/vendor/edujugon/push-notification/src/Apn.php(294): stream_socket_client('', 0, 'Failed to parse...', 60, 4, Resource id #370)
#2 /var/www/html/vendor/edujugon/push-notification/src/Apn.php(260): Edujugon\PushNotification\Apn->apnsFeedback()
#3 /var/www/html/vendor/edujugon/push-notification/src/PushNotification.php(163): Edujugon\PushNotification\Apn->send(Array, Array)
...

Android Push Notification suddenly stop working.

image

I have not change anything at all. It just stop working. Before this it works like a charm. Maybe I'm missing something here...

PushNotification::setService('fcm')
        ->setMessage([
            'notification' => [
                'title' => "hello",
                'body' => "haiii",
                'sound' => 'default'
            ],
            'data' => [
                'extraPayLoad1' => 'value1',
                'extraPayLoad2' => 'value2'
            ]
        ])
        ->setApiKey('My api key')
        ->setDevicesToken('My device token')
        ->send()
        ->getFeedback()

When download app from app store (production) , push is not arriving

When i was testing the push notification on development it works perfectly, but after I commit it on app store and downloaded it, push notification does not work, any idea what is wrong?
should the ios guy change the url for production
/**
* Url for development purposes
*
* @var string
*/
private $sandboxUrl = 'ssl://gateway.sandbox.push.apple.com:2195';

/**
 * Url for production
 *
 * @var string
 */
private $productionUrl = 'ssl://gateway.push.apple.com:2195';

/**

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.