Apache Cordova / Phonegap Push Notification Tutorial – Part 3

Want create site? Find Free WordPress Themes and plugins.


Phonegap Push Notification Tutorial – Part 3 : Sending Push Notification using PHP for Phonegap / Apache Cordova Projects

Read Previous tutorial for,


  • Install some local server (XAMPP / WAMP / MAMP ) for running your PHP files.
  • Make sure, you’ve enabled CURL

$title="Push Notification Title";
$message="Push Notification Message";

function sendPush($to,$title,$message)
// API access key from Google API's Console
// replace API
define( 'API_ACCESS_KEY', 'AIzaSyC_LcqN85irttxFXcNIzkrSkPhAfcu68HI');
$registrationIds = array($to);
$msg = array
'message' => $message,
'title' => $title,
'vibrate' => 1,
'sound' => 1

// you can also add images, additionalData
$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, '' );
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;

Note :

  • Change $to=APA91bFIj2WLkD3W4kbZcGO7dyI..... with your registration ID
  • Change define( 'API_ACCESS_KEY', 'AIzaSyC_LcqN85irttxFXcNIzkrSkPhAfcu68HI'); with your Server key


Now Run your PHP file on your server. you’ll receive a message. when you open the message you can see the same message and title in alert box (you can customize them)

Did you find apk for android? You can find new Free Android Games and apps.
  • Gopi Nath

    How to enable CURL ?

  • Gopi Nath

    For Getting multiple notifications in device,where we need to get the notification id.

    Thanks …

  • Gustavo Leonardo Castañeda Mar

    Hi , excelent tutorial, everything went good , the notifications only work when the app is running in the background , is it a way to send notifications without running the app? like whatsap

    • It’ll work even you closed your application..!!

  • sunil

    Hi have give error mismatch sender Id…. When i run php file
    Following is error..

    • Make sure, you’re using same server key (API key) and project ID

      • sunil

        I use same API key but can u tell me where use Project ID.
        Again tell me Project Id,Project number, sender id is different ids or same.

        • Please read this article

          Project ID looks like : 721393051486
          Server Key Looks like : AIzaSyCPr1FBs7lCcfTKwrKIrwo49fRAO1HcEbA

          • sunil


            ‘title’ => $title,

            ‘vibrate’ => 1,

            ‘sound’ => 1

            // you can also add images, additionalData


            $fields = array


            ‘registration_ids’ => $registrationIds,

            ‘data’ => $msg


            $headers = array


            ‘Authorization: key=’.API_ACCESS_KEY,

            ‘Content-Type: application/json’


            $ch = curl_init();







            $result = curl_exec($ch);


            echo $result;



          • sunil

            Following is the my code..Is anything wrong in this…Becoz i have got error….Invalid Reg ID.
            I match that id with my device id..

          • sunil


          • sunil

            Any Java file is necessary in Cordova in package. I have php file and one js file with deviceReady Event nothing more than that…..

          • No need to include any Java files, but push notification plugin is necessary.

      • sunil

        can u give here some example code where to use project id and where to use server key. I use same as u mention in example. I am stuck here please help me.

  • sunil

    Here is two keys server key that was a auto created by google. This is picture. can u tell me which key i should use.

    • Type: Server Key

      • sunil

        nothing to be work same error Invalid Reg Id… I check Sender ID,API,Reg id that receive on device.


        • can you please share you registerationID, project Number and Server key to my mail ?

          • sunil

            Hi can you give me u r mail id…Actually i was already sent mail on notification mail..If not receive give me u r mail. I will share all details

      • sunil

        This is actual code…See again if any wrong

  • sunil

    Hi Sundaravel,

    I am sucess in sending push notification but notification not coming on mobile deivce.


    • Make sure, you’ve connected to network, still not coming ? uninstall & reinstall your app. If nothing works, plz try again from beginning. Don’t give up 🙂

  • sunil

    Can you tell me why message not come to my deivce.

  • sunil

    Hi Which device key is Correct…


    Or This is

    Because first key when i use then tell success me…and Second devuce keys use then show error failure When i send push notification using push plugin and gcm push plugin….

    • First one is correct

      • sunil

        ok Sundara Vel Sir,
        But on internet i read and also my friend told me remove charcter before “APA9” along with colon… Please confirm sir because u also use after “APA9” in your php program…Please sir help me i ma stuck and try 3 notification plugin…2 is sucess but not coming notification and one is not install prper so give error….I am hang now from an week….

  • sunil

    This is your program you use device id from “APA”. When i received device id some character appear before APA….So can you confirm which is correct..
    I use device key like your after “APA9…” then time of notification sending give failure error.. and i try to use with character appear before “APA9..” then give me success message, but notification not coming.

  • sunil

    See this show success but not coming notification..see device key…
    If i use from word “APA” then show failure error

    • Hey!! Don’t confuse
      Use what ever you’re getting from registerationID, you don’t want to remove anything from your output

  • Greg

    Hy I have the same error as some peole here, i have this message on my php server and i don’t know how to resolve it (i check all information a lot and i see no error ): {“multicast_id”:6935268950431522957,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

    • ojhew

      Did you ever get an answer to this i have the same problem

      • That means, Invalid registration! check project id & server from same google project
        or You need to try from first!!

    • Christine White

      I have encountered the same error.

      • Thank means, Invalid registration! check project id & server from same google project

    • Jeet Gandhi

      use project number…it is the sender id

    • Isac Ferreira

      Open, import your project from Google Project and use the new key.

  • Prakash Roy

    Very good tutorial. Explained very well. Thank you SUNDARAVEL. Made my job very easy.

  • Greg

    Do we need to install ngCordova in our project for make working the plugin ?

    • If you’re using ngcordova, you need to install. otherwise it’s not required

  • Anand Moorthy

    How do I get Registration ID in $to in above php file ?

    • Read the previous article @disqus_93Z7o4HFC3:disqus

      • Anand Moorthy

        Thanks .. It worked …
        Can you please help in this .. I am getting below error …
        Field “data” must be a JSON array: [“{“message”:”Push Notification Message”,”title”:”Push Notification Title”,”vibrate”:1,”sound”:1}”]

  • Muhammet Sancaktutan

    help me plsss
    why doesnt work this ?

    function loadDoc() {

    var body = ‘{ “to”:”fZRwdrlDBzw:APA91bF2mPCTRsPV4XxRvh4enKbvdGhNJtNvcA4J57DSKcbaaU–UxE0AJRjSJDZlsFt0x5fPHBZT7QwmLapURmqxz8cuM43KxcFzmrEg3J82r5vffddi9tD3bUuTcgz0wzCiuZ2yB”, “data” { “title”: “Example title”, “body”: “Example message body”, } }’;

    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {


    if (xhttp.readyState == 4 && xhttp.status == 200) {

    document.getElementById(“demo”).innerHTML = xhttp.responseText;


    };“POST”, “”, true);

    xhttp.setRequestHeader(“Content-type”, “application/json”);

    xmlHttp.setRequestHeader(“Authorization”, “AIzaSyCb5XxY-yBfGYSpRsUL_wsk7UrIyjMDQ”);



    • Please try running this php code. If you don’t have PHP environment, try online based phpfiddle

      • Muhammet Sancaktutan

        but i want to send message(gcm) from cordova mobile to other cordova mobile, so i cant run php code in mobile, do you have other way for this ?

        • 1) how to you know the TokenID for other device ??

          • Muhammet Sancaktutan

            i think you are right 🙂
            should i do like this picture? or say me pls , i want to like basic whatsapp app,
            i want to sent message, web to mobile , mobile to mobile ,mobile to web

          • This is fine.
            Note: you need to store all messages using SQLite.

        • Solution: you need to write a web service for that..

  • foufou H

    I have a SOAP service web. I add the function in my server and i create a form with input text message and title. I create a javascript call the function but doesn’t work.

    • Are you getting a success result in you SOAP ?

  • Marain Turchyn

    Great Job. I have been looking for the solution for 2 days, and with Yours articles I’ve done this for 30 minutes. You make my day!

    • Thanks for your support…!! ,you’re always welcome

  • Francesc Torrens

    Great job!

  • Adrian Vk

    Can you give an example of how it would be additionalData on PHP?

  • Victor Betikyan

    Thank you so much for this tutorial! Everything works great and I’m really excited to implement this in my apps!
    Although I don’t know whether if I did something wrong or if I’m missing something, but:
    1) A new notification doesn’t do the green LED flash
    2) I do not get any sound at all
    3) Vibration is very weak
    4) Changing the values of ‘vibration’ & ‘sound’ have no impact (I still get a weak vibration with no sound regardless if I point vibration to 0)
    Everything else works fantastically. Is this how its supposed to be or am I missing something?
    Thanks again!

    • 1) Green LED is not a part of this plugin, If you know native development you can customize that plugin
      2) Make sure the sound system (Volume of your phone)

  • Ruslan Sokolov

    Help please!

    Error 401

    • Make sure, your project id (SENDER_ID) and API_Key from same google project

      • sharatg

        Is this the SENDER_ID?


        • Ruben

          nope, SENDER_ID is the 12digit number found in the google developer console under “Project number”.
          $to adresses the receiver (device ID/Token), APA91bFIj2WLkD3W4kbZcGO7dyI is a api_key of yours.

    • Shamsheer AT

      Hi . Did you find a solution for this

  • pradeep

    hello Sir,

    How to crate 256 encreted code notification

  • Anuj

    Hello @sundara_vel:disqus ,

    Very Nice Tutorial . Everything Working Fine For Me . Only I have facing one issue that why the app not shows permission for Push Notification as other apps shows when first installed on device.

    Can you tell me about this issue?


    • This is because, your development environment, you won’t get this issue in production mode

  • pradeep

    Hy I have the same error as some peole here


    • Project ID & API Key should be from same Google project, If you’re facing problem again, Try from step 1 again

  • Guilherme

    Hi, I’m having the same error : {“multicast_id”:6940293719875667169,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]}

    To have it working does my account on google need to be a developer account? Thanks

    • Project ID & API Key should be from same Google project, If you’re facing problem again, try from step1 again

  • M. Syamsul Arifin

    finally, step 1,2,3 success… I only need customize anything.. thanks

  • Thank you very much!

  • Shamsheer AT

    I am getting

    Error 401

    My API key and sender_id is from same project only. Please help me

    • You need to add IP address for your server key

      • Javier Rocha


      • Anshul Khare

        Please tell how to add IP address for our server key?

        • madson g.

          Hi, did you find the solution?

          • Add in server key

          • madson g.

            I cannot find where to specify that in google´s new console. Can you help me?

          • madson g.

            I found it. Thanks!

          • Rajeswar Mohanty

            how you do

          • Rajeswar Mohanty

            ho gaya 🙂 – tons of thanks

          • madson g.

            Enter your console. Go to your project. Credentials. Edit the key you have created. Check up adresses and it will open an input for you to type

  • guido pardo

    Hi, great tutorial. But I’m having an issue, I can’t send the notifications, but the strange is that I haven’t any error or success message and the code hasn’t any break… Any idea of what is going wrong?
    The code is the same, I change the API_ACCESS_KEY and the registration ID but in the end $result is empty…

    • You just try again, or add server IP Address when you’re creating server Key

      • guido pardo

        Thanks for your answer! I found that curl_exec() function gave me back error number 28 (time out), but i tested the same code in another server in the same network and it worked fine… so I think it should be some issue in server configuration

  • madson g.

    Hi, I can send push notifications from my localhost adding to google´s console. When I try to execute the php script to send them from a remote server (hostinger) I´m receiving this error:

    “Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator at to inform them of the time this error occurred, and the actions you performed just before this error.

    More information about this error may be available in the server error log.”

    I added my domain ip to google´s console too but the problem is still happening. Do you know what could it be?

  • Talker77

    Can you Help me plz..
    This is my send.php. I checked firebase sender id and google api key. And created again.
    I read all these comments belowe. I tried all of them :(.
    But still getting


    And there is no message that pushed.

    I m going to attach service worker ss from my browsers..
    define(“GOOGLE_API_KEY”, “AIzaSyBPgxIV0KRevoyyRZx1MfCYzcfN0OLKUDw”);
    define(“GOOGLE_GCM_URL”, “”);
    function send_gcm_notify($reg_id, $message) {

    $fields = array(
    ‘registration_ids’ => array($reg_id ),
    ‘data’ => array( “message” => $message ),
    $headers = array(
    ‘Authorization: key=’ . GOOGLE_API_KEY,
    ‘Content-Type: application/json’
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
    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_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    $result = curl_exec($ch);
    if ($result === FALSE) {
    die(‘Problem occurred: ‘ . curl_error($ch));
    echo $result;
    $reg_id = “gAAAAABYFVyQWYE3AhVaVek9rQisZP5uAGs63RY8-cb7gYt6wWUKrb6kqs-KWZ7dgMO3BHbNdPu0hyfkf3KVt9Qv0W0xKs8noW4s3v9MWUpJlmINpZmz72525_KINjEJEE2ftUzQL6HR”;
    $msg = “Google Cloud Messaging working well”;

    send_gcm_notify($reg_id, $msg);

  • madson g.

    Hi, how can I send to multiple devices? I separated the tokens by commas but it did not work. I was reading docs and a notification_key must be created. How can I do it in your php script?

    • Anurag Singh

      did you found any answer ?

      • madson g.

        Yes. I was reading Google’s docs and I saw the way you must set the array to notifiationsIDs. You must select the tokens from database and set them to a var in an array with this format: [“xxxxx”, “xxxxx”, …] And then pass this var to $to

        • Xinee Wong

          Hi could you show the codes? I tried and couldn’t do it. Or maybe do u still have the link to the Google doc ? Thanks!

          • madson g.

            $sql = mysqli_query($mysqli, “SELECT token FROM users”);

            $registration_IDs = array();

            while($row = mysqli_fetch_array($sql)){

            $registration_IDs[] = $row[‘token’];


            $to = $registration_IDs;

            Sorry for late answer

  • Xinee Wong

    Great tutorials!!! I’ve actually implemented many tutorials from you and found them to be very helpful. I’m currently doing my school project and i need to implement push notifications with action buttons ‘Yes’ and ‘No’, with the results after clicking being sent back to the database. How can I implement this with your html and php codes?

    *P.S. I’m a beginner in coding! Sorry for the trouble!

  • sharatg

    I am getting this error. Any idea how to fix it?

    Invalid (legacy) Server-key delivered or Sender is not authorized to perform request.

    Error 401

  • Kavin Kumar

    while sending push notification from server i’m receiving the following error code
    Error: Received error code 401 from GCM Service

  • Gino

    Just wanna to say THANK YOU after following the steps and receiving my first remote notification!!! 🙂

  • Shafiq

    Hi, how can i save the registration ID to mysql database?

MyMail WordPress Plugin free
Save $50 USD on Ionic Firebase Chat Source CodeEXPLORE