1.首先我們需要了解什么是apns auth key,下面是官方的描述
Use the Apple Push Notification service for your notification requests. One key is used for all of your apps.(使用蘋果推送通知服務通知服務,一個密鑰可以用於你所有的應用程序)
而且正常的證書對應不同的app,推送證書又有生產模式,開發者模式,使用起來非常的不方便。如果使用apns auth key就可以解決上述所有問題。
2.如何生成apns auth key?
(1)新建一個apns auth key,Name按照規則填寫,然后選擇APNs,點擊continue
(2)之后點擊confirm,最后下載證書到本地
(3)搭建測試環境,進入終端
mkdir apns cd apns npm init --yes npm install apn --save
(4)編輯app.js文件,並將剛才下載的證書命名為apns.p8拷貝到apns目錄下,需要注意production字段,是否是生產還是開發者環境通過這個字段來判斷
var apn = require('apn'); // Set up apn with the APNs Auth Key var apnProvider = new apn.Provider({ token: { key: 'apns.p8', // Path to the key p8 file keyId: 'ABCD12345', // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key) teamId: 'ABCD12345', // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/) }, production: true // Set to true if sending a notification to a production iOS app }); // Enter the device token from the Xcode console var deviceToken = '需要推送設備的devicetoken'; // Prepare a new notification var notification = new apn.Notification(); // Specify your iOS app's Bundle ID (accessible within the project editor) notification.topic = 'App的Bundle id'; // Set expiration to 1 hour from now (in case device is offline) notification.expiry = Math.floor(Date.now() / 1000) + 3600; // Set app badge indicator notification.badge = 1; // Play ping.aiff sound when the notification is received notification.sound = 'ping.aiff'; // Display the following message (the actual notification text, supports emoji) notification.alert = 'Hello World \u270C'; // Send any extra payload data with the notification which will be accessible to your app in didReceiveRemoteNotification notification.payload = {id: 123}; // Actually send the notification apnProvider.send(notification, deviceToken).then(function(result) { // Check the result for any failed devices console.log(result); });
(5)運行app.js
node app.js
運行結果
{ sent: [ { device: '設備的devicetoken' } ], failed: [] }