Click here to Skip to main content
Click here to Skip to main content

Sending Push Notifications from a Drupal site

, 22 Oct 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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 you 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 now how to administer a Drupal 7 site, for installing modules, etc.

Background

Useful links to the technologies used in this integration :

Drupal : https://drupal.org/

Architecture

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, aplication ID and provisioning profile to be used to distribute the application that will receive the notifications

A Google Account. This is necessary for:

  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. To 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 throw 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 throw 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 throw Drupal's modules administration.

7) When you have installed the Services module, another module is installed trasnparently, the REST Server module. The only thing you have to do is to enable this module too, throw Drupal's modules administration

8) Now you have to create a http endpoint to be used for creating and deleting the device tokens that wil 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 be also selected ( create and delete)

If your site is published in https://www.mysite.com , and the endpoint has been named "myendpoint", yo can access to this resources via https://www.mysite.com/myendpoint/push_notifications, and yo 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 importat thing in iOS environments to work with Push notifications, is to generate correctly the certificates and povisioning 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 plataform works, this is a resume:

1) Generate a certificate (iOS App Development certificate for development environments or Distribution / AdHoc certificate for the production enviroment)

2) Register an iOS App ID identifier for you App, with the Push notifications service enabled.

3) If you work in a develomennt 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 who 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). This steps will help you to generate a development certificate, the steps for a production are the same but selecting distribution or production items. All this steps must be done in a MAC OS computer.

1) Go to the iOs developer program web page, sigin and access to 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 notificactions 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 clik 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".

8) Conver the .p12 certificate to .pem : For this step you need to install openssl utility, if it's not installed in you OS (Linux, Mac). The command to convert is:

openssl pkcs12 -in apns_development.p12 -out apns_development.pem -clcerts -nokeys

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 a external module for Android Push Notificacions.

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 initialialization 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 uses 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.

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 de 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 configiration of your Drupal's Push Notification module. Follow this steps :

1) Create the Project

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

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

2) Activate de 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.

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 adresses for receiveing 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 you 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.
  • Clik 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 explain 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 init's push notifications add the code that manages Android's ones. This involves: 1) Configure the tiapp.xml configuration file to enable GCM push notifications.

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

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 excecuted when a push notification has been received
                callback : function ( e ) {    
                    processAndroidNotification(e);  
                }
            }
        );
    }

License

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

Share

About the Author

Ricardo Trujillo Rodríguez
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 at projects with different resources, developing applications with different architectural styles and with several technologies and frameworks.
 
Passionate about mobility, Cloud Computing and Big Data.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 22 Oct 2014
Article Copyright 2014 by Ricardo Trujillo Rodríguez
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid