Skip to content

Instantly share code, notes, and snippets.

@priyadarshy
Forked from fermion/apns.py
Last active December 28, 2015 02:09
Show Gist options
  • Save priyadarshy/7425767 to your computer and use it in GitHub Desktop.
Save priyadarshy/7425767 to your computer and use it in GitHub Desktop.
*.certSigningRequest
*.p12
*.cer
*.pem
import socket
import ssl
import json
import struct
import binascii
def apns_push(device_token, payload):
""" Pushes a python dictionary payload to the device identified with device_token. """
# Certificate issued by apple and converted to .pem format with openSSL
certfile = 'reachd_dev_apns.pem'
host = ('gateway.push.apple.com', 2195 )
# Translate payload to JSON.
payload_json = json.dumps(payload)
# Clear out spaces in the device token and convert to hex
device_token = device_token.replace(' ','')
device_token_bytes = binascii.unhexlify(device_token)
#print("HELLOS")
#print(byteToken)
notification_format = '!BH32sH%ds' % len(payload_json)
notification = struct.pack( notification_format, 0, 32, device_token_bytes, len(payload_json), payload_json)
#Just writing to a file for hex inspection
f = open('the_notification', 'w')
f.write(notification)
f.close()
# Create our connection using the certfile saved locally.
ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile=certfile)
ssl_sock.connect(host)
# Write out our data
ssl_sock.write(notification)
# Close connection upon completion.
ssl_sock.close()
if __name__ == '__main__':
device_token = '096c31c2 adc3dd5b 91675a55 6e2260c3 07e53094 7f0c16c8 59b373a6 7d72a509'
payload = {
'aps': {
'alert':'Oh no! Server\'s Down!',
'sound':'k1DiveAlarm.caf',
'badge':42,
},
'test_data': { 'foo': 'bar' },
}
apns_push(device_token, "hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment