Instantly share code, notes, and snippets.

Embed
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;
@zalow517

This comment has been minimized.

Show comment
Hide comment
@zalow517

zalow517 Feb 18, 2014

Worked, thanks :)

zalow517 commented Feb 18, 2014

Worked, thanks :)

@Domotoc

This comment has been minimized.

Show comment
Hide comment
@Domotoc

Domotoc 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 ! :)

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

This comment has been minimized.

Show comment
Hide comment
@aps112

aps112 May 2, 2014

Thank you :)

aps112 commented May 2, 2014

Thank you :)

@geek4life

This comment has been minimized.

Show comment
Hide comment
@geek4life

geek4life May 23, 2014

thanx, bro, the code really helped!!!

geek4life commented May 23, 2014

thanx, bro, the code really helped!!!

@atmimran

This comment has been minimized.

Show comment
Hide comment
@atmimran

atmimran Jun 13, 2014

Thanks its working. :)

atmimran commented Jun 13, 2014

Thanks its working. :)

@xswapnull

This comment has been minimized.

Show comment
Hide comment
@xswapnull

xswapnull Jun 29, 2014

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

xswapnull commented Jun 29, 2014

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

@bkolarov

This comment has been minimized.

Show comment
Hide comment
@bkolarov

bkolarov Aug 19, 2014

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.

bkolarov commented Aug 19, 2014

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

This comment has been minimized.

Show comment
Hide comment
@aakiky

aakiky Sep 2, 2014

call via browser ?

aakiky commented Sep 2, 2014

call via browser ?

@saadullah111

This comment has been minimized.

Show comment
Hide comment
@saadullah111

saadullah111 Sep 16, 2014

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

saadullah111 commented Sep 16, 2014

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

@saadullah111

This comment has been minimized.

Show comment
Hide comment
@saadullah111

saadullah111 Sep 16, 2014

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 ?

saadullah111 commented Sep 16, 2014

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 ?

@vinothc90

This comment has been minimized.

Show comment
Hide comment
@vinothc90

vinothc90 Sep 19, 2014

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

vinothc90 commented Sep 19, 2014

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

@tarushbali

This comment has been minimized.

Show comment
Hide comment
@tarushbali

tarushbali Sep 29, 2014

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.

tarushbali commented Sep 29, 2014

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.

@trilochanumath

This comment has been minimized.

Show comment
Hide comment
@trilochanumath

trilochanumath commented Oct 14, 2014

Thanks !

@umairali

This comment has been minimized.

Show comment
Hide comment
@umairali

umairali Oct 14, 2014

Getiing error

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

umairali commented Oct 14, 2014

Getiing error

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

@vespino

This comment has been minimized.

Show comment
Hide comment
@vespino

vespino 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?

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?

@pramod1988

This comment has been minimized.

Show comment
Hide comment
@pramod1988

pramod1988 Dec 22, 2014

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.

pramod1988 commented Dec 22, 2014

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.

@chetanakambad

This comment has been minimized.

Show comment
Hide comment
@chetanakambad

chetanakambad Jan 20, 2015

how can i get device registeration id

chetanakambad commented Jan 20, 2015

how can i get device registeration id

@huseynrasulov

This comment has been minimized.

Show comment
Hide comment
@huseynrasulov

huseynrasulov Jan 25, 2015

Thanks :) How I can send notification to iOS ?

huseynrasulov commented Jan 25, 2015

Thanks :) How I can send notification to iOS ?

@jgermanvelasquez

This comment has been minimized.

Show comment
Hide comment
@jgermanvelasquez

jgermanvelasquez Feb 4, 2015

Hi, Thanks ;) +10

jgermanvelasquez commented Feb 4, 2015

Hi, Thanks ;) +10

@mikemix

This comment has been minimized.

Show comment
Hide comment
@mikemix

mikemix 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

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
@kiransidhu

This comment has been minimized.

Show comment
Hide comment
@kiransidhu

kiransidhu Feb 17, 2015

how should i send message to multiple devices

kiransidhu commented Feb 17, 2015

how should i send message to multiple devices

@LokeshPatel

This comment has been minimized.

Show comment
Hide comment
@LokeshPatel

LokeshPatel Feb 18, 2015

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");

LokeshPatel commented Feb 18, 2015

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");

@kevindeli

This comment has been minimized.

Show comment
Hide comment
@kevindeli

kevindeli Mar 19, 2015

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

kevindeli commented Mar 19, 2015

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

@sureshbora1989

This comment has been minimized.

Show comment
Hide comment
@sureshbora1989

sureshbora1989 Mar 26, 2015

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

sureshbora1989 commented Mar 26, 2015

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

@riyaj

This comment has been minimized.

Show comment
Hide comment
@riyaj

riyaj Apr 2, 2015

Getting This Error

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

Please Help

riyaj commented Apr 2, 2015

Getting This Error

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

Please Help

@Tzafra

This comment has been minimized.

Show comment
Hide comment
@Tzafra

Tzafra Apr 12, 2015

worked right out of the box. thanks a ton!

Tzafra commented Apr 12, 2015

worked right out of the box. thanks a ton!

@yassine-developper

This comment has been minimized.

Show comment
Hide comment
@yassine-developper

yassine-developper Apr 22, 2015

Thanks so mutch bro 😊

yassine-developper commented Apr 22, 2015

Thanks so mutch bro 😊

@dflm25

This comment has been minimized.

Show comment
Hide comment
@dflm25

dflm25 May 25, 2015

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

dflm25 commented May 25, 2015

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

@colonna-mike

This comment has been minimized.

Show comment
Hide comment
@colonna-mike

colonna-mike May 25, 2015

Worked first time! thank you!!!

colonna-mike commented May 25, 2015

Worked first time! thank you!!!

@colonna-mike

This comment has been minimized.

Show comment
Hide comment
@colonna-mike

colonna-mike Jun 10, 2015

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

colonna-mike commented Jun 10, 2015

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

@lomteankush2

This comment has been minimized.

Show comment
Hide comment
@lomteankush2

lomteankush2 Jun 17, 2015

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

lomteankush2 commented Jun 17, 2015

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

@lohiloki

This comment has been minimized.

Show comment
Hide comment
@lohiloki

lohiloki Jun 22, 2015

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 commented Jun 22, 2015

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?

@lokranjan

This comment has been minimized.

Show comment
Hide comment
@lokranjan

lokranjan Jun 23, 2015

@ 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

lokranjan commented Jun 23, 2015

@ 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

@SrMordred

This comment has been minimized.

Show comment
Hide comment
@SrMordred

SrMordred Jun 30, 2015

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

SrMordred commented Jun 30, 2015

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

@DouglasHennrich

This comment has been minimized.

Show comment
Hide comment
@DouglasHennrich

DouglasHennrich Jul 12, 2015

@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);

?>

DouglasHennrich commented Jul 12, 2015

@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);

?>
@Mickael746

This comment has been minimized.

Show comment
Hide comment
@Mickael746

Mickael746 Jul 13, 2015

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

Mickael746 commented Jul 13, 2015

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

@galkeidar

This comment has been minimized.

Show comment
Hide comment
@galkeidar

galkeidar Jul 13, 2015

How do I call this script from Terminal?

galkeidar commented Jul 13, 2015

How do I call this script from Terminal?

@deinier

This comment has been minimized.

Show comment
Hide comment
@deinier

deinier Aug 16, 2015

Thank you very much! It worked pretty well.

deinier commented Aug 16, 2015

Thank you very much! It worked pretty well.

@danielvga

This comment has been minimized.

Show comment
Hide comment
@danielvga

danielvga Aug 22, 2015

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?

danielvga commented Aug 22, 2015

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?

@farizyoga

This comment has been minimized.

Show comment
Hide comment
@farizyoga

farizyoga Sep 3, 2015

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

farizyoga commented Sep 3, 2015

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

