koajs

苹果推送node-apn

暂无koa版本

与苹果推送通知服务交互的Node.js模块。

准备证书

从苹果请求证书后,从IOS配置入口下载.cer文件(通常名字为_production.cer或aps_development.cer), 保存在干净的目录, 并将其导入到钥匙串访问.

现在应该出现在"Certificates"目录下钥匙圈, 作 Apple {Production|Development} IOS Push Services. 在该证书里面你应该看到一个私有密钥 (只在过滤"Certificates"类别时). 导出私钥为.p12文件.

现在, 目录里包含 cert.cer 和 key.p12, 执行如下命令生成你的 .pem 文件:

$ openssl x509 -in cert.cer -inform DER -outform PEM -out cert.pem
$ openssl pkcs12 -in key.p12 -out key.pem -nodes

如果你使用开发版证书,你可能希望有一个不同的名字以可以在开发版和产品版快速切换. 在模块选项里可以配置文件名, 这样你可以随意起一个更合适的名字.

它也可以提供一个PFX(PFX/ PKCS12)包载入证书, 键和任何相关的CA证书. 要做到这一点的方法是留给读者作为练习. 应该有可能在“Keychain Access”里选择相关项目,并使用带“.p12”格式的导出选项。

功能

  • 快速
  • 保持服务器连接以最大限度的通知量和吞吐率.
  • 增强的带错误处理的二进制接口支持
  • 自动发送因发送错误未发送的通知
  • 反馈服务支持
  • 符合苹果制定的所有的最佳实践

安装

通过 npm:

$ npm install apn

作为你项目子模块 (你需要安装 q)

$ git submodule add http://github.com/argon/node-apn.git apn
$ git submodule update --init

入门

这是一个简单的介绍,请参考doc/了解更多.

模块加载

var apn = require('apn');

连接

创建一个新的到APN代理服务的连接, 通过选项字典来构造. If you name your certificate and key files appropriately (cert.pem and key.pem) then the defaults should be suitable to get you up and running. By default the module will connect to the sandbox environment unless the environment variable NODE_ENV=production is set. For more information consult the documentation (in doc/apn.markdown).

    var options = { };

    var apnConnection = new apn.Connection(options);

Help with preparing the key and certificate files for connection can be found in the wiki

发送通知

为了发送通知首先创建一个 Device对象。 Pass it the device token as either a hexadecimal string, or alternatively as a Buffer object containing the token in binary form.

    var myDevice = new apn.Device(token);

下一步,创建一个通知对象,设置相关参数。 (查看payload 文档获取更多信息.) 并使用 pushNotification 方法链接并发送它。.

    var note = new apn.Notification();

    note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
    note.badge = 3;
    note.sound = "ping.aiff";
    note.alert = "\uD83D\uDCE7 \u2709 You have a new message";
    note.payload = {'messageFrom': 'Caroline'};

    apnConnection.pushNotification(note, myDevice);

The above options will compile the following dictionary to send to the device:

{"messageFrom":"Caroline","aps":{"badge":3,"sound":"ping.aiff","alert":"\uD83D\uDCE7 \u2709 You have a new message"}}

建立反馈服务

苹果推荐定期检测反馈服务,为尝试失败投递的设备列表。

Using the Feedback object it is possible to periodically query the server for the list. Many of the options are similar to that of Connection.

Attach a listener to the feedback event to receive the output as two arguments, the time returned by the server (epoch time) and a Buffer object containing the device token - this event will be emitted for each device separately. Alternatively you can enable the batchFeedback option and the feedback event will provide an array of objects containing time and device properties.

var options = {
    "batchFeedback": true,
    "interval": 300
};

var feedback = new apn.Feedback(options);
feedback.on("feedback", function(devices) {
    devices.forEach(function(item) {
        // Do something with item.device and item.time;
    });
});

By specifying a time interval (in seconds) Feedback will periodically query the service without further intervention.

More information about the feedback service can be found in the feedback service documentation.

调试

If you experience difficulties sending notifications or using the feedback service you can enable debug messages within the library by running your application with DEBUG=apn or DEBUG=apnfb set as an environment variable.

You will need the debug module which can be installed with npm install debug.

You are encouraged to read the extremely informative Troubleshooting Push Notifications Tech Note in the first instance, in case your query is answered there.

APN

node-apn provides a non-blocking, fully managed interface to push notifications to iOS devices using the Apple Push Notification System.

To use the APN Module one must require('apn').

If you are not familiar with how the Apple Push Notificaion System (APNS) works, it is recommended that you read the Local and Push Notification Programming Guide in particular the section on A Push Notification and Its Path.

Sending a Push Notification

Sending push notifications is as simple as creating a new connection to APNS using the Connection class which should be configured, at minimum, with your applications' certificate and private key. The Connection class manages underlying sockets automatically.

Pushing a notification to a device is as simple as creating an instance of Notification and configuring its payload. When the payload is prepared and the Device token is ready, call Connection#pushNotification with the notification object and the device token you wish to send it to. It is also possible to send the same notification object to multiple devices very efficiently please consult the documentation for Connection#pushNotification for more details.

Connection documentation Notification documentation

The status of the Connection object, including underlying connections, can be observed by the events emitted. It is particularly important that you read Handling Errors

Monitoring the Feedback Service.

Apple provides the "Feedback Service" to inform you when devices you have attempted to send notifications to are no longer reachable - usually because the app has been deleted from the users device. The Feedback class will handle connecting to the Feedback service periodically and providing the results to your application for processing.

Feedback documentation

apn.Device(deviceToken)

Returns a new Device object. deviceToken can be a Buffer or a String containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid.

支持

If you have any questions or difficulties working with the module, the node-apn Google group should be your first port of call.

Please include as much detail as possible - especially debug logs, if the problem is reproducible sample code is also extremely helpful. GitHub Issues should only be created for verified problems and enhancements, this will allow them to be tracked more easily.

资源

贡献者

编写和维护 Andrew Naylor.

感谢: Ian Babrou, dgthistle, Keith Larsen, Mike P, Greg Bergé, Asad ur Rehman, Nebojsa Sabovic, Alberto Gimeno, Randall Tombaugh, Michael Stewart, Olivier Louvignes, porsager, Craig Hockenberry

证书

Released under the MIT License

Copyright (c) 2013 Andrew Naylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.