問題描述:訪問 客服發(fā)送消息接口 中文出現(xiàn)亂碼
- 實(shí)際發(fā)送的content:"小助手刷新有問題啦,快去看看吧"
-
實(shí)際顯示的內(nèi)容:\u5c0f\u52a9\u624b\u5237\u65b0\u6709\u95ee\u9898\u5566\uff0c\u5feb\u53bb\u770b\u770b\u5427
image.png
解決方法:將json轉(zhuǎn)換為utf-8編碼的bytes數(shù)據(jù):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 = 輸入需要發(fā)送的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):
"""
客服接口-發(fā)消息
: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())
結(jié)果展示:
image.png