@farizyoga

This comment has been minimized.

Show comment
Hide comment
@farizyoga

farizyoga Sep 3, 2015

so sorry for my bad english

farizyoga commented Sep 3, 2015

so sorry for my bad english

@kaushikshamantha

This comment has been minimized.

Show comment
Hide comment
@kaushikshamantha

kaushikshamantha Sep 20, 2015

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

kaushikshamantha commented Sep 20, 2015

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

@webs1king

This comment has been minimized.

Show comment
Hide comment
@webs1king

webs1king Oct 11, 2015

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

webs1king commented Oct 11, 2015

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

This comment has been minimized.

Show comment
Hide comment
@nehah

nehah 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!

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!

@JuanEsporrin

This comment has been minimized.

Show comment
Hide comment
@JuanEsporrin

JuanEsporrin Oct 28, 2015

Thanks! Works like a charm! :D

JuanEsporrin commented Oct 28, 2015

Thanks! Works like a charm! :D

@matgott

This comment has been minimized.

Show comment
Hide comment
@matgott

matgott Jan 20, 2016

Hi, where find THE_DEVICE_REGISTRATION_ID?

matgott commented Jan 20, 2016

Hi, where find THE_DEVICE_REGISTRATION_ID?

@ghadgetushard

This comment has been minimized.

Show comment
Hide comment
@ghadgetushard

ghadgetushard Jan 22, 2016

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

ghadgetushard commented Jan 22, 2016

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

@devkiran

This comment has been minimized.

Show comment
Hide comment
@devkiran

devkiran commented Jan 22, 2016

Thanks.

@lafimostafa1990

This comment has been minimized.

Show comment
Hide comment
@lafimostafa1990

lafimostafa1990 Jan 25, 2016

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 ???

lafimostafa1990 commented Jan 25, 2016

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

This comment has been minimized.

Show comment
Hide comment
@mgbako

mgbako Jan 26, 2016

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

mgbako commented Jan 26, 2016

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

@sunilnimble2015

This comment has been minimized.

Show comment
Hide comment
@sunilnimble2015

sunilnimble2015 Feb 1, 2016

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.

sunilnimble2015 commented Feb 1, 2016

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.

@gohelyogesh

This comment has been minimized.

Show comment
Hide comment
@gohelyogesh

gohelyogesh Feb 3, 2016

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

gohelyogesh commented Feb 3, 2016

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

@mkotrujillo18

This comment has been minimized.

Show comment
Hide comment
@mkotrujillo18

mkotrujillo18 Feb 5, 2016

How to find THE_DEVICE_REGISTRATION_ID ? please, help me.

mkotrujillo18 commented Feb 5, 2016

How to find THE_DEVICE_REGISTRATION_ID ? please, help me.

@srikanth488

This comment has been minimized.

Show comment
Hide comment
@srikanth488

srikanth488 Feb 8, 2016

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.

srikanth488 commented Feb 8, 2016

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.

@Farhansheharyar

This comment has been minimized.

Show comment
Hide comment
@Farhansheharyar

Farhansheharyar Feb 11, 2016

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

Farhansheharyar commented Feb 11, 2016

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

This comment has been minimized.

Show comment
Hide comment
@NeroJz

NeroJz Feb 24, 2016

Thanks. It works perfectly.

NeroJz commented Feb 24, 2016

Thanks. It works perfectly.

@malechoclo

This comment has been minimized.

Show comment
Hide comment
@malechoclo

malechoclo Feb 24, 2016

Hi everyone,

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

malechoclo commented Feb 24, 2016

Hi everyone,

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

@whileser

This comment has been minimized.

Show comment
Hide comment
@whileser

whileser Feb 26, 2016

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?

whileser commented Feb 26, 2016

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

This comment has been minimized.

Show comment
Hide comment
@ncodebox

ncodebox Mar 4, 2016

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

ncodebox commented Mar 4, 2016

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

@theja0473

This comment has been minimized.

