Lesson 17: Send notifications to users

From VZ Developer Wiki
Jump to: navigation, search

General Guidelines | XML Specification | Features | Views | JavaScript API | REST API | Tutorials | OAuth


Lesson 16: Request additional data from your user Back to overview Lesson 18: Embedding a gadget into user generated content using an EMBEDPROVIDER view

There are two ways to to send notifications to your users:

From within the Gadget with the JavaScript API

function sendNotification(title, body) {
  var params = [];
  params[opensocial.Message.Field.TITLE] = title;
  params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.NOTIFICATION;
  // these parameters will be send as view_params to the gadget when the user clicks
  // on the notification link to the gadget
  params[opensocial.Message.Field.OPT_PARAMS] = {param1: 'abc', param2: 'def'};
 
  var message = opensocial.newMessage(body, params);
  var recipient = "VIEWER";
  opensocial.requestSendMessage(recipient, message, callback);
};
 
function callback(data) {
  if (data.hadError()) {
    alert("There was a problem:" + data.getErrorCode());
  } else {
    alert("Ok");
  }
};
 
sendNotification("This is a test notification", "How are you doing?");

It is important, that you set the message type correctly to NOTIFICATION. Recipient can be either VIEWER or OWNER or any other OpenSocial ID.

Alternatively you can create notifications from your backend through the REST or RPC API. The following examples show how to create notifications with a two-legged OAuth authentification which is used in context of an installed gadget.

Note that we use the OAuth Body Hash Spec Extension (http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) to prevent man-in-the-middle attacks on the POST body, so you have to hash the POST body accordingly.

For a list of OAuth client libraries see OAuth_Libraries.

From your backend with the RPC API

Example in PHP:

<?php
//require the php OAuth library
require_once "oauth.php";

//set your consumer information
$consumerToken  = 'CONSUMER_KEY';
$consumerSecret = 'CONSUMER_SECRET';
$consumer = new OAuthConsumer($consumerToken, $consumerSecret);

//the user to which you want to send the notification
$userId = 'OPENSOCIAL_ID';

//the rpc endpoint
$url = 'http://GADGET_SERVER_ENDPOINT/social/rpc';

$params = array('xoauth_requestor_id' => $userId);

//now create your requests, you can batch several requests into one http request
$msg = array();
$msg[] = array('method' => 'messages.create',
        'params' => array(
                'userId' => $userId,
                'message' => array(
                        'recipients' => array($userId),
                        'title' => 'This is a test notification1',
                        'body'  => 'How are you doing?',
                        'type'  => 'notification',
                )
        ),
        'id' => 'requestOne',
);
//the second request
$msg[] = array('method' => 'messages.create',
        'params' => array(
                'userId' => $userId,
                'message' => array(
                        'recipients' => array($userId),
                        'title' => 'This is a test notification2',
                        'body'  => 'How are you doing?',
                        'type'  => 'notification',
                )
        ),
        'id' => 'requestTwo',
);

//encode the requests and create oauth_body_hash
$encodedMsg = json_encode($msg);
$bodyHash = base64_encode(hash_hmac('sha1', $encodedMsg, $consumerSecret . '&', true));
$params['oauth_body_hash'] = $bodyHash;

//now create the oauth signature for the request
$outreq = OAuthRequest::from_consumer_and_token($consumer, null, 'POST', $url, $params);
$sig = new OAuthSignatureMethod_HMAC_SHA1();
$outreq->sign_request($sig, $consumer, null);

//create the url parameter string
$params =  $outreq->get_parameters();
$pairs = array();
foreach ($params as $key => $value) {
    $pairs[] = $key . '=' . urlencode($value);
}
$pstring = implode('&', $pairs);

//send the request with curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . $pstring);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedMsg);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
var_dump($response);

A request may look like this:

URL:

http://studivz.gadgets.apivz.net/social/rpc?oauth_version=1.0&oauth_nonce=...&oauth_timestamp=...&oauth_consumer_key=...&xoauth_requestor_id=www.vz.net%3A...&oauth_body_hash=...&oauth_signature_method=HMAC-SHA1&oauth_signature=...

Body:

[{"method":"messages.create","params":{"userId":"www.vz.net:...","message":{"recipients":["www.vz.net:..."],"title":"This is a test notification1","body":"How are you doing?","type":"notification"}},"id":"requestOne"},{"method":"messages.create","params":{"userId":"www.vz.net:...","message":{"recipients":["www.vz.net:..."],"title":"This is a test notification2","body":"How are you doing?","type":"notification"}},"id":"requestTwo"}]

From your backend with the REST API

Example in PHP:

<?php
//require the php OAuth library
require_once "oauth.php";

//set your consumer information
$consumerToken  = 'CONSUMER_KEY';
$consumerSecret = 'CONSUMER_SECRET';
$consumer = new OAuthConsumer($consumerToken, $consumerSecret);

//the user to which you want to send the notification
$userId = 'USER_ID';

//the rpc endpoint
$url = 'http://sandbox.shindig.svz-pcn-107/social/rest/messages/' . $userId;

$params = array('xoauth_requestor_id' => $userId);

//now create your requests, you can batch several requests into one http request
$msg = array(
        'title' => 'This is a test notification',
        'body'  => 'How are you doing?',
        'type'  => 'notification',
);

//encode the requests and create oauth_body_hash
$encodedMsg = json_encode($msg);
$bodyHash = base64_encode(hash_hmac('sha1', $encodedMsg, $consumerSecret . '&', true));
$params['oauth_body_hash'] = $bodyHash;

//now create the oauth signature for the request
$outreq = OAuthRequest::from_consumer_and_token($consumer, null, 'POST', $url, $params);
$sig = new OAuthSignatureMethod_HMAC_SHA1();
$outreq->sign_request($sig, $consumer, null);

//create the url parameter string
$params =  $outreq->get_parameters();
$pairs = array();
foreach ($params as $key => $value) {
    $pairs[] = $key . '=' . urlencode($value);
}
$pstring = implode('&', $pairs);

//send the request with curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . $pstring);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedMsg);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
var_dump($response);

Example in Ruby:

require 'oauth'
require 'oauth/consumer'
require 'oauth/request_proxy/action_controller_request'
require 'oauth/signature/hmac/sha1'
require 'uri'

def send_notification(user_id)
      endpoints = {
        :avz => "http://meinvz.gadgets.apivz.net",
        :svz => "http://studivz.gadgets.apivz.net",
        :pvz => "http://schuelervz.gadgets.apivz.net",
        :sandbox => "http://sandbox.gadgets.apivz.net"
      }
      
      endpoint = endpoints[:sandbox]
      endpoint = endpoints[:avz] if user_id.include?("www.vz")
      endpoint = endpoints[:pvz] if user_id.include?("www.schuelervz")

      secret = "CONSUMER_SECRET"
      
      @consumer = OAuth::Consumer.new(
        CONSUMER_KEY, secret,
        :signature_method => 'HMAC-SHA1',
        :site => endpoint,
        :scheme => :header,
        :http_method => :post
      )

      @access_token = OAuth::AccessToken.new(@consumer)
      @testdata = '{"title": "hallo", "body": "bodytest", "type": "notification"}'
      @response = @access_token.post("/social/rest/messages/@me?xoauth_requestor_id=" + user_id, @testdata, {"Content-Type" => "application/json"})
    end

puts send_notification("OPENSOCIAL_ID")

The resulting request may look like this:

URL:

http://studivz.gadgets.apivz.net/social/rest/messages/www.vz.net:...?oauth_version=1.0&oauth_nonce=...&oauth_timestamp=...&oauth_consumer_key=...&xoauth_requestor_id=www.vz.net%3A...&oauth_body_hash=...&oauth_signature_method=HMAC-SHA1&oauth_signature=...

Body:

{"title":"This is a test notification","body":"How are you doing?","type":"notification"}

Quota

For the Message Type opensocial.Message.Type.NOTIFICATION the following quota is enforced on production
  • To one user you can only send three notifications a day
  • The message yon send to an user hast to be different from the notification message you send before
  • Notifications are NOT limited to a specific number of characters


  • Lesson 17: Send notifications to users