UNPKG

9.14 kBMarkdownView Raw
1# node-gcm
2[![npm](https://badge.fury.io/js/node-gcm.svg)](https://www.npmjs.com/package/node-gcm)
3
4node-gcm is a Node.JS library for [**Google Cloud Messaging**](https://developers.google.com/cloud-messaging/).
5
6## Installation
7
8```bash
9$ npm install node-gcm
10```
11
12## Requirements
13
14This library provides the server-side implementation of GCM.
15You need to generate an API key ([Sender ID](https://developers.google.com/cloud-messaging/gcm#senderid)).
16
17GCM notifications can be sent to both [Android](https://developers.google.com/cloud-messaging/android/start) and [iOS](https://developers.google.com/cloud-messaging/ios/start).
18If you are new to GCM you should probably look into the [documentation](https://developers.google.com/cloud-messaging/gcm).
19
20## Example application
21
22According to below **Usage** reference, we could create such application:
23
24```js
25var gcm = require('node-gcm');
26
27var message = new gcm.Message();
28
29message.addData('key1', 'msg1');
30
31var regTokens = ['YOUR_REG_TOKEN_HERE'];
32
33// Set up the sender with you API key
34var sender = new gcm.Sender('YOUR_API_KEY_HERE');
35
36// Now the sender can be used to send messages
37sender.send(message, { registrationTokens: regTokens }, function (err, response) {
38 if(err) console.error(err);
39 else console.log(response);
40});
41
42// Send to a topic, with no retry this time
43sender.sendNoRetry(message, { topic: '/topics/global' }, function (err, response) {
44 if(err) console.error(err);
45 else console.log(response);
46});
47```
48
49## Usage
50
51```js
52var gcm = require('node-gcm');
53
54// Create a message
55// ... with default values
56var message = new gcm.Message();
57
58// ... or some given values
59var message = new gcm.Message({
60 collapseKey: 'demo',
61 priority: 'high',
62 contentAvailable: true,
63 delayWhileIdle: true,
64 timeToLive: 3,
65 restrictedPackageName: "somePackageName",
66 dryRun: true,
67 data: {
68 key1: 'message1',
69 key2: 'message2'
70 },
71 notification: {
72 title: "Hello, World",
73 icon: "ic_launcher",
74 body: "This is a notification that will be displayed ASAP."
75 }
76});
77
78// Change the message data
79// ... as key-value
80message.addData('key1','message1');
81message.addData('key2','message2');
82
83// ... or as a data object (overwrites previous data object)
84message.addData({
85 key1: 'message1',
86 key2: 'message2'
87});
88
89// Set up the sender with you API key
90var sender = new gcm.Sender('insert Google Server API Key here');
91
92// Add the registration tokens of the devices you want to send to
93var registrationTokens = [];
94registrationTokens.push('regToken1');
95registrationTokens.push('regToken2');
96
97// Send the message
98// ... trying only once
99sender.sendNoRetry(message, { registrationTokens: registrationTokens }, function(err, response) {
100 if(err) console.error(err);
101 else console.log(response);
102});
103
104// ... or retrying
105sender.send(message, { registrationTokens: registrationTokens }, function (err, response) {
106 if(err) console.error(err);
107 else console.log(response);
108});
109
110// ... or retrying a specific number of times (10)
111sender.send(message, { registrationTokens: registrationTokens }, 10, function (err, response) {
112 if(err) console.error(err);
113 else console.log(response);
114});
115```
116## Recipients
117
118You can send push notifications to various recipient types by providing one of the following recipient keys:
119
120
121|Key|Type|Description|
122|---|---|---|
123|to|String|A single [registration token](https://developers.google.com/cloud-messaging/android/client#sample-register), [notification key](https://developers.google.com/cloud-messaging/notifications), or [topic](https://developers.google.com/cloud-messaging/topic-messaging).
124|topic|String|A single publish/subscribe topic.
125|notificationKey|String|Deprecated. A key that groups multiple registration tokens linked to the same user.
126|registrationIds|String[]|Deprecated. Use registrationTokens instead.|
127|registrationTokens|String[]|A list of registration tokens. Must contain at least 1 and at most 1000 registration tokens.|
128
129If you provide an incorrect recipient key or object type, an `Error` object will be returned to your callback.
130
131Notice that [you can *at most* send notifications to 1000 registration tokens at a time](https://github.com/ToothlessGear/node-gcm/issues/42).
132This is due to [a restriction](http://developer.android.com/training/cloudsync/gcm.html) on the side of the GCM API.
133
134## Notification usage
135
136```js
137
138var message = new gcm.Message();
139
140// Add notification payload as key value
141message.addNotification('title', 'Alert!!!');
142message.addNotification('body', 'Abnormal data access');
143message.addNotification('icon', 'ic_launcher');
144
145// as object
146message.addNotification({
147 title: 'Alert!!!',
148 body: 'Abnormal data access',
149 icon: 'ic_launcher'
150});
151
152```
153
154### Notification payload option table
155
156|Parameter|Platform|Usage|Description|
157|---|---|---|---|
158|title|Android, iOS (Watch)|Required (Android), Optional (iOS), string|Indicates notification title. This field is not visible on iOS phones and tablets.|
159|body|Android, iOS|Optional, string|Indicates notification body text.|
160|icon|Android|Required, string|Indicates notification icon. On Android: sets value to myicon for drawable resource myicon.png.|
161|sound|Android, iOS|Optional, string|Indicates sound to be played. Supports only default currently.|
162|badge|iOS|Optional, string|Indicates the badge on client app home icon.|
163|tag|Android|Optional, string|Indicates whether each notification message results in a new entry on the notification center on Android. If not set, each request creates a new notification. If set, and a notification with the same tag is already being shown, the new notification replaces the existing one in notification center.|
164|color|Android|Optional, string|Indicates color of the icon, expressed in #rrggbb format|
165|click_action|Android, iOS|Optional, string|The action associated with a user click on the notification. On Android, if this is set, an activity with a matching intent filter is launched when user clicks the notification. For example, if one of your Activities includes the intent filter: (Appendix:1)Set click_action to OPEN_ACTIVITY_1 to open it. If set, corresponds to category in APNS payload.|
166|body_loc_key|iOS|Optional, string|Indicates the key to the body string for localization. On iOS, this corresponds to "loc-key" in APNS payload.|
167|body_loc_args|iOS|Optional, JSON array as string|Indicates the string value to replace format specifiers in body string for localization. On iOS, this corresponds to "loc-args" in APNS payload.|
168|title_loc_args|iOS|Optional, JSON array as string|Indicates the string value to replace format specifiers in title string for localization. On iOS, this corresponds to "title-loc-args" in APNS payload.|
169|title_loc_key|iOS|Optional, string|Indicates the key to the title string for localization. On iOS, this corresponds to "title-loc-key" in APNS payload.|
170
171Notice notification payload defined in [GCM Connection Server Reference](https://developers.google.com/cloud-messaging/server-ref#table1)
172
173## Custom GCM request options
174
175You can provide custom `request` options such as `proxy` and `timeout` for the GCM request. For more information, refer to [the complete list of request options](https://github.com/request/request#requestoptions-callback). Note that the following options cannot be overriden: `method`, `uri`, `body`, as well as the following headers: `Authorization`, `Content-Type`, and `Content-Length`.
176
177```js
178// Set custom request options
179var requestOptions = {
180 proxy: 'http://127.0.0.1:8888',
181 timeout: 5000
182};
183
184// Set up the sender with your API key and request options
185var sender = new gcm.Sender('YOUR_API_KEY_HERE', requestOptions);
186
187// Prepare a GCM message...
188
189// Send it to GCM endpoint with modified request options
190sender.send(message, { registrationTokens: regTokens }, function (err, response) {
191 if(err) console.error(err);
192 else console.log(response);
193});
194```
195
196## GCM client compatibility
197
198As of January 9th, 2016, there are a few known compatibility issues with 3rd-party GCM client libraries:
199
200### phonegap-plugin-push
201
202* [No support for subscribing to PubSub topics](https://github.com/phonegap/phonegap-plugin-push/issues/79)
203* [Requirement for `data` payload object when sending a `notification` object](https://github.com/phonegap/phonegap-plugin-push/issues/387)
204* [Requirement for all 3 `notification` fields when sending a `notification` object (title, icon, message)](https://github.com/ToothlessGear/node-gcm/issues/180)
205
206These issues are out of this project's context and can only be fixed by the respective 3rd-party project maintainers.
207
208## Debug
209
210To enable debug mode (print requests and responses to and from GCM),
211set the `DEBUG` environment flag when running your app (assuming you use `node app.js` to run your app):
212
213```bash
214DEBUG=node-gcm node app.js
215```
216
217## Donate
218
219 Bitcoin: [13iTQf7tDhrKgibw2Y3U5SyPJa7R8sQmHQ](https://blockchain.info/address/13iTQf7tDhrKgibw2Y3U5SyPJa7R8sQmHQ)