python3:访问apple server api

 

一,安装用到的库:

(venv) liuhongdi@lhdpc:/data/work/python/xiaoqu$ pip3 install PyJWT
Collecting PyJWT
  Downloading PyJWT-2.10.1-py3-none-any.whl.metadata (4.0 kB)
Downloading PyJWT-2.10.1-py3-none-any.whl (22 kB)
Installing collected packages: PyJWT
Successfully installed PyJWT-2.10.1

[notice] A new release of pip is available: 24.2 -> 24.3.1
[notice] To update, run: pip install --upgrade pip

 遇到报错时:

NotImplementedError: Algorithm 'ES256' could not be found. Do you have cryptography installed?

解决:

$ pip3 install cryptography

二,代码:

 

import jwt
import time
import requests
import json

issuer_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx"
bundle_id = "com.niubide.house"
privatekey_path = "/data/work/python/SubscriptionKey_XXX357XX74.p8"
privatekey_id = "XXX357XX74"
# 读取密钥文件证书内容
f = open(privatekey_path)
key_data = f.read()
f.close()

# JWT Header
header = {
	"alg": "ES256",
	"kid": privatekey_id,
	"typ": "JWT"
}

# JWT Payload
payload = {
	"iss": issuer_id,
	"aud": "appstoreconnect-v1",
	"iat": int(time.time()),
	"exp": int(time.time()) + 60 * 60, # 60 minutes timestamp
	"nonce": "6edffe66-b482-11eb-8529-0242ac130003",
	"bid": bundle_id
}

# JWT token
token = jwt.encode(headers=header, payload=payload, key=key_data, algorithm="ES256")

print("JWT Token:", token)

# apple test push
url = "https://api.storekit.itunes.apple.com/inApps/v1/notifications/test"


# url = "https://api.storekit.itunes.apple.com/inApps/v1/lookup/" + "MK5TTTVWJH"
header = {
	"Authorization": f"Bearer {token}"
}
# 请求和响应
rs = requests.post(url, headers=header)
data = json.loads(rs.text)

print(data)

 

三,测试效果:

上面的接口是苹果提供的测试推送服务器通知的接口,
发送完后即有服务器通知,如下:

{"notificationType":"TEST","notificationUUID":"xxxxxxxx-xxxx-4978-xxxx-xxxxxxxxxxxx","data":{"appAppleId":1234567890,"bundleId":"com.niubide.house","environment":"Production"},"
version":"2.0","signedDate":1734429074743}

四,参考文档:

https://cloud.tencent.com/developer/article/1939304

https://www.sohu.com/a/562210059_121124372

posted @ 2024-12-21 09:46  刘宏缔的架构森林  阅读(2)  评论(0编辑  收藏  举报