Created
April 26, 2017 06:27
-
-
Save ArchieR7/500a3831f14ef4c88987659854ae99f3 to your computer and use it in GitHub Desktop.
python apple push notification server by auth key
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
# -*- coding: utf8 -*- | |
import jwt | |
import time | |
import json | |
import os | |
from hyper import HTTPConnection | |
class ApnsPusher: | |
def __init__(self, apns_key_id = '', apns_key_name = '.p8', team_id = '', bundle_id = ''): | |
self.ALGORITHM = 'ES256' | |
self.APNS_KEY_ID = apns_key_id | |
self.APNS_AUTH_KEY = os.path.dirname(os.path.realpath(__file__)) + '/' + apns_key_name | |
self.TEAM_ID = team_id | |
self.BUNDLE_ID = bundle_id | |
def push(self, title, body, device_token, isProduction): | |
file = open(self.APNS_AUTH_KEY) | |
secret = file.read() | |
token = jwt.encode({ | |
'iss': self.TEAM_ID, | |
'iat': time.time() | |
}, | |
secret, | |
algorithm = self.ALGORITHM, | |
headers = { | |
'alg': self.ALGORITHM, | |
'kid': self.APNS_KEY_ID, | |
} | |
) | |
path = '/3/device/{0}'.format(device_token) | |
request_headers = { | |
'apns-expiration': '0', | |
'apns-priority': '10', | |
'apns-topic': self.BUNDLE_ID, | |
'authorization': 'bearer {0}'.format(token.decode('ascii')) | |
} | |
if isProduction: | |
conn = HTTPConnection('api.push.apple.com:443') | |
else : | |
conn = HTTPConnection('api.development.push.apple.com:443') | |
payload_data = { | |
'aps': { | |
'alert': { | |
'title': title, | |
'body': body | |
}, | |
'badeg': 1, | |
'sound': 'default' | |
} | |
} | |
payload = json.dumps(payload_data).encode('utf-8') | |
conn.request( | |
'POST', | |
path, | |
payload, | |
headers=request_headers | |
) | |
resp = conn.get_response() | |
print(resp.status) | |
print(resp.read()) |
Have you succeed in finding a fix?
This is a fantastic example. I've run into a problem though. Calling .decode('ascii')
on the generated token when packaging as request header throws AttributeError: 'str' object has no attribute 'decode'
Omitting the call to .decode()
results in TypeError: Object of type bytes is not JSON serializable
.
Has anyone else encountered this?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gunnartorfis I have the same issue, have you found a fix?