Blog Post Icon
Blog
08/13/2015

Use PHP to send APNS iOS and GCM Android push notifications

Hello!

Through our own internal projects it has become a requirement in the past to implement a system that integrates with a mobile application. Specifically we have implemented systems that send out push notifications to iOS and Android based devices.

The conditions through which we would be sending the notifications are somewhat irrelevant, though it is important to indicate in this post that we are parsing a database of device IDs and tokens in order to build an array of devices to submit to the function that actually handles the push notifications.

This means that the workflow for this type of integration would involve someone downloading an application on their iOS or Android device that requests their permission to send push notifications. Once permissions are given, the application will send the device key to our systems which will then record it in a database for further use.

For APNS (Apple push notification service), you are required to register a certificate key that is associated with your application. This means that after permissions for push notifications is given, you are only able to authenticate messages to those authorized devices for your particular app. There is already a lot of documentation on how to create, install and integrate a development and production certificate for APNS.

For GCM (Google Cloud Messaging), you have to register with cloud messaging which will generate an API key that you will use to send messages. Much simpler than APNS in my opinion.

MySQL Database to store device info

I dont really need to spend much time on this, other than to highlight the schema we’re using in this particular scenario to better help you understand the functions for APNS and GCM notifications in PHP.

We use a mysql database to store device keys and uuid’s as registered and transmitted by the mobile app :

+----------------+--------------+------+-----+-------------------+-----------------------------+
| Field          | Type         | Null | Key | Default           | Extra                       |
+----------------+--------------+------+-----+-------------------+-----------------------------+
| dtoken         | varchar(255) | NO   | PRI |                   |                             |
| dtype          | varchar(10)  | YES  |     | NULL              |                             |
+----------------+--------------+------+-----+-------------------+-----------------------------+

“dtoken” is what we use to build an array of devices to notify. “dtype will store either the “iOS” or “Android” device types. This is how we split the notification to the proper category.

APNS Notification function in PHP

To build a function to send APNS, we used the APNSPHP implementation. There’s a lot of documentation and examples at the github page for this project that you may find helpful in your own custom implementation.

We took the example in this project and modified it to integrate as a standalone function to send push notifications to iOS devices :

function pushAPNS($pushmessage) {
    $push = new ApnsPHP_Push(
            ApnsPHP_Abstract::ENVIRONMENT_SANDBOX,
            'your-key.pem'
            );
  
  // get device tokens
  $pushdevices = array();
  $sql_getdevice = "SELECT dtoken from reg where dtype = 'iOS' DESC;";
  try {
          $db = connect_db();
          $result = $db->query($sql_getdevice);
          $sql_count = mysqli_num_rows($result);
          while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {
              $pushdevices[] = $row;
          }
       $db = NULL;
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
    if ($sql_count >= 1) {
        // do the actual push notification
        $push->connect();
        foreach ($pushdevices as $device) {
            $message = new ApnsPHP_Message($device['dtoken']);
            $message->setCustomIdentifier("Message-Badge-3");
            $message->setBadge(3);
            $message->setText('Message Alert : ' . $pushmessage);
            $message->setSound();
            $message->setExpiry(30);
            $push->add($message);
        }
    }
        $push->send();
        $push->disconnect();
        $aErrorQueue = $push->getErrors();
        if (!empty($aErrorQueue)) {
            var_dump($aErrorQueue);
        }
    }
}

Pretty straightforward, right? The function is called with the actual push message as a variable. Then we select applicable devices to send the message through and put it in an array, then apply the array to the push message variable and send.

GCM notifications in PHP

For GCM, we build a similar function but we’re using curl to connect to google’s API and send the message. You can see the original php example on Github that we used to build this function, or see the example below :

function pushGCM($pushmessage) {
    // API access key from Google API's Console
    define( 'API_ACCESS_KEY', 'YOUR-API-KEY' );
    $pushdevices = array();
    $sql_getdevice = "SELECT dtoken from reg where dtype = 'Android' order by registered_at DESC;";
        try {
                $db = connect_db();
                $result = $db->query($sql_getdevice);
                $sql_count = mysqli_num_rows($result);
                while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {
                        $pushdevices[] = $row['dtoken'];
                }
                $db = NULL;
        } catch(PDOException $e) {
                echo '{"error":{"text":'. $e->getMessage() .'}}';
        }


        if ($sql_count >= 1) {
        // prep the bundle
        $msg = array
        (
                'message'       => $pushmessage,
                'title'         => 'Alert',
                'subtitle'      => 'Alert message!',
                'tickerText'    => 'This alert happened.... this alert happened... this alert happened...',
                'vibrate'       => 1,
                'sound'         => 'default',
                'largeIcon'     => 'large_icon',
                'smallIcon'     => 'small_icon'
        );

                $headers = array
                (
                    'Authorization: key=' . API_ACCESS_KEY,
                        'Content-Type: application/json'
                );
        // loop through devices
        $fields = array
        (
                'registration_ids'      => $pushdevices,
                'data'                  => $msg
        );
        $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 );
    }
}

During your testing, you could set your php application so you can access these functions directly and var_dump the various output points in order to see whats happening, and in particular the debug response message that Google or Apple will send once the message has been sent.

I hope this helps you build your APNS or GCM notification systems! You dont always have to subscribe to 3rd party services unless you are looking at high volume notifications. Its very straightforward for an intermediate developer to implement their own systems free of charge! šŸ™‚

At Shift8, we cater to all sorts of businesses in and around Toronto from small, medium, large and enterprise projects. We are comfortable adapting to your existing processes and try our best to compliment communication and collaboration to the point where every step of the way is as efficient as possible.

Our projects are typically broken into 5 or 6 key “milestones” which focus heavily on the design collaboration in the early stages. We mock-up any interactive or unique page within your new website so that you get a clear picture of exactly how your design vision will be translated into a functional website.

Using tools like Basecamp and Redpen, we try to make the process simple yet fun and effective. We will revise your vision as many times as necessary until you are 100% happy, before moving to the functional, content integration and development phases of the project.

For the projects that are more development heavy, we make sure a considerable amount of effort is spent in the preliminary stages of project planning. We strongly believe that full transparency with a project development plan ensures that expectations are met on both sides between us and the client. We want to ensure that the project is broken into intelligent phases with accurate budgetary and timeline breakdowns.

Approved design mock-ups get translated into a browse-ready project site where we revise again and again until you are satisfied. Client satisfaction is our lifeblood and main motivation. We aren’t happy until you are.

Need Web Design?

Fill out the form to get a free consultation.

shift8 web toronto – 416-479-0685
203A-116 geary ave. toronto, on M6H 4H1, Canada
Ā© 2023. All Rights Reserved by Star Dot Hosting Inc.

contact us
phone: 416-479-0685
toll free: 1-866-932-9083 (press 1)
email: sales@shift8web.com

Shift8 Logo