Child pages
  • Push notifications to devices

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Localtab Group
Localtab
titleApstrata script
Code Block
languagejs
<script>
	<scriptACL>
		<execute>nobody</execute>
		<read>nobody</read>
		<write>nobody</write>
	</scriptACL>
	<code>
		<![CDATA[
			
			// Prepare the parameters to pass to the ListUsers API in order to seachsearch for users
			// who registered more than n months ago
			var queryUsersParams = {
			    // Search for users who have a creation time <= the given date and that
			    "apsdb.query": "apsdb.creationTime<date> <= \"2014-07-01\" and pushToken is not null", 
			    // only return the login and pushToken attributes of the user's profile. We assume that we added the "pushToken" field to the users pofilesprofiles
			    "apsdb.attributes": "login, pushToken" 
			}
			
			// Execute the request by invoking the ListUsers API
			var response = apsdb.callApi("ListUsers", queryUsersParams, null);
			if (response.metadata.status == "failure") {
			    return response.metadata;
			}
			
			var users = response.result.users;
			if (users.length == 0) {
			    return {
			        "result": "No matching users"
			    }
			}
			
			// Create an array of device tokens (GCM registration ids) from the data returedreturned by the query
			var tokens = [];
			for (var i = 0; i < users.length; i++) {
			    tokens.push(users[i].pushToken[0]); // We assume that users only have one device token (GCM registration id)
			}
			
			// Prepare the parameters to pass to the push notification API
    		var notificationStr = "{\"Content\":\"Get 50% using this promotion code for your next purchase: AZX34W \"}";
			var pushParams = {
			    "apsdb.store": "DefaultStore",
			    "adhoc.tokens": tokens,
                "adhoc.lifeTime": "3600", // the lifetime in seconds of a notification before it is discarded if not pushed
                "adhoc.applicationID": "gcm", // the identifier of the push application in order to use the correct credentials
                "adhoc.platform": "Android",
                "fireAndForget": "false", // asynchronous pus, do not wait for a response
                "notification": notificationStr
			};
			
			// Call the PushNotification API
			var pushNotificationsResponse = apsdb.callApi("PushNotification", pushParams, null);
            if (pushNotificationsResponse.metadata.status == "failure") {
                return pushNotificationsResponse.metadata;
            }
            
            return pushNotificationsResponse;
		]]>
	</code>
</script>

 

 

...