Skip to content

Instantly share code, notes, and snippets.

@atomAltera
Created August 29, 2017 11:16
Show Gist options
  • Save atomAltera/5e3aa736e5e0701eb69b0657847eea5d to your computer and use it in GitHub Desktop.
Save atomAltera/5e3aa736e5e0701eb69b0657847eea5d to your computer and use it in GitHub Desktop.
Testing APN
#!/usr/bin/env python
import binascii
import json
import socket
import ssl
import struct
import sys
def pack_payload(title, message, data=None, sound='Default', badge=1):
payload = {
'aps': {
'alert': {'title': title, 'body': message, 'data': data},
'sound': sound,
'badge': badge,
'content-available': 1
},
}
return payload
def send_apn_push(token, payload, cert_file):
the_host = ('gateway.push.apple.com', 2195)
data = json.dumps(payload).encode()
# Clear out spaces in the device token and convert to hex
device_token = token.replace(' ', '')
byte_token = binascii.unhexlify(device_token)
the_format = '!BH32sH%ds' % len(data)
the_notification = struct.pack(the_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(the_host)
# Write out our data
ssl_sock.write(the_notification)
# Close the connection -- apple would prefer that we keep
# a connection open and push data as needed.
ssl_sock.close()
return True
if __name__ == '__main__':
token = sys.argv[1]
cert_file = sys.argv[2]
payload = pack_payload('Hello', 'Lorem Ipsum')
send_apn_push(token=token, payload=payload, cert_file=cert_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment