python3 接入IOS推送apn

官方文档地址:ios notification

推送截图步骤:
推送接入方法苹果给出了两种:

  1. certificate 证书接入
  2. token 接入

token 接入方法

  1. 根据文档给出的签名规则获取签名token。
import jwt
import time
token_dict = {
    'iat': int(time.time()),
    'iss': '**********'  #颁发者密钥,其值是您用于开发公司应用程序的10个字符的团队ID。从您的开发人员帐户获取此值
}
header = {
    'alg': "ES256",     # 指定的加密方法
    'kid': "**********" # 您从开发者帐户获得的10个字符的密钥ID
}
signing_pem = open("AuthKey_WW37W62BVM.p8", 'r').read()  # 身份验证令牌签名密钥,指定为文本文件(带有.p8文件扩展名)。

jwt_token = jwt.encode(token_dict,  # payload, 有效载体
                       signing_pem,  # 进行加密签名的密钥
                       algorithm="ES256",  # 指明签名算法方式, 默认也是HS256
                       headers=header  # json web token 数据结构包含两部分, payload(有效载体), headers(标头)
                       ).decode('ascii')  # python3 编码后得到 bytes, 再进行解码(指明解码的格式), 得到一个str

print(jwt_token)
  1. 根据获取的token,发现请求到对应接口(苹果支支持HTTP2请求,普通的请求HTTP1会报错)。
import requests
import json

test_url = "https://api.sandbox.push.apple.com"
product_url = "https://api.push.apple.com"


def get_headers():
    headers = {
        "authorization": "bearer " + jwt_token,
        "apns-push-type": "alert",
        "apns-topic": "com.sxzq.ficc.fawo"
    }
    return headers


def post_data():
    from hyper.contrib import HTTP20Adapter
    sessions = requests.session()
    path = "/3/device/6211b0b7a393c90cc770c7d8a6c54ef760c22a5df1d06eea4778b7d4d614494a"
    url_full = test_url + path
    data = {
        "aps": {
            "alert": "测试通知",
            "sound": "default",
            "badge":4
        }
    }

    print(url_full)
    sessions.mount('https://api.sandbox.push.apple.com', HTTP20Adapter())
    r = sessions.post(url_full, data=json.dumps(data), headers=get_headers())
    print(r.content)
    print(r.status_code)
    print(r.headers)


if __name__ == "__main__":
    post_data()

其他参数说明:
apns-expiration:过期
apns-priority:优先权
apns-collapse-id:合并
content-available:静默提示
其他参数说明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章