Created
August 24, 2020 21:43
-
-
Save cruzach/8535b87d9f6475a78df22b69cf86da03 to your computer and use it in GitHub Desktop.
Example of sending a notification to APNS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jwt = require("jsonwebtoken"); | |
const http2 = require("http2"); | |
const fs = require("fs"); | |
const token = jwt.sign( | |
{ | |
iss: "APPLE-TEAM-ID" | |
iat: Math.round(new Date().getTime() / 1000), | |
}, | |
fs.readFileSync("./myapp_apns_key.p8", "utf8"), | |
{ | |
header: { | |
alg: "ES256", | |
kid: "P8-KEY-ID", | |
}, | |
} | |
); | |
const client = http2.connect( | |
IS_PRODUCTION ? 'https://api.push.apple.com' : 'https://api.sandbox.push.apple.com' | |
); | |
const deviceToken = "device token grabbed cient-side"; | |
headers = { | |
":method": "POST", | |
":scheme": "https", | |
"apns-topic": "YOUR-BUNDLE-IDENTIFIER", //your application bundle ID | |
":path": "/3/device/" + deviceToken, | |
authorization: `bearer ${token}`, | |
}; | |
const request = client.request(headers); | |
request.setEncoding("utf8"); | |
request.write( | |
JSON.stringify({ | |
aps: { | |
alert: { | |
title: "\uD83D\uDCE7 You've got mail!", | |
body: "Hello world! \uD83C\uDF10", | |
}, | |
}, | |
}) | |
); | |
request.on("response", (headers, flags) => { | |
for (const name in headers) { | |
console.log(`${name}: ${headers[name]}`); | |
} | |
}); | |
let data = ""; | |
request.on("data", (chunk) => { | |
data += chunk; | |
}); | |
request.on("end", () => { | |
console.log(`\n${data}`); | |
client.close(); | |
}); | |
request.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment