async def create_wechat_menu(menu_data: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
创建微信公众号自定义菜单
:param menu_data: 格式化后的菜单数据,符合微信菜单 API 要求的 JSON 结构。
:return: 微信接口的返回数据
"""
try:
access_token = await get_access_token()
create_menu_url = f"https://api.weixin.qq.com/cgi-bin/menu/create?access_token={access_token}"
from urllib.parse import quote
for button in menu_data:
button["name"] = sanitize_text(button.get("name"), max_length=16)
if "url" in button:
button["url"] = quote(sanitize_text(button["url"]), safe=":/")
for sub_button in button.get("sub_button", []):
sub_button["name"] = sanitize_text(sub_button.get("name"), max_length=16)
if "url" in sub_button:
sub_button["url"] = quote(sanitize_text(sub_button["url"]), safe=":/")
import json
final_data = {"button": menu_data}
print("Final JSON Data:", json.dumps(final_data, ensure_ascii=False))
final_data = json.dumps(final_data, ensure_ascii=False)
async with httpx.AsyncClient() as client:
response = await client.post(
create_menu_url,
json=final_data,
)
print("Sent Data:", final_data)
print("Request URL:", create_menu_url)
print("Response Status Code:", response.status_code)
print("Response Content:", response.text)
data = response.json()
if "errcode" in data and data["errcode"] != 0:
error_msg = data.get("errmsg", "Unknown error from WeChat API")
raise HTTPException(
status_code=500,
detail=f"Failed to create menu: {error_msg} (errcode: {data['errcode']})"
)
return data
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
Formatted menu: [{"name": "联系客服", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}, {"name": "数电票", "sub_button": [{"name": "联系客服", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}]}]
Final JSON Data: {"button": [{"name": "联系客服", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}, {"name": "数电票", "sub_button": [{"name": "联系客服", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}]}]}
Sent Data: {"button": [{"name": "联系客服", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}, {"name": "数电票", "sub_button": [{"name": "联系客服", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}]}]}
Request URL: https:
Response Status Code: 200
Response Content: {"errcode":40033,"errmsg":"invalid charset. please check your request, if include \\uxxxx will create fail! rid: 674efbb6-3395f40c-0cbc93a4"}
你好,中文乱码
{"button": [{"name": "\u8054\u7cfb\u5ba2\u670d", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}, {"name": "\u6570\u7535\u7968", "sub_button": [{"name": "\u8054\u7cfb\u5ba2\u670d", "type": "view", "url": "https://work.weixin.qq.com/kfid/kfc3ddb6b2475315b6c"}]}]}"