简体   繁体   中英

Apple Push Notifications (APN) service server side Python 2 script in iOS

I have configured my iOS application with Apple Push Notification (APN) service enabled. I was able to send notifications to devices with PHP and Python 3 scripts. I tested both on local server with local machine. But now I need to write the script in Python2.

Below is the script I've written and when I run this I get nothing. Neither a notification to my device nor error in command line.

import socket, ssl, json, struct
import binascii
import os

deviceToken = 'my_device_tocken_without_spaces' 

thePayLoad = {
     'aps': {
          'alert':'My first push notification!',
          'sound':'default'
          }
     }

theCertfile = 'ck3_2.pem'

theHost = ( 'gateway.sandbox.push.apple.com', 2195 )

data = json.dumps( thePayLoad )

theFormat = '!BH32sH%ds' % len(data)

theNotification = struct.pack( theFormat, 0, 32, deviceToken, len(data), data )

ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )

ssl_sock.connect( theHost )

ssl_sock.write( theNotification )

ssl_sock.close()

What did I miss? How can I check where is the mistake happen?

I ran PHP script in localhost using XAMPP and I ran Python script in command line because I was unable to set-up Python with XAMPP which I already posted a question here .

you may consider https://github.com/djacobs/PyAPNs that wrapped lot of useful features, including:

  • error handling
  • support enhanced message format and auto resend messages which are sent before error response
  • non-blocking ssl socket connection with great performance

I think there's nothing wrong with your code. You can try adding following lines after ssl_sock.connect( theHost )

print repr(ssl_sock.getpeername())
print ssl_sock.cipher()
print pprint.pformat(ssl_sock.getpeercert())

Which will print information about ssl of your connection.

Alternatively you can create a sample server and change the connections in your client and test against the server. http://carlo-hamalainen.net/blog/2013/1/24/python-ssl-socket-echo-test-with-self-signed-certificate

You imported binascii, but you forgot to use it. Convert the token and json data to byte arrays, eg:

deviceToken = binascii.a2b_hex('my_device_tocken_without_spaces')

and

data = json.dumps(thePayLoad, separators=(',', ':'), ensure_ascii=False).encode('utf-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM