皆さんお元気でしたか?
今回は前回のC2DMに続き、APNsをnode.jsで実装したいと思います。
こちらは証明書の発行等、相当厄介ですので、
わからなければコメント等で聞いてください。
証明書の作成
まずは、iOS Provisioning Portalで証明書の発行等の手続きをします。下記を参考に発行いたしました。
【iPhone】Push Notificationの実装方法 | iPhoneアプリで稼げるのか
証明書の変換
次に、先程保存した、.p12ファイルを変換します。まずFTPかscpか何かでサーバにアップロードしてください。
apns_push_projectという仮名を/var/wwwの下に作ると仮定して、
/var/www/apns_push_project/keys/
というディレクトリを作って、そこへコピーしてください。
上記の参考サイトにもありましたが、.pemファイルへ変換しますが、
node.js用に少し改変いたします。
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12 openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12 openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pemこれで、
apns_dev_key.pem
と
apns-dev-key-noenc.pem
が作成されます。今回はこの2つを使用します。
プログラミング
最後にnode.jsのプログラミングです。こちらはnpmでapnモジュールをインストールしておいてください。
npm install apn
そして、サンプルコードへ移ります。
/**
* APNs Sample Code
*
* @author dommy <shonan.shachu at gmail.com>
* @version 1.0.0 updated on 2012-03-15
*/
// settings
var http = require('http');
var server = http.createServer();
// APNs Configuration
var apns = require('apn');
var options = {
cert : './keys/apns-dev-cert.pem',
key : './keys/apns-dev-key-noenc.pem',
gateway : 'gateway.push.apple.com',
port : 2195,
};
// create device object
var token = 'xxxxxxxxxx';
var myDevice = apns.Device(token);
// main function
server.on('request', function(req, res) {
// create apns connection object
var apnsConnection = new apns.Connection(options);
// create notification object
var note = new apns.Notification();
// Notification Configuration
note.badge = 3; // Number will be shown on the right top corner of App icon
note.alert = 'You have new message'; // Message displayed on the Notification Center
note.device = myDevice; // device information
// send notification
apnsConnection.sendNotification(note);
res.writeHead(200, {'Content-Type': 'application/json'});
res.write('{status:1}');
res.end();
});
server.listen(80, '127.0.0.1');
サーバとかポートとかは変えてくださいね。
tokenの取得方法とかはまた解説します。
参考: argon / node-apn | GitHub
0 件のコメント:
コメントを投稿