Show comment
Hide comment
@theja0473

theja0473 Mar 8, 2016

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

theja0473 commented Mar 8, 2016

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

@sarathkumarbaskaran

This comment has been minimized.

Show comment
Hide comment
@sarathkumarbaskaran

sarathkumarbaskaran Mar 14, 2016

@theja0473

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

sarathkumarbaskaran commented Mar 14, 2016

@theja0473

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

@hemanth5636

This comment has been minimized.

Show comment
Hide comment
@hemanth5636

hemanth5636 Mar 15, 2016

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

hemanth5636 commented Mar 15, 2016

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

@Zaeembinrehman

This comment has been minimized.

Show comment
Hide comment
@Zaeembinrehman

Zaeembinrehman Mar 16, 2016

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

Zaeembinrehman commented Mar 16, 2016

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

@rpayanm

This comment has been minimized.

Show comment
Hide comment
@rpayanm

rpayanm Mar 17, 2016

@Zaeembinrehman look here:
selection_075

Here i have 3.

rpayanm commented Mar 17, 2016

@Zaeembinrehman look here:
selection_075

Here i have 3.

@riteshnewal

This comment has been minimized.

Show comment
Hide comment
@riteshnewal

riteshnewal Mar 19, 2016

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?

riteshnewal commented Mar 19, 2016

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?

@ogaravito

This comment has been minimized.

Show comment
Hide comment
@ogaravito

ogaravito Mar 23, 2016

Help... the following error is generated

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

ogaravito commented Mar 23, 2016

Help... the following error is generated

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

@sivaguna

This comment has been minimized.

Show comment
Hide comment
@sivaguna

sivaguna 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?

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?

@phpninja123

This comment has been minimized.

Show comment
Hide comment
@phpninja123

phpninja123 Apr 12, 2016

Thanks dude, it works prefectly :)

phpninja123 commented Apr 12, 2016

Thanks dude, it works prefectly :)

@Sakshityagi011

This comment has been minimized.

Show comment
Hide comment
@Sakshityagi011

Sakshityagi011 Apr 26, 2016

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.

Sakshityagi011 commented Apr 26, 2016

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

This comment has been minimized.

Show comment
Hide comment
@codenpk

codenpk 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

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

This comment has been minimized.

Show comment
Hide comment
@arpit999

arpit999 May 9, 2016

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

arpit999 commented May 9, 2016

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

@sridhar2392

This comment has been minimized.

Show comment
Hide comment
@sridhar2392

sridhar2392 May 12, 2016

How can I set TTL value ?

sridhar2392 commented May 12, 2016

How can I set TTL value ?

@iamayaz

This comment has been minimized.

Show comment
Hide comment
@iamayaz

iamayaz May 18, 2016

it returning unauthorized error 401

iamayaz commented May 18, 2016

it returning unauthorized error 401

@anubhaw2091

This comment has been minimized.

Show comment
Hide comment
@anubhaw2091

anubhaw2091 May 20, 2016

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

anubhaw2091 commented May 20, 2016

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

@shubhkr

This comment has been minimized.

Show comment
Hide comment
@shubhkr

shubhkr May 24, 2016

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

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

@chathudan

This comment has been minimized.

Show comment
Hide comment
@chathudan

chathudan May 24, 2016

@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

chathudan commented May 24, 2016

@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

@mmr99869

This comment has been minimized.

Show comment
Hide comment
@mmr99869

mmr99869 May 27, 2016

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

mmr99869 commented May 27, 2016

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

This comment has been minimized.

Show comment
Hide comment
@khurshid-alam

khurshid-alam May 27, 2016

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.

khurshid-alam commented May 27, 2016

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

This comment has been minimized.

Show comment
Hide comment
@shubhkr

shubhkr May 30, 2016

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

shubhkr commented May 30, 2016

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

@anubhaw2091

This comment has been minimized.

Show comment
Hide comment
@anubhaw2091

anubhaw2091 Jun 3, 2016

@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.

anubhaw2091 commented Jun 3, 2016

@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.

@maqboolshah

This comment has been minimized.

Show comment
Hide comment
@maqboolshah

maqboolshah Jun 8, 2016

GCM notification received but not displaying anything on my cellphone

maqboolshah commented Jun 8, 2016

GCM notification received but not displaying anything on my cellphone

@rgherta

This comment has been minimized.

Show comment
Hide comment
@rgherta

rgherta Jun 12, 2016

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.

rgherta commented Jun 12, 2016

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

This comment has been minimized.

Show comment
Hide comment
@nasznjoka

nasznjoka Jun 20, 2016

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

nasznjoka commented Jun 20, 2016

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

@adhishlal

This comment has been minimized.

Show comment
Hide comment
@adhishlal

adhishlal Jun 29, 2016

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

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

adhishlal commented Jun 29, 2016

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

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

@nh1402

This comment has been minimized.

Show comment
Hide comment
@nh1402

nh1402 Jul 4, 2016

@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.

nh1402 commented Jul 4, 2016

@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

This comment has been minimized.

Show comment
Hide comment
@haxpor

haxpor Jul 12, 2016

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

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

This comment has been minimized.

Show comment
Hide comment
@haxpor

haxpor Jul 12, 2016

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.

haxpor commented Jul 12, 2016

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.

@ZaeemSattar

This comment has been minimized.

Show comment
Hide comment
@ZaeemSattar

ZaeemSattar Jul 13, 2016

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

ZaeemSattar commented Jul 13, 2016

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

@vikramparihar

This comment has been minimized.

Show comment
Hide comment
@vikramparihar

vikramparihar Jul 13, 2016

Thanks man.. its working :)

vikramparihar commented Jul 13, 2016

Thanks man.. its working :)

@rohitcoder

This comment has been minimized.

Show comment
Hide comment
@rohitcoder

rohitcoder Jul 13, 2016

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

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

This comment has been minimized.

Show comment
Hide comment
@rohitcoder

rohitcoder Jul 13, 2016

@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

rohitcoder commented Jul 13, 2016

@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

This comment has been minimized.

Show comment
Hide comment
@haxpor

haxpor 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.

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.

@vjbhaskar93

This comment has been minimized.

Show comment
Hide comment
@vjbhaskar93

vjbhaskar93 Jul 26, 2016

Thanks a Ton! Worked like a charm!!

vjbhaskar93 commented Jul 26, 2016

Thanks a Ton! Worked like a charm!!

@DeepakNamdev

This comment has been minimized.

Show comment
Hide comment
@DeepakNamdev

DeepakNamdev Aug 11, 2016

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

DeepakNamdev commented Aug 11, 2016

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

@skiworks

This comment has been minimized.

Show comment
Hide comment
@skiworks

skiworks Aug 16, 2016

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

skiworks commented Aug 16, 2016

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

@albovieira

This comment has been minimized.

Show comment
Hide comment
@albovieira

albovieira commented Aug 25, 2016

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

@triusdeeepak

This comment has been minimized.

Show comment
Hide comment
@triusdeeepak

triusdeeepak Sep 8, 2016

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

triusdeeepak commented Sep 8, 2016

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

@helpmewithphp

This comment has been minimized.

Show comment
Hide comment
@helpmewithphp

helpmewithphp Sep 20, 2016

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.

helpmewithphp commented Sep 20, 2016

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.

@gunjandev

This comment has been minimized.

Show comment
Hide comment
@gunjandev

gunjandev Sep 21, 2016

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

gunjandev commented Sep 21, 2016

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

@Revucurly

This comment has been minimized.

Show comment
Hide comment
@Revucurly

Revucurly Sep 22, 2016

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.

Revucurly commented Sep 22, 2016

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.

@sangitashinde

This comment has been minimized.

Show comment
Hide comment
@sangitashinde

sangitashinde Sep 26, 2016

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

sangitashinde commented Sep 26, 2016

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

@ferdhika31

This comment has been minimized.

Show comment
Hide comment
@ferdhika31

ferdhika31 Sep 26, 2016

thanks, it's work for me!

ferdhika31 commented Sep 26, 2016

thanks, it's work for me!

@nabaasa

This comment has been minimized.

Show comment
Hide comment
@nabaasa

nabaasa Oct 5, 2016

Thanks alot.....it works

nabaasa commented Oct 5, 2016

Thanks alot.....it works

@yourchoice

This comment has been minimized.

Show comment
Hide comment
@yourchoice

yourchoice Oct 16, 2016

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

yourchoice commented Oct 16, 2016

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

@autopten

This comment has been minimized.

Show comment
Hide comment
@autopten

autopten Nov 10, 2016

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

autopten commented Nov 10, 2016

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

@MohammadaliMirhamed

This comment has been minimized.

Show comment
Hide comment
@MohammadaliMirhamed

MohammadaliMirhamed Nov 11, 2016

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


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

MohammadaliMirhamed commented Nov 11, 2016

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


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

@poornimaa

This comment has been minimized.

Show comment
Hide comment
@poornimaa

poornimaa Dec 4, 2016

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!.

poornimaa commented Dec 4, 2016

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

This comment has been minimized.

Show comment
Hide comment
@Eitol

Eitol Dec 15, 2016

muchas gracias! funciona de 10

Eitol commented Dec 15, 2016

muchas gracias! funciona de 10

@FernandoFactor

This comment has been minimized.

Show comment
Hide comment
@FernandoFactor

FernandoFactor Dec 15, 2016

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.

FernandoFactor commented Dec 15, 2016

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.

@andymurakami

This comment has been minimized.

Show comment
Hide comment
@andymurakami

andymurakami Dec 22, 2016

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

error message to me
.

Anybody can help me ?

andymurakami commented Dec 22, 2016

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

error message to me
.

Anybody can help me ?

@luvscholar

This comment has been minimized.

Show comment
Hide comment
@luvscholar

luvscholar Jan 19, 2017

Thanks a million..

luvscholar commented Jan 19, 2017

Thanks a million..

@DavidAlejandroM

This comment has been minimized.

Show comment
Hide comment
@DavidAlejandroM

DavidAlejandroM Jan 26, 2017

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"}]}"

DavidAlejandroM commented Jan 26, 2017

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

This comment has been minimized.

Show comment
Hide comment
@astrex

astrex 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

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

This comment has been minimized.

Show comment
Hide comment
@makedir

makedir 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

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

This comment has been minimized.

Show comment
Hide comment
@vivekvikani

vivekvikani Feb 8, 2017

@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/

vivekvikani commented Feb 8, 2017

@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

This comment has been minimized.

Show comment
Hide comment
@PSteph

PSteph Feb 9, 2017

Thanks Bro

PSteph commented Feb 9, 2017

Thanks Bro

@ramonescamilla

This comment has been minimized.

Show comment
Hide comment
@ramonescamilla

ramonescamilla Feb 23, 2017

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

ramonescamilla commented Feb 23, 2017

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

@narsipanta

This comment has been minimized.

Show comment
Hide comment
@narsipanta

narsipanta Feb 25, 2017

For android do we have badge count?

narsipanta commented Feb 25, 2017

For android do we have badge count?

@gomathyfollowon

This comment has been minimized.

Show comment
Hide comment
@gomathyfollowon

gomathyfollowon Mar 7, 2017

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

gomathyfollowon commented Mar 7, 2017

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

This comment has been minimized.

Show comment
Hide comment
@anikn

anikn Mar 13, 2017

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

anikn commented Mar 13, 2017

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

@apurav2007

This comment has been minimized.

Show comment
Hide comment
@apurav2007

apurav2007 commented May 11, 2017

Thanks..

@diegocando

This comment has been minimized.

Show comment
Hide comment
@diegocando

diegocando May 12, 2017

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"
}
}

diegocando commented May 12, 2017

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"
}
}

@rolinger