Skip to content

Instantly share code, notes, and snippets.

@orehush
Created July 5, 2018 14:24
Show Gist options
  • Save orehush/f101052e781f78b8f42f1c68a4503196 to your computer and use it in GitHub Desktop.
Save orehush/f101052e781f78b8f42f1c68a4503196 to your computer and use it in GitHub Desktop.
Send apns notification to iOS device in Python
import socket
import ssl
import json
import struct
import binascii
# device token returned when the iPhone application
# registers to receive alerts
device_token = b'XXXX ... XXX'
payload = {
'aps': {
'alert':'Test',
'sound':'default',
},
'msgData': { 'foo': 'bar' },
}
# Certificate issued by apple and converted to .pem format with openSSL
# Per Apple's Push Notification Guide (end of chapter 3), first export the cert in p12 format
# openssl pkcs12 -in cert.p12 -out cert.pem -nodes
# when prompted "Enter Import Password:" hit return
#
cert_file = 'voip.pem'
host = ('gateway.push.apple.com', 2195)
data = json.dumps(payload).encode()
# convert to hex
byte_token = binascii.hexlify(device_token) # Python 3
format = '!BH32sH%ds' % len(data)
notification = struct.pack(format, 0, 32, byte_token, len(data), data)
# Create our connection using the certfile saved locally
ssl_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), certfile=cert_file)
ssl_sock.connect(host)
# Write out our data
ssl_sock.write(notification)
# Close the connection -- apple would prefer that we keep
# a connection open and push data as needed.
ssl_sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment