Click here to Skip to main content
15,881,172 members
Articles / Mobile Apps

Sending Push Notifications from a Drupal Site

Rate me:
Please Sign up or sign in to vote.
4.95/5 (15 votes)
6 May 2015CPOL10 min read 44.4K   18   10
How to integrate push notifications on your Drupal 7 site and your Titanium Apps

Introduction

With this article, I want to share how to integrate the management of push notifications on your Drupal site using the Apple and Android notification services.

In this scenario, you have a personal or corporate App deployed in Apple (Apple Store) and Google (Google Play) App markets, and you want to send push notifications to the users of both Apps from your Drupal site.

In this example, the apps are developed with Titanium Appcelerator, so the App's code described in this solution will fit this requirement. If you are using native code (Objective C with iOS or Java with Android), just adapt the steps involving the client applications using the native API.

It's supposed that you know how to administer a Drupal 7 site, for installing modules, etc.

Background

Useful links to the technologies used in this integration are listed below:

Drupal: https://drupal.org/

Architecture

Image 1

Requirements

An iOS Developer Program Account. This is necessary to:

  1. generate the certificate that the provider (your Drupal 7 site) will use to send the notifications to the APNs
  2. generate the certificate, application ID and provisioning profile to be used to distribute the application that will receive the notifications

A Google Account. This is necessary to:

  1. create a Google API Project (generates a Project ID and a Project number)
  2. enable the GCM (Google Cloud Messaging) service for this project
  3. obtain a server API Key

A Drupal 7 site with some modules installed and configured:

  1. Push Notifications module: https://www.drupal.org/project/push_notifications
  2. Services module: https://www.drupal.org/project/services
  3. Libraries module: https://www.drupal.org/project/libraries

Description

In this scenario, you have a personal or corporate App deployed in Apple and Google App markets (Apple Store and Google Play) developed with Appcelerator Titanium, and you want to send push notifications to the users of both Apps from your Drupal site.

Drupal: Steps

  1. Install Services module, go to https://www.drupal.org/project/services, download the package and install it manually, or use the installing packages utility in the "modules" section of your Drupal site administration (Install new module). This module requires Chaos Tools module, so if it's not installed, install it before. https://www.drupal.org/project/ctools
  2. Enable Services module through Drupal's modules administration.
  3. Install and enable Push Notifications module, go to https://www.drupal.org/project/push_notifications, download the package and install it manually, or use the installing packages utility in the "modules" section of your Drupal site administration (Install new module).
  4. Enable Push Notifications module through Drupal's modules administration.
  5. Install and enable Libraries module, go to https://www.drupal.org/project/libraries, download the package and install it manually, or use the installing packages utility in the "modules" section of your Drupal site administration (Install new module).
  6. Enable Libraries module through Drupal's modules administration.
  7. When you have installed the Services module, another module is installed transparently, the REST Server module. The only thing you have to do is to enable this module too, through Drupal's modules administration.
  8. Now you have to create an http endpoint to be used for creating and deleting the device tokens that will be stored and used to send the push notifications. For example, if your site is published in https://www.mysite.com, and you want to call the endpoint "myendpoint", do this:
    • Go to the Drupal module's administration page.
    • Click on the link "Configure" of the Services module.
    • Click on the link "Add" (adds a new endpoint), a form is shown.
    • Fill the form with:
      1. Machine-readable name of the endpoint: write "myendpoint"
      2. Server: Select "REST"
      3. Path to endpoint: write "myendpoint"
      4. Click "Save" Button

When the endpoint appears in the endpoints list, configure push notifications resources to be attached to this endpoint. To do that:

  1. Click on link "Edit resources"
  2. In the resources list, select the check box of "push_notifications" resource, all the methods of this resource will also be selected (create and delete)

If your site is published in https://www.mysite.com, and the endpoint has been named "myendpoint", you can access this resources via https://www.mysite.com/myendpoint/push_notifications, and you will need to:

  • Do a POST for creating a new device token.
  • Do a DELETE for deleting a existing device token.

Backend Configuration for iOS Notifications: Steps

The most important thing in iOS environments to work with Push notifications is to generate correctly the certificates and provisioning profiles. You will need two certificates:

One for the App, used to distribute the application in the Apple Store, and used to generate a Provisioning Profile for distribution. To know more about client certificates, App IDs, Devices and Provisioning profiles (all necessary for the client side - app), you must know how iOS developer platform works, this is a resume:

  1. Generate a certificate (iOS App Development certificate for development environments or Distribution / AdHoc certificate for the production environment)
  2. Register an iOS App ID identifier for your App, with the Push notifications service enabled.
  3. If you work in a development environment and want to distribute the app for testing, you must enable the user's devices that will test adding the UUIDs of that devices.
  4. Generate a provisioning profile that will attach a certificate and an App ID in a file necessary to distribute the App.

One for the server, you will need another certificate for the Push notifications Server provider (your Drupal site that runs under Apache). These steps will help you to generate a development certificate, the steps for a production are the same but selecting distribution or production items. All these steps must be done in a MAC OS computer.

  1. Go to the iOs developer program web page, signin and access the "Certificates, Identifiers and profiles" section.
  2. Add a new certificate - Development - and select the "Apple Push Notification service SSL (Sandbox)" option. Click on the "continue" button.
  3. Select the App ID of the application that will receive push notifications via this certificate. Click on the "continue" button.
  4. To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions of the page that appears to create one using Keychain Access.
  5. Upload the CSR file saved on your MAC computer.
  6. Download the certificate to your Mac, then double click the .cer file to install in keychain access (used to be apns_development.cer).
  7. Export that certificate (.cer) to .p12.

    To export the certificate to .p12 is necessary to have the private key used to generate the certificate (when you first generated your certificate, you first had to create a CSR (certificate signing request) with Keychain - steps 4 and 5) . This puts the private key in your Keychain. You then submit the CSR to the Apple Developer portal, which would give you the certificate back).

    In the Keychain Access tool, select the category "My certificates", and select the certificate and the private key - both!, this is very important - and right click to show the menu, click on "Export 2 items".

    Image 2

  8. Convert the .p12 certificate to .pem: For this step, you need to install openssl utility, if it's not installed in your OS (Linux, Mac). The command to convert is:
    openssl pkcs12 -in apns_development.p12 -out apns_development.pem -clcerts -nodes
  9. Deploy the .pem file to the "certificates" folder of your Drupal's site Push Notifications module (this is the default configuration of the module). For example, /var/www/yoursite/sites/all/modules/push_notifications/certificates

Titanium - iOS Application

In this case, we have developed the iOs App using Titanium Mobile Development Environment http://www.appcelerator.com/titanium

There aren't too many Titanium modules developed to manage both push notifications services, GCM (Google Cloud Messaging for Android apps) and APN (Apple Push Notifications) at the same time. The best solution actually is to use the Titanium Network API to manage iOS push notifications, and an external module for Android Push Notifications.

The steps to configure and manage the push notifications in an iOS Titanium App are:

Create a JavaScript module (for example, m_push_notifications.js) with a public method that will be called when we'll want to initialize the push notifications. This initialization involves:

  1. Register the App for push notifications. This calls the APNs service that will give us a device token. The device token is analogous to a phone number; it contains information that enables APNs to locate the device on which the client application is installed. APNs also use it to authenticate the routing of a notification.
  2. Implement the callback that will manage the device token received after the registering. In this case, we must call our Drupal's backend API to register the device token in the Provider.
  3. Implement the callback to manage device token error receptions.
  4. Implement the callback to manage the reception of a push notification message. We receive the message in a JavaScript object.
    JavaScript
    exports.initPushNotifications = function() {  
        if(Alloy.isIos)
        {        
            var iosDeviceToken = null;
            
            Ti.Network.registerForPushNotifications({
            // Specifies which notifications to receive
                types: [
                    Ti.Network.NOTIFICATION_TYPE_BADGE,
                    Ti.Network.NOTIFICATION_TYPE_ALERT,
                    Ti.Network.NOTIFICATION_TYPE_SOUND
                ],
                success: iosDeviceTokenSuccess,
                error: iosDeviceTokenError,
                callback: iosReceivePush
            });
            
            function iosReceivePush(e) {
                customAlert(e.data.aps.alert);            
            }
            
            // Save the device token on the backend (Push Provider)
            function iosDeviceTokenSuccess(e) {
     
                // Compose the Payload to be sent to the PUSH Provider
                payload ={ 
                    token : e.deviceToken,
                    type : 'ios'
                };    
                
                // Call
                client = Ti.Network.createHTTPClient({
                    // function called when the response data is available
                    onload : function(e) {
                        console.log("OK : " + e.text);
                    },
                    // function called when an error occurs, including a timeout
                    onerror : function(e) {
                        console.log("ERROR : " +  e.error);
                    },
                    timeout : 3000,  // in milliseconds
                    // If it's an https connection, to validate or not the certificate
                    validatesSecureCertificate: Alloy.CFG.VALIDATE_SECURE_CERTIFICATE
                });
                
                client.setRequestHeader("Content-Type", contentType);
                // Prepare the connection.
                client.open("POST", 'http://yourserverurl/endpoint/push_notifications');
                // Send the request.
                client.send(payload);
            }
            
            function iosDeviceTokenError(e) {
                customAlert('Failed to register for iOS push notifications! ' + e.error);
            }
        } 
    }

Backend Configuration for Android Notifications: Steps

In this case, it's very simple. You only need to have a Google account, create a project related to your App, activate the GCM Service and create an API key to be used as the configuration of your Drupal's Push Notification module. Follow these steps:

1) Create the Project

  • Sign in to your Google account.
  • Go to the Google developers console, https://console.developers.google.com/

    Image 3

  • Click on "Create Project" button.
  • Fill in the form with your desired data: Project Name and Project-ID

    Image 4

  • Click on the "Create" button. This will generate the Project and will redirect you to the Project Dashboard page.

2) Activate the GCM Service for Android

  • In the Project Dashboard, click on the "APIs" link under the "APIs & auth" menu.
  • This will show you a list of Google APIs (enabled or not). Search for the "Google Cloud Messaging for Android" service and enable it, clicking on the "OFF" button.

    Image 5

3) Create an API Key for Your Server

  • In the Project Dashboard, click on the "Credentials" link under the "APIs & auth" menu.
  • Click on the "Create new Key" button.
  • Click on the "Server Key" button. Select the IP's range or addresses for receiving requests (the public IP of your Drupal server, or none if you want to use this service from anywhere)
  • Click on the "Create" button.
  • A Key for servers information will appear. Select the API KEY generated and copy it.

4) Configure your Drupal's Push Notifications Module to use this API KEY

  • Go to the Drupal module's administration page.
  • Click on the link "Configure" of the Push Notifications module.
  • Click on the "CONFIGURATION" tab.
  • In the GOOGLE CLOUD MESSAGING section, fill the text box "Google Cloud Messaging API Key" with the key provided in the last step.
  • Click on the "Save Configuration" button.

That's it! Easier.

Titanium - Android Application

In the case of integrating the push notifications with the Android platform using Titanium, we need an external module to solve this. I recommend you two modules:

  1. IamYellow's GCM Push Notifications Module for Titanium (https://github.com/iamyellow/gcm.js) , http://iamyellow.net/post/40100981563/gcm-appcelerator-titanium-module
  2. Liccowee's GCM in titanium: https://github.com/liccowee/Google-Cloud-Messaging--Titanium-

