Skip to content

Instantly share code, notes, and snippets.

@danylokos
Created November 23, 2016 11:49
Show Gist options
  • Save danylokos/1e4af1487e4703389a796d5d36013ff7 to your computer and use it in GitHub Desktop.
Save danylokos/1e4af1487e4703389a796d5d36013ff7 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# Usage:
# send_apn.py --dev --token=$DEVICE_TOKEN --message='Hello World!' --payload='{"foo": "bar"}'
from optparse import OptionParser
import json, binascii, struct, socket, ssl
parser = OptionParser()
parser.add_option("--dev", action="store_true", dest="dev", default=False, help="use development certificate and sandbox")
parser.add_option("--token", action="store", type="string", dest="device_token", help="device token")
parser.add_option("--message", action="store", type="string", dest="message", help="message to be sent")
parser.add_option("--payload", action="store", type="string", dest="payload", help="payload")
(options, args) = parser.parse_args()
def send(device_token, message, payload, dev=False):
if dev:
# openssl pkcs12 -nodes -in CertKey.p12 -out CertKey.pem
certfile = 'DevCertKey.pem'
host = ('gateway.sandbox.push.apple.com', 2195)
else:
certfile = 'ProdCertKey.pem'
host = ('gateway.push.apple.com', 2195)
josn_payload = { 'aps': { 'alert':message, 'sound':'default'}, 'payload':json.loads(payload) }
data = json.dumps(josn_payload)
byte_token = binascii.unhexlify(device_token)
data_format = '!BH32sH%ds' % len(data)
notification = struct.pack(data_format, 0, 32, byte_token, len(data), data)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, certfile=certfile)
ssl_sock.connect(host)
ssl_sock.write(notification)
ssl_sock.close()
if __name__ == "__main__":
send(options.device_token, options.message, options.payload, options.dev)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment