Using Perl to send ACS Push Notifications

By | May 1, 2014

On my GloMotion App I’m sending push notifications to notify users about new followers, likes, etc.

To do this I have a cron running on my server which every 5 minutes polls the database to see if new activity has happened, and notify the corresponding users.

The script is in Perl, and I’m going to show you the basic gist of it so you can connect to the ACS API and make your own push notifications.

The modules we’ll be using are JSONLWP::UserAgent and REST::Client.

#!/usr/bin/perl -w

use strict;

use REST::Client;
use HTTP::Cookies;
use JSON;

my $ACS_KEY = '[YOUR ACS KEY]';
my $ACS_USERNAME = '[YOUR USERNAME]';
my $ACS_PASSWORD = '[YOUR PASSWORD]';

#Create a LWP::UserAgent with a cookie_jar to hold the login data
my $ua = LWP::UserAgent->new( cookie_jar => {} );

#Create our REST::Client
my $ACS = REST::Client->new( { useragent => $ua } );

#Login to ACS using an ACS username and password. We'll stayed login thanks to
#the cookie_jar
$ACS->POST(
    'http://api.cloud.appcelerator.com/v1/users/login.json?key='.$ACS_KEY,
    to_json({login => $ACS_USERNAME, password => $ACS_PASSWORD}),
    {
        "Content-type" => 'application/json'
    }
);
if( $ACS->responseCode() eq '200' ){
    print "Logged In\n";
}
else{
    print $ACS->responseContent();
    exit;
}


#Send a Push Notification Request
my $push_request = {
    'channel' => undef,
    'payload' => 'My Test Push Notification',
    'to_ids' => 'everyone',
};

$ACS->POST(
    'http://api.cloud.appcelerator.com/v1/push_notification/notify.json?key='.$ACS_KEY,
    to_json($push_request),
    {
        "Content-type" => 'application/json'
    }
);

if( $ACS->responseCode() eq '200' ){
    print "Push Sent\n";
}
else{
    print $ACS->responseContent();
    exit;
}

You should have your App registered with ACS. Then login to your ACS Panel go to your app overview and select on Users. There you should create an Admin user, whose credentials you’ll use on the script to be able to login through the API and send push notifications.

 

Targeting Specific Users

On the GloMotion app, since I’m sending notifications which are account specific, I needed a way to target a specific user for each notification. Right now ACS doesn’t have a way to filter by Device ID, which would have been great. But it does allow you to create channels, and register one or multiple devices to those channels.

So what I’m doing, is that for each device id, I’m generating a channel with the same name. So when I deliver a push notification all I have to do is target the channel. Right now is working wonderful.

 

Happy coding!

 

[box type=”shadow”] If you want to use PHP instead of Perl. @ricardoalcocer has a way to do it:
Cross-platform ACS Push Notifications with PHP[/box]

Leave a Reply