url = f"https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token={access_token}"
jsonmenu ={
"button": [{
"type": "click",
"name": "开发指引",
"key": "mpGuide"
},
{
"name": "公众平台",
"sub_button": [{
"type": "view",
"name": "大闸蟹",
"url": ""
}]
},
{
"type": "click",
"name": "周末天气",
"key": "week"
}
]
}
jsonmenu = json.dumps(jsonmenu, ensure_ascii=False).encode("utf-8")
headers = {'Content-Type': 'application/json; charset=utf-8'}
result = requests.post(url, json=jsonmenu,headers=headers).text
print("menuid", json.loads(result))
永远返回的是
{'errcode': 40033, 'errmsg': 'invalid charset. please check your request, if include \\uxxxx will create fail! rid: 657829d3-6b5a9be4-7b7f360a'}
create_url = f"https://api.weixin.qq.com/cgi-bin/menu/create?access_token={access_token}"
response = requests.post(
create_url,
# 使用 ensure_ascii=False 来防止中文被转换为 \uXXXX 格式
data=json.dumps(menu_data, ensure_ascii=False).encode('utf-8'),
headers={'Content-Type': 'application/json; charset=utf-8'}
)
result = response.json()
主要修改:
使用 json.dumps() 时添加 ensure_ascii=False 参数,这样可以保持中文字符原样输出
将 JSON 字符串编码为 UTF-8 字节
不使用 requests 的 json 参数,而是使用 data 参数传递已编码的 JSON 字符串。这样修改后,发送到微信服务器的 JSON 数据中的中文字符将保持原样,而不会被转换为 Unicode 转义序列。
import json import requests url = f"https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token={access_token}" jsonmenu = { "button": [{ "type": "click", "name": "开发指引", "key": "mpGuide" }, { "name": "公众平台", "sub_button": [{ "type": "view", "name": "大闸蟹", "url": "" }] }, { "type": "click", "name": "周末天气", "key": "week" }] } headers = {'Content-Type': 'application/json; charset=utf-8'} result = requests.post(url, json=jsonmenu, headers=headers).json() # 直接使用 .json() 解析 JSON 响应 print("menuid", result)