Saturday 6 May 2017

Can I use APNs Auth Key .p8 file with PHP to send iOS push notifications?

My push notifications stopped working with one of the recent updates. When I looked into it more, I discovered that Apple now lets you generate a non-expiring APNs Auth Key that works for both production and test. I have it working with the following node.js script:

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: '<my key id>', // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key)
        teamId: '<my team id' // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/)
    },
    production: false // Set to true if sending a notification to a production iOS app
});

// Enter the device token from the Xcode console
var deviceToken = '<my device token>';

// Prepare a new notification
var notification = new apn.Notification();

// Specify your iOS app's Bundle ID (accessible within the project editor)
notification.topic = '<my 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 = 3;

// 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 = 'This is a test notification \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);
    process.exit(0)
});

Is there any way to use the new APNs Auth Key with PHP? I can call the node.js script from PHP, using exec("node app.js &", $output);, and it works, but it starts to get ugly. Should PHP still work using the old .pem file approach?



via Lastmboy

No comments:

Post a Comment