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 | | +----------------+--------------+------+-----+-------------------+-----------------------------+ 1 2 3 4 5 6 + -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- + -- -- - + -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + | 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); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 - & gt ; query ( $ sql_getdevice ) ; $ sql_count = mysqli_num_rows ( $ result ) ; while ( $ row = $ result - & gt ; fetch_array ( MYSQLI_ASSOC ) ) { $ pushdevices [ ] = $ row ; } $ db = NULL ; } catch ( PDOException $ e ) { echo '{"error":{"text":' . $ e - & gt ; getMessage ( ) . '}}' ; } if ( $ sql_count & gt ; = 1 ) { // do the actual push notification $ push - & gt ; connect ( ) ; foreach ( $ pushdevices as $ device ) { $ message = new ApnsPHP_Message ( $ device [ 'dtoken' ] ) ; $ message - & gt ; setCustomIdentifier ( "Message-Badge-3" ) ; $ message - & gt ; setBadge ( 3 ) ; $ message - & gt ; setText ( 'Message Alert : ' . $ pushmessage ) ; $ message - & gt ; setSound ( ) ; $ message - & gt ; setExpiry ( 30 ) ; $ push - & gt ; add ( $ message ) ; } } $ push - & gt ; send ( ) ; $ push - & gt ; disconnect ( ) ; $ aErrorQueue = $ push - & gt ; 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 ); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 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 - & gt ; query ( $ sql_getdevice ) ; $ sql_count = mysqli_num_rows ( $ result ) ; while ( $ row = $ result - & gt ; fetch_array ( MYSQLI_ASSOC ) ) { $ pushdevices [ ] = $ row [ 'dtoken' ] ; } $ db = NULL ; } catch ( PDOException $ e ) { echo '{"error":{"text":' . $ e - & gt ; getMessage ( ) . '}}' ; } if ( $ sql_count & gt ; = 1 ) { // prep the bundle $ msg = array ( 'message' =& gt ; $ pushmessage , 'title' =& gt ; 'Alert' , 'subtitle' =& gt ; 'Alert message!' , 'tickerText' =& gt ; 'This alert happened.... this alert happened... this alert happened...' , 'vibrate' =& gt ; 1 , 'sound' =& gt ; 'default' , 'largeIcon' =& gt ; 'large_icon' , 'smallIcon' =& gt ; 'small_icon' ) ; $ headers = array ( 'Authorization: key=' . API_ACCESS_KEY , 'Content-Type: application/json' ) ; // loop through devices $ fields = array ( 'registration_ids' =& gt ; $ pushdevices , 'data' =& gt ; $ 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! 🙂