python - 制作.p12/.pem并在本地测试APNS的正确方法

标签 python ios push-notification apple-push-notifications

我找不到任何突出显示如何创建 .p12/.pem 文件并在本地测试推送通知的脚本。

我找到了多种制作 .pem 文件(带/不带密码、.key 和 .cer 组合等)和 .p12 文件的方法,但最终出现 ssl 错误或设备 token 无效。

哪个脚本有效以及如何创建它所需的证书。

最佳答案

如果你坚持使用.pem 和证书,那么下面的代码就可以了..

# setup:
# sudo apt-get install python35
# python select --set python python35
# sudo apt-get install py35-pip
# python select --set pip pip35
# sudo pip35 install Hyper


import ssl
import json
from hyper import HTTP20Connection
from hyper import tls

APNS_SANDBOX_HOST = 'api.development.push.apple.com'
APNS_PRODUCTION_HOST = 'api.push.apple.com'

class APNS(object):
    def __init__(self, sandbox=True):
        self.sandbox = sandbox
        self.port = 443
        self.host = APNS_SANDBOX_HOST if sandbox else APNS_PRODUCTION_HOST

        certificate_file = "./apns_dev.pem" if sandbox else "./apns_prod.pem"

        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        ctx.load_cert_chain(keyfile=certificate_file, certfile=certificate_file)

        self.connection = HTTP20Connection(self.host, port=self.port, ssl_context=ctx, force_proto=tls.H2C_PROTOCOL)

    def push(self, uuid, topic, payload):
        headers = {
            "apns-topic": topic,
            "apns-priority": str(10),
            "apns-expiration": str(0)
        }

        self.connection.request("POST", "/3/device/{0}".format(uuid), payload, headers=headers)
        return self.connection.get_response()


if __name__ == "__main__":
    payload = {
        "aps": {
            "alert": {
                "title": "Hey",
                "body": "Test"
            },
            "sound": "default"
        }
    }

    apns = APNS()
    print(apns.push(uuid="device_uuid", topic="bundle_id", payload=json.dumps(payload)).read())

附言我强烈建议使用 jwt token 而不是证书。它非常简单,不会过期,您不必担心证书和 key 或任何东西。

关于python - 制作.p12/.pem并在本地测试APNS的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46893594/

相关文章:

mod-wsgi - Python 中子解释器 API 的用途是什么?

python - 使用 self.* 作为方法的默认值

ios - 在 Xcode 4.5 和 4.6 中调试速度非常慢

ios - 为 UIViewController 中的 UIView 创建 Controller

python-2.7 - 如果使用 python 和 opencv 在两个目录之间检测到公共(public)面孔,如何通知用户

python - 如何从外部访问函数的 FREE 变量

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'str' Simpleton

ios - Adobe AIR 无法在 iOS 上加载 PDF

ios - 更改应用程序中解析推送通知的当前 channel

ios - UrbanAirship iOS SDK - 是否有通知权限请求回调?