Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple PHP script showing how to send an Android push notification. Be sure to replace the API_ACCESS_KEY with a proper one from the Google API's Console page. To use the script, just call scriptName.php?id=THE_DEVICE_REGISTRATION_ID
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

Worked, thanks :)

Domotoc commented Apr 8, 2014

Hello,
Thanks for this. For find API_ACCESS_KEY it's ok, but where find my THE_DEVICE_REGISTRATION_ID ?
It's a unique id for my mobile device android ? where active this id ?
Thanks ! :)

aps112 commented May 2, 2014

Thank you :)

thanx, bro, the code really helped!!!

Thanks its working. :)

Yeah ! Worked for me ....
Easiest way to send notification.

Does somebody have the android client for this code. I'm trying to figure out how to implement it but can't find anything useful.

aakiky commented Sep 2, 2014

call via browser ?

what is API_ACCESS_KEY and YOUR-API-ACCESS-KEY-GOES-HERE

How to find API_ACCESS_KEY and THE_DEVICE_REGISTRATION_ID ?
It's a unique id for my mobile device android ? where active this id ?

Hi Iam getting InvalidRegistration in results..
{"multicast_id":8084355120763866533,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

vinothc90 - Make sure you specify the reg id (the registration id you get back from google) as the id and the correct API key. I got the same error but it worked when I specified a reg id.

Thanks !

Getiing error

{"multicast_id":7717951616416938707,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

vespino commented Oct 27, 2014

So basically:

  • I have to call this script per device? Or can I send to more than 1 device?
  • I need to store the device ids on my server?

Is there something like this for iOS?

Hi, I have used this code but i am getting error Unauthorized Error 401.Can you plz help me in this? I have search this error everyone providing different solutions not getting idea what to do.

how can i get device registeration id

Thanks :) How I can send notification to iOS ?

Hi, Thanks ;) +10

mikemix commented Feb 12, 2015

Yes, but as a developer you must:

  • ensure connection is secured, so CURLOPT_SSL_VERIFYPEER should be set to true
  • escape $_GET input

how should i send message to multiple devices

Nice One :)

I have one Question ?

Can i send multiple Registration ids with single call

$registrationIds = array( $_GET['id'] ); // $_GET['id'] pass multiple ids in array formate.

like this : $registrationIds = array("id_1", "id_2", "id_3", "id_4");

great function,
i dont recive notification when the app is closed.. do you know what i need to do????

I am getting Unauthorized error ? Why, and which api key i have to use here Like android api key or server api key ?

riyaj commented Apr 2, 2015

Getting This Error

{"multicast_id":6564323768923178706,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

Please Help

Tzafra commented Apr 12, 2015

worked right out of the box. thanks a ton!

Thanks so mutch bro 😊

dflm25 commented May 25, 2015

Hi, How can I send a picture through push notification?

Worked first time! thank you!!!

Is there a example of sending a bigview? (wraptext)

Hello... how can I send notification to iOS?

Hi I have a demo app with text box with submit button.
I need to send push notification when anyone submit the button from the app. How can i achieve it. Please help out in this.?
I am not good at coding things but have a aspiration in this thing.

How to start from the beginning a a step by step.

Could you help me out in this?

@ lohiloki please read the artical the link I am Providing.I am sure it will help you to find your solution.
http://androidexample.com/Android_Push_Notifications_using_Google_Cloud_Messaging_GCM/index.php?view=article_discription&aid=119&aaid=139

Hello, Everything works perfectly for android ;) but when trying to send push to iOs it give me "InvalidRegistration" (after getting a valid id token)

@thisdyingsoul for ios is a little different:

<?php

    // Provide the Host Information.

    $tHost = 'gateway.sandbox.push.apple.com';

    $tPort = 2195;

    // Provide the Certificate and Key Data.

    $tCert = 'dev.pem';

    // Provide the Private Key Passphrase (alternatively you can keep this secrete

    // and enter the key manually on the terminal -> remove relevant line from code).

    // Replace XXXXX with your Passphrase

    $tPassphrase = 'xxxxxx';

    // Provide the Device Identifier (Ensure that the Identifier does not have spaces in it).

    // Replace this token with the token of the iOS device that is to receive the notification.

    $tToken = 'ada56107075e4d00f9da001b0ad71200cb953b99266e506884f6eab06f13f666';

    // The message that is to appear on the dialog.

    $empresa = "Petiskeira";

    $tAlert = $empresa . ' tem um recado para você!';

    // The Badge Number for the Application Icon (integer >=0).

    $tBadge = 1;

    // Audible Notification Option.

    $tSound = 'default';

    // The content that is returned by the LiveCode "pushNotificationReceived" message.

    $tPayload = '{"endereco":"lauro oscar diefenthaeler","tel":"51 3561-8797","numero":"243","complemento":"0","id":"9","nome":"petiskeira","msg":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum."}';

    // Create the message content that is to be sent to the device.

    $tBody['aps'] = array (

    'alert' => $tAlert,

    'badge' => $tBadge,

    'sound' => $tSound,

    );

    $tBody ['payload'] = $tPayload;

    // Encode the body to JSON.

    $tBody = json_encode ($tBody);

    // Create the Socket Stream.

    $tContext = stream_context_create ();

    stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert);

    // Remove this line if you would like to enter the Private Key Passphrase manually.

    stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase);

    // Open the Connection to the APNS Server.

    $tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext);

    // Check if we were able to open a socket.

    if (!$tSocket)

    exit ("APNS Connection Failed: $error $errstr" . PHP_EOL);

    // Build the Binary Notification.

    $tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody;

    // Send the Notification to the Server.

    $tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg));

    if ($tResult){

    echo 'Delivered Message to APNS' . PHP_EOL;

    }else

    echo 'Could not Deliver Message to APNS' . PHP_EOL;

    // Close the Connection to the Server.

    fclose ($tSocket);

?>

Hi,

It works but I have a little issue. The vibration/sound don't work.... And a question, can I use the light of the phone when I receive a notification?

Thank's

How do I call this script from Terminal?

deinier commented Aug 16, 2015

Thank you very much! It worked pretty well.

My server responds:
{"multicast_id":6442407815248771621,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1440257601123697%ae320ab3f9fd7ecd"}]}
My android phone does not receive Your Messages which may be wrong !? I'm using native extension freshplanet
it generates the token but is not getting the message please help me!
The error is in the application or php or php server?

if the phone is silent configured. is the phone will ringing if the variable "sound" filled with '1' ?

so sorry for my bad english

how to find the registration Id? is it from android mobile phone? how to find?

Wowowowo!!!!! Worked Nicely...I recommend everyone to use www file from Push plugin Example and This as a server side script. Get the crypto keys right, and you will rock

nehah commented Oct 22, 2015

Hi,
I want to implement PushNotification, tried this code but getting the error: {"multicast_id":7134379556373134147,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I put the API Key and the Client Id in Place of 'Registration Id' which is returned from the google account as: OAuth client
Here is your client ID
'73298986399-g26sd4fetehsl5n43tpd2300aa8smpob.apps.googleusercontent.com'

Can anyone help me figure out where I am wrong?
Thanks!

Thanks! Works like a charm! :D

matgott commented Jan 20, 2016

Hi, where find THE_DEVICE_REGISTRATION_ID?

thanks a lot ... it worked for me .... but the messege what we encode on send notification.php file it does not appear over android notification messege .... what to do to show the messege we have encoded in pushnotification php file

Thanks.

Hi everyone
I'im getting this resultat :{"multicast_id":7255225399436680676,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
is this script that allows us to sent a notification on android was not need anything else because it's not working for me ???

mgbako commented Jan 26, 2016

Pls how can i redirect to a specific page on clicking the notification

HI,

I had used this script for android push notification, it was working fine but recently it stopped to work.

it giving following error For android push notification:-

"Curl failed: Failed to connect to android.googleapis.com port 443: Connection timed out."

Can you please provide me a suitable solution regarding it.

How to know Push Notification delivery status from parse server in Parse PHP?

How to find THE_DEVICE_REGISTRATION_ID ? please, help me.

Thank you , nice tutorial , i have one issue that getting only inline-notification i want outside status bar notification ,can you please help me out.

I need to know whether we can you use posted code in our professional projects means would'nt it be a copyright issue, I'll be waiting for your kind response

NeroJz commented Feb 24, 2016

Thanks. It works perfectly.

Hi everyone,

Can anyone give an example for receive it in ionic?
Thanks!!

I'm in trouble he always returns "registration_ids" field is not a JSON array "someone has gone through it, you know tell me what I'm missing?

ncodebox commented Mar 4, 2016

Hi,
Thank you, code is working.
but now i get response as NOT REGISTERED
please reply.

I have an error while using this script please help me out of it...
capturadsasde

@theja0473

Kindly, check your API header and params against the one in GCM help doc. Also, verify the JSON here in http://jsonlint.com/

i have an doubt. in what format my app receives the message, weather in json or assoc array

How the get the 'THE_DEVICE_REGISTRATION_ID'? Anyone who knows, please help. Thanks.

rpayanm commented Mar 17, 2016

@Zaeembinrehman look here:
selection_075

Here i have 3.

Hello, My PUSH on android get overwritten when new push arrives. Is there any way i can show all pushes in list. What change I should do?

Help... the following error is generated

{"multicast_id":5549268725019984832,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}

sivaguna commented Apr 4, 2016

Hi all,
am developing android app using ionic framework.
Need to implement push notification.
so am planned to use GCM and your code as backed trigger.
created one project in gcm, I have both API access key & Registration id
when i run the script am getting the following json..
{"multicast_id":5443360276219079358,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

can any one help me to get rid of this?
in general, i didn't configure api key / project number in my app. do i need to configure anywhere?

Thanks dude, it works prefectly :)

You can use Push notification Service in now these days. it;s very common and save money to make an android App. Push notification Service providers provide you an dashboard for make a panel, to send notification on mobile directly. As I used www.pushalive.com for this service and easy to use.

codenpk commented May 2, 2016

Hi, The script doesn't handle cannonical_ids. That is why some people are getting InvalidRegistration. Refer this link http://stackoverflow.com/questions/18200167/google-cloud-messaging-registration-id-expiration

arpit999 commented May 9, 2016

i can not able to fetch message in this script what should i do thanks in advance

How can I set TTL value ?

iamayaz commented May 18, 2016

it returning unauthorized error 401

It's not working for FCM.
Does anyone have any script for Firebase Cloud Messaging?

shubhkr commented May 24, 2016

what do you mean by "just call scriptName.php?id=THE_DEVICE_REGISTRATION_ID"?
how to run this from ubuntu

@shubhkr "THE_DEVICE_REGISTRATION_ID" is your android device's token
InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

Obtain a registration token

Hi everyone,

If you want to use the script for Firebase Cloud Messaging (FCM), you can just try to change the POST URL:
https://fcm.googleapis.com/fcm/send

Take into account that you will have to migrate from GCM to FCM first. Further instructions about the migration can be found here:
https://developers.google.com/cloud-messaging/android/android-migrate-fcm

Firebase sample code for Android Client:
https://github.com/firebase/quickstart-android/tree/master/messaging

khurshid-alam commented May 27, 2016 edited

Is there any easy way to get registration id without installing entire Android Studio? May be something like installing a simple apk on my device...put my api key....run the app....and get device registration id printed on the screen.

shubhkr commented May 30, 2016

registration id is getting changed i guess each time i send a notification.. what to do?

@shubhkr ,AFAIK ,Registration ID changes only when you uninstall your app( I am assuming, you are debugging your app in android studio and reinstalling it once in a while). If you don't explicitly uninstall the app, the ID won't change.

GCM notification received but not displaying anything on my cellphone

rgherta commented Jun 12, 2016 edited

If you want to send push notifications using chrome then the registration id is the endpoint generated by the service worker(you need a service worker for your html frontend, you can use this tutorial https://goo.gl/YNrXjn Just do all the steps and hit next at the end of the page for the next lesson and you ll get there.

nasznjoka commented Jun 20, 2016 edited

Hey Hi!!, I have been using code for the past 2 months and it works.... all of the sudden , since this past saturday, it won't send the notification down to the app even though the status shows that it is successfully sent... the result echoed is as
"{"multicast_id":7432182696628500008,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1466421665565231%0ada1155f9fd7ecd"}]}"

it seems that using the constant to insert the api key (define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' )) is not a good idea after all.. this was the problem why messages failed to reach the destination even though the results show success... I'm suggesting passing the api key as a normal variable from somewhere based on the project structure

Well, to make this work with new firebase, refer this:

https://adhishlal.github.io/Firebase-PHP/

nh1402 commented Jul 4, 2016 edited

@adhishlal does that work with iOS?

If not is there an equivalent php script for Firebase that works with iOS, I can't seem to get it working with the iOS example from above.

EDIT: got it working with the same function, ios requires the priority.

haxpor commented Jul 12, 2016 edited

I've spent a full day trying to make it works. It turns out at the end that my code is not a right way to show notification message.

For those who cannot receive push notification message on client side although the message was successfully sent, make sure you code it properly. My case was due to not subscribe to topics to listen to (i.e. global), and no proper code to show notification (I didn't specify icon for notification in client side and it silently didn't show notification message to me at all). Check this example out https://github.com/googlesamples/google-services/tree/master/android/gcm. It also contains a java command line program to send out push notification in the similar way of the script above. Both works.

All in all, I suggest to settle down with example in the link, make sure it works, then take the code and adapt to fit your case.

Edit: added clarification on where to add code for icon notification, it's on android app side.

haxpor commented Jul 12, 2016 edited

I slightly modified above script too to reflect the doc as seen at https://developers.google.com/cloud-messaging/ (although FCM is newer, but google still support GCM for now).

I changed

  • 'https://android.googleapis.com/gcm/send' to https://gcm-http.googleapis.com/gcm/send
  • Safely set true to CURLOPT_SSL_VERIFYPEER
  • registration_ids to to

See my forked script at https://gist.github.com/haxpor/866efcbb155140f75dcec240a9714e2e

Edit: added link to modified script, thanks to this script too.

HI . i tried this code but this code is not working when we send message to multiple ids

Thanks man.. its working :)

Yes i got a nice output
{"multicast_id":7890106619869834726,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1468449775328886%a48957e1f9fd7ecd"}]}

But why i am not receiving any notification yet? Can please anyone help me

rohitcoder commented Jul 13, 2016 edited

@haxpor can you please help me ? i didn't receiving
capture
1

notifications after getting this console output
{"multicast_id":7890106619869834726,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1468449775328886%a48957e1f9fd7ecd"}]}

Here's the code of my send.php file from which am trying to send notification

'here is a message. message', 'title' => 'This is a title. title', 'subtitle' => 'This is a subtitle. subtitle', 'tickerText' => 'Ticker text here...Ticker text here...Ticker text here', 'vibrate' => 1, 'sound' => 1, 'largeIcon' => 'http://icons.iconarchive.com/icons/marcus-roberto/google-play/512/Google-plus-icon.png', 'smallIcon' => 'http://icons.iconarchive.com/icons/marcus-roberto/google-play/512/Google-plus-icon.png' ); $fields = array ( 'registration_ids' => $registrationIds, 'data' => $msg ); $headers = array ( 'Authorization: key='.$api_key, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch ); echo $result; ?>

But am not receiving it although success json output

haxpor commented Jul 16, 2016

@rohitcoder First of all try changing registration_ids to to. All just check out modified script at https://gist.github.com/haxpor/866efcbb155140f75dcec240a9714e2e. Another problem might be at your client side, make sure the code to show notification message on android app is proper one. Check out the example link in my comment above. Use and adapt that code.

Thanks a Ton! Worked like a charm!!

this code is runnable ... if any error occured that reason of device id or google api key... sorry for my bad english

hi,
my app crashes when i send the notification using the above code.
my output is this though ...

{"server_response":[{"code":"firebase_true","message":"Notification sent successfully..."}]}{"multicast_id":6018791074250838508,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1471352487893305%c6f35c1ff9fd7ecd"}]}

plz help

I did a package for that, take a look::
https://github.com/AlboVieira/push-notification

triusdeeepak commented Sep 8, 2016 edited

How I can send other parameter in messages like sender_id, receiver_id etc.?

If I am using PHP for my server and would like to send back data (eg. percentage) back to Android App, how should i do it? Can anyone help me? Thanks.

how do i push gcm notification using PHP with a message and an image ?? please help..

Revucurly commented Sep 22, 2016 edited

Hi, this code is working fine for android app. What about Cross Platform app. If I am using PHP for my server and JavaScript for client and mysql for DB, which technique would be the best to get push notification? Please help. If the user is not actively using the app also, they doesn't require the app on a mobile device to be open in order for a message to be received. i.e. (This is like a smartphone to receive and display social media or text message alerts even when the device's screen is locked and the social media application that is pushing the notification is closed). One user should get a notification as soon as another user posts a comment using the app. I have searched some websites, they provide code only for app developed for Android, IOS, etc. but its not available for cross platform apps. Is this possible to implement in mobile app developed using Php, JS and mysql? Pls help me out with the code. Thanks in advance.

I have tried the below code to get the notification count like Facebook and its working fine.

           $(function() { // on document ready

          function updateAlerts() {
           $.ajax({
             url : "/check.php",
            type : "POST",
            data : {
               method : 'checkAlerts'
         },
           success : function(data, textStatus, XMLHttpRequest) {
                var response = $.parseJSON(data);

           // Update the DOM to show the new alerts!
             if (response.friendRequests > 0) {
            // update the number in the DOM and make sure it is visible...
           $('#unreadFriendRequestsNum').show().text(response.friendRequests);
         }
               else {
                   // Hide the number, since there are no pending friend requests
                  $('#unreadFriendRequestsNum').hide();
               }

                 // Do something similar for unreadMessages, if required...
            }
         });
           setTimeout('updateAlerts()', 15000); // Every 15 seconds.
          }

        });

I want pop up (Push) like notifications even if the user is not using the app actively.

what is the registration id, it is multiple or single and where i get registration id?
Please reply.

thanks, it's work for me!

nabaasa commented Oct 5, 2016

Thanks alot.....it works

Hi,

A question:
Same script can be used to send notification and for desktop google chrome ?

I tried it, but Service Worker show an notification with data undefined

self.addEventListener('push', event => {
  let promiseChain;
  if (event.data) { 
    // We have data - lets use it
    promiseChain = Promise.resolve(event.data.json());
  } else {
    promiseChain = fetch('/push-notifications/get')
      .then(response => response.json());
  }

  promiseChain = promiseChain.then(data => {
      console.log('DATA: ', data);
      return self.registration.showNotification(data.title, {
        body: data.body,
        icon: (data.icon ? data.icon : '/images/logo.png'),
        vibrate: [200, 100, 200, 100, 200, 100, 400],
        tag: data.tag
      });
    });
  event.waitUntil(promiseChain);
});

Instead to get get data (mesage defined in php) after I launch this php script, Service Worker arrive in else case when fetch data...

Can somebody help me to understand? Thank's

How to open the app on a specific url after user pushed the notification? I'd appreciate any help.

MohammadaliMirhamed commented Nov 11, 2016 edited

Best Simple Sample For Firebase Push Notification in below link :
https://gist.github.com/MohammadaliMirhamed/7384b741a5c979eb13633dc6ea1269ce


Tags : FCM - FIREBASE - firebase - base - fire - notification

Hi,

Is it possible to send multiple mobile numbers?.. I've tried but not able to find the solution.

If so much appreciated for your help.

Thanks!.

Eitol commented Dec 15, 2016

muchas gracias! funciona de 10

FernandoFactor commented Dec 15, 2016 edited

Thank you, also I have to thank @haxpor to give the information to change registration_ids to to, without that change my code would not work, so I just had to do some small changes to get the code working on my server because I need to send message to topics:

`<?php

// API access key from Google API's Console
define('API_ACCESS_KEY', 'AIzaSyDta...');
// prep the bundle
$msg = array
(
'body' => 'This is a message sent from my http server',
'title' => 'From server side',
'priority' => 'high',
'sound' => 'default',
'time_to_live' => 3600
);
$fields = array('to' => '/topics/news', 'notification' => $msg);

$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>`

5 days trying to make a push from server side, with some headaches and frustration but now it finally works perfectly 👍

Sorry for my english.

{"multicast_id":5352284567557772186,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

error message to me
.

Anybody can help me ?

Thanks a million..

i am develpment ionic aplication for android, i have a problem with notifications, if i send menssage with token from console of firebase, the message is recibed in my app, also if use the this script , the menssage no recibed the response is {"multicast_id":9211726170113352103,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1485467751893255%e573a045f9fd7ecd"}]}"

astrex commented Jan 30, 2017

Hello, I have tried Your code, but the 'tickerText' and 'largeIcon' does not work.
How could I set the ticker and the image ?

Best Greetings

makedir commented Feb 4, 2017

Does this (still) work? Or is it compatible with FCM? I tried it with a FCM test app but the moment it receives the broadcast, it crashes with:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference

vivekvikani commented Feb 8, 2017 edited

@rohitcoder @junmper
In the fields array, change 'data' to 'notification'
and in the
$msg = array
(
'body' => 'here is a message. message',
'title' => 'This is a title. title',
);

This worked for me. This makes it a Notification instead of a Data payload.

Try the following link
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

PSteph commented Feb 9, 2017

Thanks Bro

I'm using the above php script for my fcm android push notifications. It seems to work however in the result I receive back "to\n".. whatever I echo in this script shows up in my phonegap-push-plugin error. Any reason why I get "to\n" back?
Thanks,
Ramon

For android do we have badge count?

Can anyone send full code with explanation step by step how to send push notification in android? pls! Tons of thanks.. if get response ASP

anikn commented Mar 13, 2017

Using the above code, Can I send notification from browser ?

Thanks..

Hi, I've tried this code and partially works, the notification arrieves empty, I have tried many data inputs and formats but haven'e get a positive result, can someone share a valid data payload so I can try?

Json content I'm sending:

{"to":"APA91basdfasdfasdfas",
"priority" : "high",
"notification" : {
"Body" : "This week’s edition is now available.",
"title" : "NewsMagazine.com",
"icon" : "new",
},
"data" : {
"Message" : "3.21.15",
"contents" : "http://www.news-magazine.com/world-week/21659772"
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment