问题描述:访问 客服发送消息接口 中文出现乱码
- 实际发送的content:"小助手刷新有问题啦,快去看看吧"
-
实际显示的内容:\u5c0f\u52a9\u624b\u5237\u65b0\u6709\u95ee\u9898\u5566\uff0c\u5feb\u53bb\u770b\u770b\u5427
解决方法:将json转换为utf-8编码的bytes数据:data=bytes(json.dumps(data, ensure_ascii=False), encoding='utf-8')
代码演示:
#!/usr/bin/python3
# _._ encoding: utf-8 _._
import requests
import json
class WeiXin:
def __init__(self):
self.open_id = 输入需要发送的openid
self.appid = 输入公众号的appid
self.secret = 输入公众号的secret
def get_token(self):
"""
获取微信的access_token
:return:返回access_token
"""
url = "https://api.weixin.qq.com/cgi-bin/token"
params = {"grant_type": "client_credential",
"appid": self.appid,
"secret": self.secret}
return requests.get(url=url, params=params).json().get("access_token")
def post_send(self):
"""
客服接口-发消息
:return:
"""
url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"
params = {"access_token": self.get_token()}
header = {"Content-type": "application/json", "charset": "UTF-8"}
data = {
"touser": self.open_id,
"msgtype": "text",
"text": {
"content": "小助手测试失败,请及时查看"
}}
r = requests.post(url=url, headers=header, params=params,
data=bytes(json.dumps(data, ensure_ascii=False), encoding='utf-8'))
return r.json()
a = WeiXin()
print(a. post_send())