All the code explained here is done with the second one (Liccowee's).

The steps to configure and manage the push notifications in an Android Titanium App are: In the created JavaScript module m_push_notifications.js, in the public method created that inits push notifications add the code that manages Android's ones. This involves:

  1. Configure the tiapp.xml configuration file to enable GCM push notifications.
    XML
    <property name="com.activate.gcm.sender_id" type="string">XXXXXXXXX</property>
      <property name="com.activate.gcm.icon" type="int">2130837504</property>
      <property name="com.activate.gcm.component" type="string">
       com.entelgy.telemadrid.haztutele/com.entelgy.telemadrid.haztutele.HaztuteleActivity
      </property>
    

    The property sender_id value (in this case XXXXXXXXXX) must have the project id value of the project generated in the Google developer console.

  2. Import the module gcm.
  3. Register the App for push notifications. This calls the GCM service that will give us a Register ID.
  4. Implement the callback that will manage the Register ID received after the registering. In this case, we must call our Drupal's backend API to register the device token in the Provider.
  5. Implement the callback to manage Register ID error receptions.
  6. Implement the callback to manage the reception of a push notification message. We receive the message in a JavaScript object.
    JavaScript
    gcm = require('com.activate.gcm');
     
    if(Alloy.isAndroid){
            var hostURL = 'http://urlmyhost/endpoint/push_notifications';
            
            gcm.registerC2dm({
                    success:function(e){     
                        var regId = e.registrationId;
     
                        var payload = { 
                            token : e.registrationId,
                            type : 'android'
                        };
     
                        client = Ti.Network.createHTTPClient({
                            onload : function(e) {
                                Ti.API.info("Register device token in CMS  success");
                            },
                            // function called when an error occurs, including a timeout
                            onerror : function(e) {
                                Ti.API.error("Register device token in CMS  error");
                            },
                            timeout : 3000,  // in milliseconds
                            validatesSecureCertificate: Alloy.CFG.VALIDATE_SECURE_CERTIFICATE
                        });
                
                        client.setRequestHeader("Content-Type", contentType);
                        client.open("POST", urlPushProvider);
                        client.send(payload);            
                    },
                    error:function(e){
                        Ti.API.error("Error during registration : " + e.error);
                        
                        var message;
                        if(e.error == "ACCOUNT_MISSING"){
                            message = "No Google account found; 
                            you will need to add on in order to activate notifications";
                        }
                        else{
                            message = e.error;                        
                        }
                    },
                    // Callback executed when a push notification has been received
                    callback : function ( e ) {    
                        processAndroidNotification(e);  
                    }
                }
            );
        }

History

  • 6th May, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Spain Spain
Software Engineer with over 15 years of experience in Software development projects assuming several responsibilities and performing heterogeneous profiles. Experience in management and participation in projects with different location members, developing applications with different architectural styles and with several technologies and frameworks.

Passionate about mobility, Cloud Computing and Big Data.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Santhakumar Munuswamy @ Chennai6-May-15 15:33
professionalSanthakumar Munuswamy @ Chennai6-May-15 15:33 
QuestionHow receive the deviceID with the druapl userID. Pin
Member 1152915116-Mar-15 3:38
Member 1152915116-Mar-15 3:38 
QuestionMy vote of 5 Pin
Volynsky Alex17-Nov-14 2:02
professionalVolynsky Alex17-Nov-14 2:02 
AnswerRe: My vote of 5 Pin
Ricardo Trujillo Rodríguez17-Nov-14 5:32
Ricardo Trujillo Rodríguez17-Nov-14 5:32 
GeneralRe: My vote of 5 Pin
Volynsky Alex17-Nov-14 6:31
professionalVolynsky Alex17-Nov-14 6:31 
GeneralMy vote of 5 Pin
iRakeshJha10-Nov-14 22:32
professionaliRakeshJha10-Nov-14 22:32 
GeneralRe: My vote of 5 Pin
Ricardo Trujillo Rodríguez10-Nov-14 22:37
Ricardo Trujillo Rodríguez10-Nov-14 22:37 
GeneralMy vote of 5 Pin
priti@cp6-Nov-14 0:16
professionalpriti@cp6-Nov-14 0:16 
GeneralMy vote of 5 Pin
Member 1108233828-Oct-14 17:54
Member 1108233828-Oct-14 17:54 
GeneralRe: My vote of 5 Pin
Ricardo Trujillo Rodríguez29-Oct-14 1:41
Ricardo Trujillo Rodríguez29-Oct-14 1:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.