SelectPubNub REST API Documentation

Common REST Query String Parameters

The following parameters should be used on all REST calls being made to PubNub.

  • uuid – required - A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

  • auth – optional - A PAM (access control) token, to be used on PAM-enabled endpoints:

    • Publishing
    • Subscribing
    • History
    • Channel Group operations
  • signature – optional - Only to be used for PAM admin REST calls (grant, audit).

  • pnsdk – required - An identifier which uniquely identifies your client SDK. This should be of the format CompanyName-ProgrammingLanguageUsed/YourClientSDKVersion (e.g. CompanyABC-JS/1.0). Please contact support@pubnub.com for further information.

Common HTTP Request Headers

The following HTTP headers should be used across all PubNub REST requests.

  • Content-Encoding - When sending compressed, gzipped data via POST requests, set value as gzip

  • Content-Type - Always use application/json; charset=UTF-8 when sending JSON, and using UTF-8

  • Accept-Encoding - If your client supports gzip, set this value to gzip, if your client supports deflate, set this value to deflate, if it supports both, set this value to gzip, deflate and if it supports neither, omit this header altogether.

Common HTTP Status Codes

The following HTTP Status codes should be treated the same across all PubNub REST responses.

  • 200 – The REST call was successful. Refer to the detail usage by operation for more information on parsing the response.

  • 403 – The REST call was unsuccessful, due to a PAM (access control) issue. Try again, without an auth URL parameter, or with a different auth URL parameter.

Publish / Subscribe

Publish V1 via GET

Publish a message to a channel.

Publish v1 - Valid / Success Responses

Successful (HTTP Status 200) Publish() calls will always return a three-element array:

  • Array Element 0 - Integer – 1 or 0, where 1 is success, and 0 is error.

  • Array Element 1 - String – Description of the success or error, if available.

  • Array Element 2 - String – The current PubNub time expressed as a Timetoken, on success only.

A sample response from server [1,"Sent","14375189629170609"] contains the following fields:

  • The first element is an integer of value 1 representing success.

  • The second element is a string description of the success, which for 200 response codes will always be "Sent".

  • The third element is the string Timetoken value the system accepted the Publish() operation at.

Publish v1 - Invalid / Error Responses

In the event of an error, you will receive a non-200 HTTP status code. Depending on the error, you may or may not have a parseable array returned. If you do, and it has a second element, and that element is a string, you may parse it for a description of the error.

Errors specific to Publish() will occur when URL (e.g., message payload) is too large (>=32K), and invalid publish and/or subscribe keys are used.

Publish JSON to channel via GETGET/publish/{pub_key}/{sub_key}/0/{channel}/{callback}/{payload}{?store,uuid}

Example URI

GET https://ps.pndsn.com/publish/myPubKey/mySubKey/0/ch1/myCallback/%7B%22text%22%3A%22hey%22%7D?store=0&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
pub_key
string (required) Example: myPubKey

the publish key to use

sub_key
string (required) Example: mySubKey

the subscriber key

channel
string (required) Example: ch1

the destination of the message

callback
string (required) Example: myCallback

response will be wrapped in JSONP function, 0 for no JSONP

payload
string (required) Example: %7B%22text%22%3A%22hey%22%7D

url-encoded JSON

store
number (optional) Example: 0

this parameter overrides default account configuration on message saving. 1 to Save, 0 to not save.

auth
string (optional) Example: "authKey"

If the channel is protected by PAM, auth must be passed with a key which is authorized to publish to the channel.

meta
object (optional) Example: meta={"cool":"meta"}

used to send additional information about the message which can be used on stream filtering.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  without JSONP
HideShow
Headers
Location: /publish/myPubKey/mySubKey/ch1/0/%7B%22text%22%3A%22hey%22%7D
Response  200
HideShow
Headers
Content-Type: application/json
Body
[
  1,
  "Sent",
  "14375220012064619"
]
Request  with JSONP
HideShow
Headers
Location: /publish/myPubKey/mySubKey/ch1/myCallback/%7B%22text%22%3A%22hey%22%7D
Response  200
HideShow
Headers
Content-Type: application/json
Body
myCallback([1,"Sent","14375220012064619"])

Publish V1 via POST

Publish a message to a channel.

Publish JSON to channel via POSTPOST/publish/{pub_key}/{sub_key}/0/{channel}/{callback}{?store,uuid}

Example URI

POST https://ps.pndsn.com/publish/myPubKey/mySubKey/0/ch1/myCallback?store=0&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
pub_key
string (required) Example: myPubKey

the publish key to use

sub_key
string (required) Example: mySubKey

the subscriber key

channel
string (required) Example: ch1

the destination of the message

callback
string (required) Example: myCallback

response will be wrapped in JSONP function, 0 for no JSONP

store
number (optional) Example: 0

this parameter overrides default account configuration on message saving. 1 to save, 0 to not save.

auth
string (optional) Example: "authKey"

If the channel is protected by PAM, auth must be passed with a key which is authorized to write to the channel.

meta
object (optional) Example: meta={"cool":"meta"}

used to send additional information about the message which can be used on stream filtering.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  without JSONP
HideShow
Headers
Content-Type: application/json
Location: /publish/myPubKey/mySubKey/ch1/0
Body
{
  "message": "All your base are belong to us."
}
Response  200
HideShow
Headers
Content-Type: application/json
Body
[
  1,
  "Sent",
  "14375220012064619"
]
Request  with JSONP
HideShow
Headers
Location: /publish/myPubKey/mySubKey/ch1/myCallback/%7B%22text%22%3A%22hey%22%7D
Body
{
  "message": "All your base are belong to us."
}
Response  200
HideShow
Headers
Content-Type: application/json
Body
myCallback([1,"Sent","14375220012064619"])

Fire

The fire endpoint allows the client to send a message to BLOCKS Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.

FireGET/publish/{pub_key}/{sub_key}/0/{channel}/{callback}?&norep=true&store=0

Example URI

GET https://ps.pndsn.com/publish/myPubKey/mySubKey/0/ch1/myCallback/{"text"%3A"hey"}?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561&norep=true&store=0
URI Parameters
pub_key
string (required) Example: myPubKey

The publish key to use.

sub_key
string (required) Example: mySubKey

The subscriber key.

channel
string (required) Example: ch1

The destination of the message.

callback
string (required) Example: myCallback

Response will be wrapped in JSONP function, 0 for no JSONP.

store
number (required, should be 0 for Fire)

norep
boolean (required, should be true for Fire)

auth
string (optional) Example: "authKey"

If the channel is protected by PAM, auth must be passed with a key which is authorized to write to the channel.

meta
object (optional) Example: meta={"cool":"meta"}

Used to send additional information about the message which can be used on stream filtering.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request without JSONP
Response 200
Request with JSONP
Response 200

Subscribe

Subscribe to messages on channels and/or channel groups.

Subscribe v1 - Valid / Success Responses

Successful responses (200) return a three-element array:

  • Array Element 0 - Array - An array consisting of messages.

  • Array Element 1 - String - The next timetoken to connect with.

  • Array Element 2 - String - A CSV (not array) of the channels associated, in order, with the messages in array element 0. If the is an empty heartbeat response, or an empty initial timetoken 0 response, or you are only subscribed to a single channel or channel group, this element will not be returned.

  • Array Element 3 - String -When subscribed to one or more channel groups, array element 3 appears. It is a CSV (not array) of the "real channel" name associated with the channel group name.

If you are subscribed to a channel group named myCG, and you receive a message on myCG from a member channel named myCH, array element 2 will contain "myCG", and the corresponding entry in element 3 will be "myCH".

When subscribing to both channels and channel groups, the corresponding entry for an non-CG member channel will be identical to that of the entry for it element 2.

Subscribe v1 - Invalid / Error Responses

In the event of an error, you will receive a non-200 HTTP status code. Depending on the error, you may or may not have a parseable array returned.

Common HTTP Status Codes should be expected. In the event of a non-Common HTTP Status Code and/or unparseable JSON, assume an error, fire your error callback with as much information as possible, wait 1 second, and retry the failed request indefinitely.

It is critical to design your subscribe logic to be durable and always retry. Although it should try indefinately, since its calling the error callback on each failure, the developer will be able to unsubscribe from the channel(s) if needed.

SubscribeGET/subscribe/{sub_key}/{channel}/{callback}/{timetoken}{?state,heartbeat,uuid}

Example URI

GET https://ps.pndsn.com/subscribe/mySubKey/ch1/myFunction/1231312313123?state=%7B%22text%22%3A%22hey%22%7D&heartbeat=412&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key

channel
string (required) Example: ch1

The channel name(s) you are subscribing to. Verify that channels are comprised of valid characters. You may subscribe to mulitple channels using a comma seperator. If subscribing to no channels (only channel groups), use a comma char (,) as a placeholder. You may subscribe to channels, channels & channel groups, or just channel groups.

callback
string (required) Example: myFunction

JSONP callback name, or 0 if none.

timetoken
string (required) Example: 1231312313123

0 (zero) for the initial subscribe, or a valid timetoken if resuming / continuing / fast-forwarding from a previous subscribe flow.

channel-group
string (optional) Example: cg1,cg2,cg3

Channel group name(s) to subscribe to. If subscribing to more than one channel group, use a comma separator between channel group names. You may subscribe to channels, channels & channel groups, or just channel groups.

state
string (optional) Example: %7B%22text%22%3A%22hey%22%7D

When state is set, this value is an object with root keys associated with each channel you are setting are setting state for. You must be subscribed to a channel to set state for it. (Refer to the get/set state sections)

heartbeat
number (optional) Example: 412

If heartbeat is set, send this parameter with the heartbeat value. (Refer to the heartbeat section)

auth
string (optional) Example: "authKey"

If the channel / channel group is protected by PAM, auth must be passed with a key which is authorized to read from the channel.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Subscribe v2 - Valid / Success Responses

An Object containing 2 elements:

  • First element is an object containing 2 values: t - String - the timetoken and r - Int - the region.

  • Second element is an array of messages, each message contains.

    • a - String - Shard
    • b - String - Subscription match or the channel group
    • c - String - Channel
    • d - Object - The payload
    • f - Int - Flags
    • i - String - Issuing Client Id
    • k - String - Subscribe Key
    • o - Object - Originating Timetoken, containing: t - String - the timetoken and r - Int - the region.
    • p - Object - Publish Timetoken Metadata containing: t - String - the timetoken and r - Int - the region.
    • u - Object - User Metadata

If you are subscribed to a channel group named myCG, and you receive a message on myCG from a member channel named myCH, array element 2 will contain "myCG", and the corresponding entry in element 3 will be "myCH".

When subscribing to both channels and channel groups, the corresponding entry for an non-CG member channel will be identical to that of the entry for it element 2.

Subscribe v2 - Invalid / Error Responses

In the event of an error, you will receive a non-200 HTTP status code. Depending on the error, you may or may not have a parseable array returned.

Common HTTP Status Codes should be expected. In the event of a non-Common HTTP Status Code and/or unparseable JSON, assume an error, fire your error callback with as much information as possible, wait 1 second, and retry the failed request indefinitely.

It is critical to design your subscribe logic to be durable and always retry. Although it should try indefinately, since its calling the error callback on each failure, the developer will be able to unsubscribe from the channel(s) if needed.

SubscribeGET/v2/subscribe/{sub_key}/{channel}/{callback}{?uuid,tt,tr,state,filter-expr}

Example URI

GET https://ps.pndsn.com/v2/subscribe/mySubKey/ch1/myFunction?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561&tt=14586610176891624&tr=4&state=%7B%22ch1%22%3A%7B%22testkey%22%3A%22testval%22%7D%7D&filter-expr=uuid%20!%3D%20%27cvc1%27
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key

channel
string (required) Example: ch1

The channel name(s) you are subscribing to. Verify that channels are comprised of valid characters. You may subscribe to mulitple channels using a comma seperator. If subscribing to no channels (only channel groups), use a comma char (,) as a placeholder. You may subscribe to channels, channels & channel groups, or just channel groups.

callback
string (required) Example: myFunction

JSONP callback name, or 0 if none.

tt
string (required) Example: 1231312313123

0 (zero) for the initial subscribe, or a valid timetoken if resuming / continuing / fast-forwarding from a previous subscribe flow.

tr
string (optional)

Region as returned from the initial call with tt=0.

channel-group
string (optional) Example: cg1,cg2,cg3

Channel group name(s) to subscribe to. If subscribing to more than one channel group, use a comma separator between channel group names. You may subscribe to channels, channels & channel groups, or just channel groups.

state
string (optional) Example: %7B%22text%22%3A%22hey%22%7D

When state is set, this value is an object with root keys associated with each channel you are setting are setting state for. You must be subscribed to a channel to set state for it. (Refer to the get/set state sections)

heartbeat
number (optional) Example: 412

If heartbeat is set, send this parameter with the heartbeat value. (Refer to the heartbeat section)

auth
string (optional) Example: "authKey"

If the channel / channel group is protected by PAM, auth must be passed with a key which is authorized to read from the channel.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

filter-expr
string (optional) Example: uuid%20!%3D%20%27cvc1%27

Set filter expression for Subscribe message filtering.

History

Fetch History

History - Valid / Success Responses

  • Array Element 0 – Array – Contains an array of JSON messages. Array will be between 0 and 100 in length, based on the count parameter (default 100) used at request time, and the number of valid messages available for the given time-slice.

  • Array Element 1 – Int – Start Timetoken of returned results,

  • Array Element 2 – Int – End Timetoken of returned results,

Successful (HTTP Status 200) History() calls will always return a three-element array similar to:

[ [MSG1, MSG2, ...], START_TIMETOKEN, END_TIMETOKEN ]

for example: [["Pub1","Pub2","Pub3"],13406746729185766,13406746780720711]

History - Invalid / Error Responses

In the event of an error, you will receive a non-200 HTTP status code. Depending on the error, you may or may not have a parseable array returned.

About Timetokens

The timetoken represents a 17-digit precision unix time (UTC). To convert PubNub’s timetoken to Unix timestamp (seconds), divide the timetoken number by 10,000,000 (10^7).

To convert back and forth between current time, A Ruby example follows as:

> now = Time.now
 => 2012-11-02 14:27:11 -0700

> timetoken = now.to_f * 10000000
 => 13518916319742640

> Time.at(timetoken / 10000000)
 => 2012-11-02 14:27:11 -0700

Paging

Page through History, traversing newest to oldest:

Perform the initial history request, without any start or end parameters (we’ll limit results to two at a time to make this example easier to grok):

curl "https://ps.pndsn.com/v2/history/sub-key/demo-36/channel/dox?count=4"
 --> [["msg4","msg5","msg6","msg7"],14382111171320896,14382111251236844]

Using the start Timetoken provided from the last response, use as the start parameter for the next page:

curl "https://ps.pndsn.com/v2/history/sub-key/demo-36/channel/dox?count=4&start=14382111171320896"
 --> [["msg1","msg2","msg3"],14382102111436851,14382102175496790]

Repeat, until you get 0 (zero) back as a start Timetoken. This indicates you are at the end of the list.

curl "https://ps.pndsn.com/v2/history/sub-key/demo-36/channel/dox?count=4&start=14382102111436851"
 --> [[],0,0]`

You may also wish to page through history from oldest to newest:

Perform the initial history request, without any start or end parameters (we’ll limit results to two at a time to make this example easier to grok), but with reverse=true:

curl "https://ps.pndsn.com/v2/history/sub-key/demo-36/channel/dox?count=4&reverse=true"
 --> [["msg1","msg2","msg3","msg4"],14382102111436851,14382111171320896]

Repeat the request, with the end Timetoken provided in the response, used as the start value in the next request:

curl "https://ps.pndsn.com/v2/history/sub-key/demo-36/channel/dox?count=4&reverse=true&start=14382111171320896"
 --> [["msg5","msg6","msg7"],14382111201316589,14382111251236844]

Repeat, until you get 0 (zero) back as a start Timetoken. This indicates you are at the end of the list.

curl "https://ps.pndsn.com/v2/history/sub-key/demo-36/channel/dox?count=4&reverse=true&start=14382111251236844"
 --> [[],0,0]

Fetch HistoryGET/v2/history/sub-key/{sub_key}/channel/{channel}{?stringtoken,count,reverse,start,end,include_token,auth,uuid}

Example URI

GET https://ps.pndsn.com/v2/history/sub-key/mySubKey/channel/ch1?stringtoken=false&count=100&reverse=false&start=123323123123123&end=123323123123123&include_token=false&auth="authKey"&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

channel
string (required) Example: ch1

channel for which the history is requested

stringtoken
boolean (optional) Example: false

If false, 0, or not provided, the returned start and end Timetoken values will be returned as long ints. If 1, or true, the start and end Timetoken values will be returned as strings.

count
number (optional) Example: 100

The maximum number of messages to return per response. If the count parameter is not provided, the server will default to the maximum value of 100. When the count parameter is provided, you may request between 1 and 100 messages.

reverse
boolean (optional) Example: false

Direction of time traversal. Default is false, which means timeline is traversed newest to oldest.

start
number (optional) Example: 123323123123123

If provided, lets you select a "start date", in Timetoken format. If not provided, it will default to current time. Page through results by providing a start OR end time token. Retrieve a slice of the time line by providing both a start AND end time token. start is ‘exclusive’ – that is, the first item returned will be the one immediately after the start Timetoken value.

end
number (optional) Example: 123323123123123

If provided, lets you select an "end date", in Timetoken format. If not provided, it will provide up to the number of messages defined in the "count" parameter. Page through results by providing a start OR end time token. Retrieve a slice of the time line by providing both a start AND end time token. End is ‘exclusive’ – that is, if a message is associated exactly with the end Timetoken, it will be included in the result.

include_token
boolean (optional) Example: false

pass true to recieve a timetoken with each history message. Defaults to false

auth
string (optional) Example: "authKey"

If the channel is protected by PAM, auth must be passed with a key which is authorized to read from the channel.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Delete From History

If Auth is enabled then the Delete request is accepted only if signed with the secret-key. If not will return:

{status: 403, error: true, error_message: "Do not have permission to delete"}.

If parsing the request fails, will return:

{status: 400, error: true, error_message: "Parse error"}.

Delete API is asynchronously processed. Getting a {status: 200, error: false, error_message: ""} implies the Delete request has been received and will be processed soon.

After the delete has been processed, a webhook is called if the subkey specifies one. If multiple (say N) channels are given in the request a single 200 is returned but N webhook calls will be made.

Note: There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Administration Portal.

Delete History DELETE /v3/history/sub-key/<sub-key>/channel/<channels>

Use a REST DELETE method in this format to make the request to the PubNub service to delete a channel or subset of a channel.

Example URI

curl -s -X DELETE -i  https://ps.pndsn.com/v3/history/sub-key/demo/channel/channelfoo?start=14993928130000000&end=14992200130000000
URI Parameters
start
number  (optional)  Example:  14993928130000000

end
number  (optional)  Example:  14992200130000000

  • If neither start nor end is given, we delete all messages for that channel.
  • If start is given and no end, we delete from the start time and all messages before that time. Start time is not inclusive, as in message with timestamp start will not be deleted.
  • If end is given and no start, we delete all messages from the current time till the end time. End time is inclusive, as in message with timestamp end will be deleted.
  • If start and end are given, we delete all messages from the start time till the end time. Start time is inclusive and the end time is not included.
  • If auth is enabled for subkey, the request needs to have signature.
Response   200
Headers
response.set_header('Content-Type', 'text/javascript; charset="UTF-8"')
response.set_header('Cache-Control', 'no-cache')
response.set_header('Access-Control-Allow-Origin', '*')
response.set_header('Access-Control-Allow-Methods', 'GET')

//if message_count is not None:

response.set_header('PN-Messages', str(message_count))
if request.headers.get('SSL'):
    response.set_header('PN-SSL', 'ssl')
Body
{
    "status": 200,
    "error": false,
    "error_message": "",
}
Response   400
Headers
response.set_header('Content-Type', 'text/javascript; charset="UTF-8"')
response.set_header('Cache-Control', 'no-cache')
response.set_header('Access-Control-Allow-Origin', '*')
response.set_header('Access-Control-Allow-Methods', 'GET')

//if message_count is not None:

response.set_header('PN-Messages', str(message_count))
if request.headers.get('SSL'):
    response.set_header('PN-SSL', 'ssl')
Body
{ 
    "status": 400,
    "error": true,
    "error_message": "Parse error",
}
Response   403
Headers
response.set_header('Content-Type', 'text/javascript; charset="UTF-8"')
response.set_header('Cache-Control', 'no-cache')
response.set_header('Access-Control-Allow-Origin', '*')
response.set_header('Access-Control-Allow-Methods', 'GET')

//if message_count is not None:

response.set_header('PN-Messages', str(message_count))
if request.headers.get('SSL'):
    response.set_header('PN-SSL', 'ssl')
Body
{ 
    "status": 403, 
    "error": true, 
    "error_message": "Do not have permission to delete", 
}

Webhook Method POST /v3/history/sub-key/<sub-key>/channel/<channels>

Once the deletion of the requested messages has been performed, PubNub will make a callback to your application to inform you that your request has been completed, and all the requested messages / channels have been completely deleted.

Example URI

curl -i  http://<balancer>/v3/history/sub-key/<sub-key>/channel/<channels>

Retry Policy: Exponential Total retries: 3

The URL that PubNub will make a web hook call to is configurable on a per key basis. You can configure this URL in the Administration Portal under the Storage & Playback settings for your key.

PubNub expects your application to respond to our webhook informing you of the completion of the delete request with an appropriate status response. This can be either 200 or 400, to indicate success or failure to receive the webhook, respectively.

PubNub will include a message in the body of the POST request to your server that indicates more detail of what happened to your deletion request.

Successful completion of the message delete request
Body
{
    "error": false,
    "error_message": "",
    "channel": channel_deleted
}
Unsuccessful completion of the message delete request
Body
{
    "error": true,
    "error_message": "Storage Error",
    "channel": ""
}

Creating a signature with JS Standalone

// Requires the request module: https://www.npmjs.com/package/request

var request = require("request");

// Set your keys (replace with your own)

var pnAPIKeys = {
    "subKey": "MySubKey",
    "pubKey": "MyPubKey",
    "secKey": "MySecretKey"
};

// In this config as it stands, it will delete all messages in the channel 
// To delete from an offset or range
// Add start and/or end parameters with PN timetoken integers as values

var historyDeleteURLParams = {
    "uuid": "pn-86eec3a6-2aff-4faf-8722-71374c737f2a",
    "pnsdk": "[companyname][base_pn_sdk][branch_pn_sdk]-v.#.#",
    "auth": "myAuthToken",
    "uuid": "ec4b2732-4739-494a-b83f-094ad22be275",
    "timestamp": Math.floor(new Date().getTime() / 1000)
};

// Create the URL for History Delete

var historyDeleteUrl = "/v3/history/sub-key/" + pnAPIKeys.subKey + "/channel/myChannel"

// TODO: Cleanup temp vars (currently used to swap out for other signature-based REST calls)

var url = historyDeleteUrl;
var urlParams = historyDeleteURLParams;

// Sign the request

var signature = signRequest(url, pnAPIKeys);

// Add the signature to the URL Params obj

urlParams.signature = signature;

// Create the params string from the obj

var finalParams = (objectToParams(urlParams));

// DELETE history operation must use DELETE method

request.del("http://ps.pndsn.com" + url + "?" + finalParams, function(error, response, body){
    if(error){
        console.log(error);
    } else {
        console.log(JSON.stringify(response));
    }
});

/* *** Utility *** */

function signRequest(url, outgoingParams) {

    var hmacsha256 = require("crypto-js/hmac-sha256");
    var CryptoJS = require("crypto-js");
    var signInput = pnAPIKeys.subKey + '\n' + pnAPIKeys.pubKey + '\n' + url + '\n';

    // Add a new line containing the query parameters in urlencoded alpha order

    signInput += signPamFromParams(urlParams);

    // Create the hash

    var signature = hmacsha256(signInput, outgoingParams.secKey);
    base64Signature = signature.toString(CryptoJS.enc.Base64);

    // In the signature, Replace the plusses with -, Replace the slashes with underscores

    base64Signature = base64Signature.replace(/\+/g, '-');
    base64Signature = base64Signature.replace(/\//g, '_');

    // Done!

    //console.log(base64Signature);
    return base64Signature;
}

function objectToList(o) {
    var l = [];
    Object.keys(o).forEach(function (key) {
        return l.push(key);
    });
    return l;
}

function encodeString(input) {
    return encodeURIComponent(input).replace(/[!~*'()]/g, function (x) {
        return '%' + x.charCodeAt(0).toString(16).toUpperCase();
    });
}

function objectToListSorted(o) {
    return objectToList(o).sort();
}

function objectToParams(obj) {
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }

    return str;
}

function signPamFromParams(params) {
    var l = objectToListSorted(params);
    return l.map(function (paramKey) {
        return paramKey + '=' + encodeString(params[paramKey]);
    }).join('&');
}

function endsWith(searchString, suffix) {
    return searchString.indexOf(suffix, this.length - suffix.length) !== -1;
}

Encrypt Msg Using secret-key as the Encryption Key

key = "demo-36" //Secret-key

msg = "

{subkey}

{pubkey}

{path}

{params}"

Example:
subkey=demo-36,
pubkey=demo-36,
path= '/v3/history/sub-key/demo-36/channel/channel1' ,
params= '"timestamp"=1506666034'

params is REST Query parameters and the timestamp should be the current epoch timestamp when signing.

Then the URI with signature will be

    curl -s -X DELETE -i 'http://pubsub.pubnub.com/v3/history/sub-key/demo-36/channel/channel1?timestamp=1506666034&signature=uVRcaYccGYlmNUAjHBOSGZ-10O9-sQm8HqYlGomNOCc%3D'

Channel Groups

Listing All Registered Channel Groups

Listing All Registered Channel GroupsGET/v1/channel-registration/sub-key/{sub_key}/channel-group{?uuid}

This endpoint is disabled on most subscribe keys, please contact support@ to confirm endpoint usability

Example URI

GET https://ps.pndsn.com/v1/channel-registration/sub-key/mySubKey/channel-group?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  Get all channel groups for subscribe key
Response  200
HideShow
Headers
Content-Type: application/json
Body
{
  "service": "name of the service returning the data",
  "status": "HTTP status code of the performed action",
  "error": "returns the reason an error has occoured",
  "payload": {
    "sub_key": "subKey",
    "groups": [
      "group1",
      "group2",
      "group3"
    ]
  }
}

Listing all channels for a channel group

Listing all channels for a channel groupGET/v1/channel-registration/sub-key/{sub_key}/channel-group/{group}{?uuid}

Example URI

GET https://ps.pndsn.com/v1/channel-registration/sub-key/mySubKey/channel-group/group1?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

group
string (required) Example: group1

the group for which we need the list of channels

auth
string (optional) Example: "authKey"

If the channel group is protected by PAM, auth must be passed with a key which is authorized to read the channel group.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  Get all channels for a channel group
Response  200
HideShow
Headers
Content-Type: application/json
Body
{
  "service": "name of the service returning the data",
  "status": "HTTP status code of the performed action",
  "error": "returns the reason an error has occoured",
  "payload": {
    "group": "group_id",
    "channels": [
      "channel1",
      "channel2",
      "channel3"
    ]
  }
}

Adding channels // New Channel Group

This endpoint supports both the addition of channels to channel groups and also creating a channel group. To create a new group, pass the neme of the desired group as the group name

Adding Channels // New Channel GroupGET/v1/channel-registration/sub-key/{sub_key}/channel-group/{group}{?add,uuid}

Example URI

GET https://ps.pndsn.com/v1/channel-registration/sub-key/mySubKey/channel-group/group1?add=ch1&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

The subscriber key

group
string (required) Example: group1

The channel group to which the channels will be added

add
string (required) Example: ch1

Name of a channel to be added to the channel group. You may add mulitple channels using a comma seperator (ch1,ch2,ch3).

auth
string (optional) Example: "authKey"

If the channel group is protected by PAM, auth must be passed with a key which is authorized to manage the channel group.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request
Response  200
HideShow
Headers
Content-Type: application/json
Body
{
  "service": "channel-registry",
  "status": "200",
  "error": false,
  "message": "OK"
}

Removing channels

Removing channelsGET/v1/channel-registration/sub-key/{sub_key}/channel-group/{group}{?remove,uuid}

Example URI

GET https://ps.pndsn.com/v1/channel-registration/sub-key/mySubKey/channel-group/group1?remove=ch1&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

The subscriber key

group
string (required) Example: group1

The channel group to which the channels will be added

remove
string (required) Example: ch1

Name of a channel to be removed from the channel group. You may add mulitple channels using a comma seperator (ch1,ch2,ch3).

auth
string (optional) Example: "authKey"

If the channel group is protected by PAM, auth must be passed with a key which is authorized to manage the channel group.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request
Response  200
HideShow
Headers
Content-Type: application/json
Body
{
  "service": "channel-registry",
  "status": "200",
  "error": false,
  "message": "OK"
}

Deleting a Channel Group

Deleting a Channel GroupGET/v1/channel-registration/sub-key/{sub_key}/channel-group/{group_name}/remove{?uuid}

Example URI

GET https://ps.pndsn.com/v1/channel-registration/sub-key/mySubKey/channel-group/group1/remove?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

group_name
string (required) Example: group1

the group to be deleted

auth
string (optional) Example: "authKey"

If the channel group is protected by PAM, auth must be passed with a key which is authorized to manage the channel group.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  Deleting a Channel Groups
Response  200
HideShow
Headers
Content-Type: application/json
Body
{
  "service": "channel-registry",
  "status": "200",
  "error": false,
  "message": "OK"
}

PubNub Access Manager -- PAM

PubNub Access Manager

PubNub Access Manager (PAM) provides fine-grained access controls to PubNub Data Streams and DataSync Objects. It presents a minimal REST API for secure administration tasks, and transparently protects Data Stream and DataSync resource access. This document divides these two responsibilities clearly into their own sections; REST API, and ACL Enforcement.

General Information

  • Global Permissions

    Do Not Provide auth nor channel in the {signed-content} query-string parameters

  • Channel Permissions

    Provide only a channel parameter, but not auth parameter, this then sets permissions on the channel itself overriding any auth-key permissions

  • AuthKey Permissions

    Provide both auth and channel parameters to set the permissions for one or more channels and one or more auth-keys

Both auth and channel accept comma-separated lists.

Check out http://www.pubnub.com/docs/access-manager-signature-construction to know more about computing the signature for the request.

Access Manager Request String Required Formatting

  • {access-manager-request-string} parameters must be sorted lexicographically (case-sensitive) by key.

  • Secondly, all characters in the query string parameters must be percent-encoded except alphanumeric, hyphen, underscore, and period; E.g. all characters matching the RegExp /[^0-9a-zA-Z\-_\.]/.

  • Space characters must be replaced by %20 (NOT + character).

  • Each key-value pair must be separated by ampersand characters.

  • Unicode characters must be broken up into UTF-8 encoded bytes before percent-encoding.

  • Final signed value should be Base64 encoded using the "URL safe" characters - and _ replacing + and / respectively.

Here is an example of a query string containing unicode characters (PoundsSterling is just there to demonstrate encoding/sorting):

auth={auth-key-to-be-updated}&r=1&w=1&ttl=60&timestamp=123456789&PoundsSterling=£13.37

And here is the same query string after sorting and percent-encoding (PoundsSterling is just there to demonstrate encoding/sorting):

PoundsSterling=%C2%A313.37&auth=joker&r=1&timestamp=123456789&ttl=60&w=1

Let’s imagine the demo account’s secret key is:

wMfbo9G0xVUG8yfTfYw5qIdfJkTd7A

The signature generated for this request is Base64 encoded using the "URL safe" characters - and _ replacing + and / respectively:

v2rgQQ1eFzk8omugFV9V1_eKRUvvMv9jyC9Z-L1ogdw=

This signature is then percent-encoded according to standard query parameter percent-encoding practices. E.g. the = character is transformed into %3D.

v2rgQQ1eFzk8omugFV9V1_eKRUvvMv9jyC9Z-L1ogdw%3D

Applying PAMGET/v2/auth/grant/sub-key/{sub_key}{?signature,auth,uuid}

In this Request, the auth-key is the client that has permissions to modify Access Manager permissions, not the auth-key you want to modify permissions on. The one you are changing permissions for is within the parameters.

Example URI

GET https://ps.pndsn.com/v2/auth/grant/sub-key/mySubKey?signature='v2rgQQ1eFzk8omugFV9V1_eKRUvvMv9jyC9ZL1ogdw%3D'&auth=myAuthKey&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key.

signature
string (required) Example: 'v2rgQQ1eFzk8omugFV9V1_eKRUvvMv9jyC9ZL1ogdw%3D'

A signed request as described in the section above.

auth
string (required) Example: myAuthKey

The Auth key that is being granted permissions.

uuid
string (optional) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

timestamp
int (required) Example: 123456789

The timetoken represents a 17-digit precision unix time (UTC). To convert PubNub's timetoken to Unix timestamp (seconds), divide the timetoken number by 10,000,000 (10^7).

ttl
int (optional) Example: 15

Time to live for permission to be valid

w
boolean (optional) Example: 1

Write permission

r
boolean (optional) Example: 0

Read permission

m
boolean (optional) Example: 0

Manage permission

Request
Response  200
HideShowExample:
Body
Depending on the parameters provided (channel name, auth)

{
    "status": 200,
    "message": "Success",
    "payload": {
        "ttl": 1440,
        "auths": {
            "password": {
                "r": 1,
                "w": 0
            }
        },
        "subscribe_key": "{subscribe-key}",
        "level": "user",
        "channel": "my_channel"
    },
    "service": "Access Manager"
}

Presence

Presence is what enables us to say who (UUID) is on a where (channel), when, and how (state).

Identifying Users with UUID

Each REST call uses a URL parameter called UUID. A client's UUID is how the system differentiates one user from another. This is how the user Bob is being differentiated from the user Alice?—?by UUID.

Presence Events

If you are subscribed to a Presence channel, for any given UUID, you will see Presence events occur in real-time on that channel. Those events are named:

  • JOIN (Joined)

  • LEAVE (Explicitly Left)

  • TIMEOUT (Implicitly Left)

  • STATE-CHANGE

Presence events are idempotent – that is, the event will not be repeated (alerted) again until it transitions to another event.

Presence States

For any user, an optional "state" object may be attached to that user's UUID. This state may be set/changed at subscribe (Join) time, or anytime during the sustained Join lifecycle. Once a user transitions to TIMEOUT or LEAVE, that user's associated state (if any) is deleted from the server.

The Different Types of Presence Calls

There are three main classes of Presence methods

  1. The streaming, realtime, subscribe-based presence calls, generally implemented as presence()

  2. The ad-hoc, on-demand presence calls, such as [global_]here_now() and where_now(), get_state(), set_state(), and leave()

  3. Long running heartbeat calls, configured via subscribe initializer, and/or via set_hb() and set_hb_interval()

Streaming Presence Calls

To get realtime Presence Events as they occur, subscribe to the presence variant of a channel name. The variant name is the channel you wish to monitor events for, appended with "-pnpres". For example, to subscribe to presence for channel foo, under the hood, we subscribe to channel "foo-pnpres".

Aside from the channel name (channel-pnpres) and the structured data that one can expect from a presence call (vs the relatively random nature of the structured data from user data), there is nothing technically different from a presence call vs a subscribe call.

Ad-hoc, On-demand Presence Calls

In addition to the "fire and forget" streaming presence calls, there are a group of calls that can be called anytime to get the current presence and state information for a given UUID. These methods are:

  • here_now - Who is here, now, on this channel [on this subscribe key]?

  • global_here_now - Who is here, now, on this subscribe-key?

  • where_now - Where (which channels) is this UUID currently subscribed on [on this subscribe-key]?

  • get_state - Give me the Presence state info for a given UUID.

  • set_state - Set the Presence state info for a given UUID.

Long running heartbeat calls

By default, the server expects the client to respond to either an intentially published message, or an empty server "ping" (issued every 270s) within 290s. When this doesn't happen, the Server will transition the UUID from "Join" to "Timeout". (When this does happen as expected, there is no transition – the UUID stays in "Join".)

Some customers require a greater precision to detect a UUID's presence than 270s. To fulfill that requirement, an additional heartbeat (HB) call can be set to "ping", from the client, every n seconds. When this HB is enabled a long-running HB process is started on the client, which will connect to the server every HB-Interval (HBI) seconds.

Using this HB scheme, it's possible to inform the Presence system "if you don't hear from me within x seconds, mark me as TIMEOUT."

By default, if the client is set for a HB of x, the HBI is automatically set to x / 2 - 1. This enables, by default, that under excellent to average-bad network scenarios, the client should be able to "ping" the Presence server between 1 and 2 times before its HB timeout limit.

The user can always override the default HBI to a lower value, but it's important to keep in mind that making this chattier demands extra battery and network resources.

Heartbeat has no functional effect on the performance or integrity of the client itself. Its only provided for Presence functionality.

Heartbeat is the mechanism used to 'ping' back from the client to the server that the client is still online. The heartbeat is only germane to the Presence service.

It affects presence in the following ways:

  • Subscribe calls and Heartbeat calls count as heartbeat signals to Presence?—?but only on the server RESPONSE does the heartbeat signal register.

  • Since a subscribe call can long poll, the server RESPONSE to the subscribe REQUEST may not be immediate (could be many minutes), so it's not always beneficial to rely on only the subscribe call as the heartbeat.

  • Since the server will RESPOND immediately to the client HP REST API call REQUEST, using the heartbeat call, in concert with subscribe calls, is the perfect method to registering heartbeats with the Presence system.

Transitioning Between Presence Events

Non-Present to Present (Emitting a Join Event)

  • To be "Present", you must go from "Non-Present" to "Present" by subscribing to a channel, and/or sending heartbeats to that channel.

  • Going from "Non-Present" to "Present" emits a "JOIN" event within the Presence system.

  • If the system continues to hear Heartbeats and/or subscribe requests from this client within HEARTBEAT timeout seconds, you will remain "Present".

  • If the client is not currently "JOINED" to a channel, a client heartbeat or subscribe call will create a JOIN event.

  • If the client is currently "JOINED" to a channel, and the server hears the heartbeat or subscribe within HEARTBEAT seconds, the server resets the heartbeat timer, and keeps the client "JOINED" to the channel.

Present back to Not-Present (Emitting a Timeout or Leave Event)

  • The client issues a LEAVE REST call, and stops sending subscribe requests and heartbeat requests. This will generate a "LEAVE" Presence event.

  • The client does not issue a LEAVE REST call, but the server no longer receives subscribe or heartbeat requests from the client within HEARTBEAT timeout seconds. This will generate a "TIMEOUT" Presence event.

  • Once "Not-Present", you can always be "Present" again by repeating this process by subscribing and/or sending a heartbeat.

  • If the client is currently "JOINED" to a channel, and the server DOES NOT hear the heartbeat or subscribe within HEARTBEAT seconds, the server will issue a "LEAVE" event for that client.

Heartbeat

Inform presence server user is still active. If user has not been seen before, user will join the channel and send a "join event".

Announce HeartbeatGET/v2/presence/sub-key/{sub_key}/channel/{channel}/heartbeat{?callback,state,uuid}

Example URI

GET https://ps.pndsn.com/v2/presence/sub-key/'mySubKey'/channel/'ch1,ch2'/heartbeat?callback=myFunction&state=%7B%22text%22%3A%22hey%22%7D&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: 'mySubKey'

Your PubNub Subscribe API Key

channel
string (required) Example: 'ch1,ch2'

The channel name for which the new state will be applied. Verify that channels are comprised of valid characters. May be a single channel, or multiple channels, separated by comma.

callback
string (required) Example: myFunction

JSONP callback name, or 0 if none.

channel-group
string (optional) Example: cg1,cg2,cg3

Channel group name(s) to subscribe to. If subscribing to more than one channel group, use a comma separator between channel group names. You may subscribe to channels, channels & channel groups, or just channel groups.

state
string (required) Example: %7B%22text%22%3A%22hey%22%7D

When state is set, this value is an object with root keys associated with each channel you are setting are setting state for. You must be subscribed to a channel to set state for it. (Refer to the get/set state sections)

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Setting User State

Set state for a user for a channel(s) and/or channel-group(s).

Setting User StateGET/v2/presence/sub-key/{sub_key}/channel/{channel}/uuid/data{?state,callback}

Example URI

GET https://ps.pndsn.com/v2/presence/sub-key/mySubKey/channel/ch1/uuid/data?state=%7B%22text%22%3A%22hey%22%7D&callback=myFunction
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key

channel
string (required) Example: ch1

The channel name(s) you are applying the state to. Verify that channels are comprised of valid characters. You may update state to mulitple channels using a comma seperator. If applying state to no channels (only channel groups), use a comma char (,) as a placeholder. You may apply state to channels, channels & channel groups, or just channel groups.

channel-group
string (optional) Example: cg1,cg2,cg3

Channel group name(s) to which you are applying the new state. If applying state to more than one channel group, use a comma separator between channel group names. You may apply state to channels, channels & channel groups, or just channel groups.

callback
string (optional) Example: myFunction

If provided, wraps the response in function (JSONP)

state
string (required) Example: %7B%22text%22%3A%22hey%22%7D

url-encoded json which will be associated with the UUID for the channels and/or channel groups

Request  Setting User State
HideShow
Headers
Location: /v2/presence/sub-key/mySubKey/channel/channel/uuid/db9c5e39-7c95-40f5-8d71-125765b6f561/data?state=%7B%22text%22%3A%22hey%22%7D&callback=0
Response  200
HideShow
Headers
Location: /v2/presence/sub-key/mySubKey/channel/channel/uuid/db9c5e39-7c95-40f5-8d71-125765b6f561/data?state=%7B%22text%22%3A%22hey%22%7D&callback=0
Content-Type: application/json
Body
{
  "service": "presence",
  "status": "200",
  "error": false,
  "message": "OK",
  "payload": "{text:hey}"
}

Getting User State

Get state for a user for a channel(s) and/or channel-group(s).

Getting User StateGET/v2/presence/sub-key/{sub_key}/channel/{channel}/uuid{?callback}

Example URI

GET https://ps.pndsn.com/v2/presence/sub-key/mySubKey/channel/ch1/uuid?callback=myFunction
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key

channel
string (required) Example: ch1

The channel name(s) you are fetching the state for. Verify that channels are comprised of valid characters. You may fetch state for mulitple channels using a comma seperator. If fetching state to no channels (only channel groups), use a comma char (,) as a placeholder. You may fetch state to channels, channels & channel groups, or just channel groups.

channel-group
string (optional) Example: cg1,cg2,cg3

Channel group name(s) to which you are fetching the state. If fetching state for more than one channel group, use a comma separator between channel group names. You may fetch state for channels, channels & channel groups, or just channel groups.

callback
string (optional) Example: myFunction

If provided, wraps the response in function (JSONP)

Request  Setting User State
HideShow
Headers
Location: /v2/presence/sub-key/mySubKey/channel/channel/uuid/db9c5e39-7c95-40f5-8d71-125765b6f561?state=%7B%22text%22%3A%22hey%22%7D&callback=0
Response  200
HideShow
Headers
Location: /v2/presence/sub-key/mySubKey/channel/channel/uuid/db9c5e39-7c95-40f5-8d71-125765b6f561?state=%7B%22text%22%3A%22hey%22%7D&callback=0
Content-Type: application/json
Body
{
  "service": "presence",
  "status": "200",
  "error": false,
  "message": "OK",
  "payload": "{text:hey}"
}

Announce Leave

Indicate to the PubNub Presence system that a device has left a channel(s).

via GETGET/v2/presence/sub_key/{sub_key}/channel/{channel}/leave{?callback,uuid}

Example URI

GET https://ps.pndsn.com/v2/presence/sub_key/mySubKey/channel/ch1/leave?callback=myFunction&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key

channel
string (required) Example: ch1

The channel name(s), separated by comma, that you wish to send leave events for. Verify that channels are comprised of valid characters.

channel-group
string (optional) Example: cg1,cg2,cg3

The channel group name(s), separated by comma, that you wish to send leave events for. Verify that channels are comprised of valid characters. You may leave channels, channels & channel groups, or just channel groups.

callback
string (optional) Example: myFunction

If provided, wraps the response in function (JSONP)

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

via POSTPOST/v2/presence/sub_key/{sub_key}/channel/{channel}/leave{?callback,uuid}

Example URI

POST https://ps.pndsn.com/v2/presence/sub_key/mySubKey/channel/ch1/leave?callback=myFunction&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

Your PubNub Subscribe API Key

channel
string (required) Example: ch1

The channel name(s), separated by comma, that you wish to send leave events for. Verify that channels are comprised of valid characters.

channel-group
string (optional) Example: cg1,cg2,cg3

The channel group name(s), separated by comma, that you wish to send leave events for. Verify that channels are comprised of valid characters. You may leave channels, channels & channel groups, or just channel groups.

callback
string (optional) Example: myFunction

If provided, wraps the response in function (JSONP)

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Here Now

Retrieve UUID and State Information for subscribed devices on a specific channel.

Here NowGET/v2/presence/sub-key/{sub_key}/channel/{channel}{?disable_uuids,state,callback,uuid}

Example URI

GET https://ps.pndsn.com/v2/presence/sub-key/'mySubKey'/channel/'ch1,ch2'?disable_uuids=0&state=0&callback=myFunction&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: 'mySubKey'

Your PubNub Subscribe API Key

channel
string (required) Example: 'ch1,ch2'

The channel name you wish to pull history from. Verify that channels are comprised of valid characters. May be a single channel, or multiple channels, separated by comma.

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

callback
string (optional) Example: myFunction

If provided, returns a JSONP function-wrapped response.

disable_uuids
string (optional) Example: 0

If true or 1, or not provided, UUIDS, and accompanying state info, will not be returned, only occupancy numbers. If 0, or false, UUIDS, will be returned with occupancy numbers.

channel-group
string (optional) Example: cg1,cg2,cg3

Comma delimited list of channel groups that presence should be returned for as well. When channel-groups are included, the response format will be different than when channel-groups are not included, that is, the Global Here Now response format will be returned.

state
string (optional) Example: 0

If false or 0, state info is not returned. If true or 1, AND disable_uuids is false, accompanying state info for each UUID is provided.

Global Here Now

Retrieve UUID and State Information for subscribed devices on a all channels. This is exactly like Here Now, except without a channel path / channel group query string parameter.

Global Here NowGET/v2/presence/sub-key/{sub_key}{?disable_uuids,state,callback,uuid}

Example URI

GET https://ps.pndsn.com/v2/presence/sub-key/'mySubKey'?disable_uuids=0&state=0&callback=myFunction&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: 'mySubKey'

Your PubNub Subscribe API Key

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

callback
string (optional) Example: myFunction

If provided, returns a JSONP function-wrapped response.

disable_uuids
string (optional) Example: 0

If true or 1, or not provided, UUIDS, and accompanying state info, will not be returned, only occupancy numbers. If 0, or false, UUIDS, will be returned with occupancy numbers.

channel-group
string (optional) Example: cg1,cg2,cg3

Comma delimited list of channel groups that presence should be returned for as well. When channel-groups are included, the response format will be different than when channel-groups are not included, that is, the Global Here Now response format will be returned.

state
string (optional) Example: 0

If false or 0, state info is not returned. If true or 1, AND disable_uuids is false, accompanying state info for each UUID is provided.

Where Now

Get list of channels user is present in.

Where NowGET/v2/presence/sub-key/{sub_key}/uuid/{uuid}{?callback,uuid}

Example URI

GET https://ps.pndsn.com/v2/presence/sub-key/'mySubKey'/uuid/db9c5e39-7c95-40f5-8d71-125765b6f561?callback=myFunction&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: 'mySubKey'

Your PubNub Subscribe API Key

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

callback
string (optional) Example: myFunction

If provided, returns a JSONP function-wrapped response.

Push Notifications || APN & GCM

Authorize and Revoke push tokens for the Apple and Google Push Notification services.

The type parameter indicates the backend which PubNub will utilize:

  • apns - apple push notification service

  • gcm - google push notification service

  • mpns - microsoft push notification service

Publishing

Given a channel ch1, and subscribed mobile clients, a server SDK must execute a publish commend by sending the following JSON payload to ch1

{
    "pn_apns": {
        "aps": {
            "alert": "hi",
            "badge": 2,
            "sound": "melody"
        },
        "pn_other": {
            "additional": "fields"
        }
    }
}
{
  "pn_gcm": {

  },
  "pn_other": {
    "additional": "fields"
  }
}
  • microsoft push notification service
{
  "pn_mpns": {

  },
  "pn_other": {
    "additional": "fields"
  }
}

Please refer to the tutorial for additional examples

Listing registrations for device

Listing registrations for deviceGET/v1/push/sub-key/{sub_key}/devices/{push_token}{?type,uuid}

Example URI

GET https://ps.pndsn.com/v1/push/sub-key/mySubKey/devices/A332C23D?type=apns&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

push_token
string (required) Example: A332C23D

the push token of the device

type
string (required) 
  • indicates the backend to use (apns for apple, gcm for google, mpns for microsoft)
uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  show all channels for device for apple services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?type=apns
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  show all channels for device for google services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?type=gcm
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [] <!-- TODO -->
Request  show all channels for device for microsoft services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?type=mpns
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [] <!-- TODO -->

Removing a Device

Removing all registrations for a deviceGET/v1/push/sub-key/{sub_key}/devices/{push_token}/remove{?type,uuid}

Example URI

GET https://ps.pndsn.com/v1/push/sub-key/mySubKey/devices/A332C23D/remove?type=apns&uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

push_token
string (required) Example: A332C23D

the push token of the device

type
string (required) 
  • indicates the backend to use (apns for apple, gcm for google, mpns for microsoft)
uuid
string (optional) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  Removing an Apple device from all push notifications
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D/remove?type=apns
Response  200
HideShow
Headers
Content-Type: application/json
Request  Removing an Android device from all push notifications
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D/remove?type=gcm
Response  200
HideShow
Headers
Content-Type: application/json
Request  Removing a microsoft device from all push notifications
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D/remove?type=mpns
Response  200
HideShow
Headers
Content-Type: application/json

Adding Registrations

Adding registrationsGET/v1/push/sub-key/{sub_key}/devices/{push_token}{?uuid,auth,type,add}

Example URI

GET https://ps.pndsn.com/v1/push/sub-key/mySubKey/devices/A332C23D?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561&auth=385dfa9c-6a16-4145-aaf9-043f0060c7d3&type=apns&add=channel1
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

push_token
string (required) Example: A332C23D

the push token of the device

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

UUID of the client

auth
string (required) Example: 385dfa9c-6a16-4145-aaf9-043f0060c7d3

PAM authorization key

type
string (required) 
  • indicates the backend to use (apns for apple, gcm for google, mpns for microsoft)
add
string (required) Example: channel1

name of the channel to allow the device to recieve notifiactions for (mulitple channels are also supported by commad delimited (ch1,ch2,ch3) will add three channels)

Request  Subscribe a device to channel for apple services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=apns&add=ch1
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  Subscribe a device to channel for google services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=gcm&add=ch1
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  Subscribe a device to channel for microsoft services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=mpns&add=ch1
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]

Removing Registrations

Removing registrationsGET/v1/push/sub-key/{sub_key}/devices/{push_token}{?uuid,auth,type,remove}

Example URI

GET https://ps.pndsn.com/v1/push/sub-key/mySubKey/devices/A332C23D?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561&auth=385dfa9c-6a16-4145-aaf9-043f0060c7d3&type=apns&remove=channel1
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

push_token
string (required) Example: A332C23D

the push token of the device

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

UUID of the client

auth
string (required) Example: 385dfa9c-6a16-4145-aaf9-043f0060c7d3

PAM authorization key

type
string (required) 
  • indicates the backend to use (apns for apple, gcm for google, mpns for microsoft)
remove
string (required) Example: channel1

name of the channel for which the device will no longer recieve push notifications (mulitple channels are also supported by commad delimited (ch1,ch2,ch3) will remove three channels)

Request  Remove a device from push notifications for channel ch1 for apple services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=apns&remove=ch1
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  Remove a device from push notifications for channel ch1 for google services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=gcm&remove=ch1
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  Remove a device from push notifications for channel ch1 for microsoft services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=mpns&remove=ch1
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]

Mixing add & remove operations

Mixing add & remove operationsGET/v1/push/sub-key/{sub_key}/devices/{push_token}{?uuid,auth,type,add,remove}

Mixing the addition and removal operations will be executed in the following order:

  1. channels passed in the remove will be removed from the registrations list for the device

  2. channels passed in the add will be added to the registrations list for the device

Example URI

GET https://ps.pndsn.com/v1/push/sub-key/mySubKey/devices/A332C23D?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561&auth=385dfa9c-6a16-4145-aaf9-043f0060c7d3&type=apns&add=channel1&remove=channel1
URI Parameters
HideShow
sub_key
string (required) Example: mySubKey

the subscriber key

push_token
string (required) Example: A332C23D

the push token of the device

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

UUID of the client

auth
string (required) Example: 385dfa9c-6a16-4145-aaf9-043f0060c7d3

PAM authorization key

type
string (required) 
  • indicates the backend to use (apns for apple, gcm for google, mpns for microsoft)
add
string (required) Example: channel1

comma delimited channels to allow the device to recieve notifiactions for. Also supports comma delited list for multiple channels. ch1,ch2,ch3 will add three channels

remove
string (required) Example: channel1

commad delimited channels for which the device will no longer recieve push notifications. Also supports comma delited list for multiple channels. (ch1,ch2,ch3) will remove three channels

Request  Remove a device from push notifications for channels ch1,ch2 for apple services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=apns&remove=ch1,ch2
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  Remove a device from push notifications for channels ch1,ch2 for google services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=gcm&remove=ch1,ch2
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]
Request  Remove a device from push notifications for channels ch1,ch2 for microsoft services
HideShow
Headers
Location: /v1/push/sub-key/mySubKey/devices/A332C23D?uuid=appUUID&auth=MyAuth&type=mpns&remove=ch1,ch2
Response  200
HideShow
Headers
Content-Type: application/json
Body
+ [1, "Modified Channels"]

Miscellaneous

Time

Get current PubNub Time in the form of a Timetoken.

About Timetokens

The timetoken represents a 17-digit precision unix time (UTC). To convert PubNub's timetoken to Unix timestamp (seconds), divide the timetoken number by 10,000,000 (10^7).

To convert back and forth between current time, A Ruby example follows as:

> now = Time.now
 => 2012-11-02 14:27:11 -0700

> timetoken = now.to_f * 10000000
 => 13518916319742640

> Time.at(timetoken / 10000000)
 => 2012-11-02 14:27:11 -0700

Fetch TimeGET/time/{callback}{?uuid}

Example URI

GET https://ps.pndsn.com/time/0?uuid=db9c5e39-7c95-40f5-8d71-125765b6f561
URI Parameters
HideShow
callback
string (required) Example: 0

pass function name to wrap in JSONP or 0 to disable JSONP

uuid
string (required) Example: db9c5e39-7c95-40f5-8d71-125765b6f561

A unique alphanumeric ID for identifying the client to the PubNub Presence System, as well as for PubNub Analytics.

Request  fetch time without JSONP
HideShow
Headers
Location: /time/0
Response  200
HideShow
Headers
Content-Type: application/json
Body
[
  14374273908474348
]
Request  fetch time with JSONP
HideShow
Headers
Location: /time/moose
Response  200
HideShow
Headers
Content-Type: text/javascript
Body
moose([14374273908474349])