Forked from saminadhikari/APNs request using JWT - node.js
Created
March 19, 2022 13:57
-
-
Save EzhilAdhavan/c75907d8fe1400f6954a405b8f6102f3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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'); | |
| /* | |
| Read p8 file. Assumes p8 file to be in same directory | |
| */ | |
| const key = fs.readFileSync(__dirname + "/{your p8 filename}.p8", 'utf8') | |
| //"iat" should not be older than 1 hr from current time or will get rejected | |
| const token = jwt.sign( | |
| { | |
| iss: "{your team ID}", //"team ID" of your developer account | |
| iat: 1588152436 //Replace with current unix epoch time [Not in milliseconds, frustated me :D] | |
| }, | |
| key, | |
| { | |
| header: { | |
| alg: "ES256", | |
| kid: "{key ID of your p8 file}", //issuer key which is "key ID" of your p8 file | |
| } | |
| } | |
| ) | |
| /* | |
| Use 'https://api.push.apple.com' for production build | |
| */ | |
| host = 'https://api.sandbox.push.apple.com' | |
| path = '/3/device/{you device token}' | |
| const client = http2.connect(host); | |
| client.on('error', (err) => console.error(err)); | |
| body = { | |
| "aps": { | |
| "alert": "hello", | |
| "content-available": 1 | |
| } | |
| } | |
| headers = { | |
| ':method': 'POST', | |
| 'apns-topic': 'com.xxxxxx.xxxxxxx', //your application bundle ID | |
| ':scheme': 'https', | |
| ':path': path, | |
| 'authorization': `bearer ${token}` | |
| } | |
| const request = client.request(headers); | |
| request.on('response', (headers, flags) => { | |
| for (const name in headers) { | |
| console.log(`${name}: ${headers[name]}`); | |
| } | |
| }); | |
| request.setEncoding('utf8'); | |
| let data = '' | |
| request.on('data', (chunk) => { data += chunk; }); | |
| request.write(JSON.stringify(body)) | |
| 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