python实现的华为推送,开发文档。
请结合开发文档理解以下内容
1. 封装HuaWeiPusher类,这里把SecretKey和APPID直接写死了(应该写到配置文件里的)
import requests
import datetime, time,json
from urllib.parse import quote
class HuaWeiPusher:
def __init__(self):
self.SecretKey = "xxx"
self.APPID = "xxx"
self.TokenUrl = "https://login.cloud.huawei.com/oauth2/v2/token"
self.TokenHeader = {
"Host": "Login.cloud.huawei.com",
"Content-Type": "application/x-www-form-urlencoded"
}
self.s = requests.Session()
self.Token = self.getToken()
2. 初始化后,需要根据文档,实现第一个接口,获取token
由于有个过期时间,所以每次获取token后都需要计算出过期时间。(之后可以根据这个过期时间,来自动更新token)
def getToken(self):
data = {
"grant_type": "client_credentials",
"client_secret": self.SecretKey,
"client_id": self.APPID,
}
ret = self.s.post(url=self.TokenUrl, data=data, headers=self.TokenHeader)
r = ret.json()
r["expires_time"] = datetime.datetime.now() + datetime.timedelta(seconds=r["expires_in"])
return r
3. 实现消息推送接口
我这里是自定义推送内容
def getAccessToken(self):
if datetime.datetime.now() >= self.Token["expires_time"]:
self.Token = self.getToken()
return self.Token["access_token"]
def push(self,tokens,body):
ctx = '{"ver": "1", "appId":"' + self.APPID + '"}'
url = "https://api.push.hicloud.com/pushsend.do?nsp_ctx=" + quote(ctx, 'utf-8')
payload = {
"hps": {
"msg": {
"type": 3,
"body": body,
"action": {
"type": 1,
"param": {
"intent": f'intent://com.jssj.sb.push/push_detail?pushType=huawei&pushMessage={str(dict(SUB_PUSH, **body))}#Intent;scheme=shanbiaopush;launchFlags=0x10000000;end',
"appPkgName": "com.jssj.sb"
}
}
},
"ext": {
"biTag": "Trump"
}
}
}
data = {
"access_token": self.getAccessToken(),
"nsp_svc": "openpush.message.api.send",
"nsp_ts": str(int(time.time())),
"device_token_list": json.dumps(tokens),
"nsp_fmt":"JSON",
"payload": json.dumps(payload)
}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
ret=self.s.post(url=url,data=data,headers=headers)
return ret.content
# 解释:intent 参数中的{str(dict(SUB_PUSH, **body))}替换成安卓端需要的内容,SUB_PUSH是我的状态码,**body 是解开字典的内容。
最后创建HuaWeiPusher单例,以供其他py文件import
hwp = HuaWeiPusher()
4. 如何调用?
from utils.huaweiPush import HuaWeiPusher
hwp = HuaWeiPusher()
content_bytes = hwp.push(tokens=[push_token], body={"content": "Push message content", "title": "Push message title"}) #push_token 就是华为手机给用户的唯一标识,需要客户端提供。
网友评论