无需第三方工具或WebDriver,用FastAPI+Python对接WhatsApp API构建聊天机器人
对接WhatsApp Business Platform API(无WebDriver/第三方工具方案)
前提准备
- 注册Meta开发者账号,创建应用并启用WhatsApp Business Platform
- 获取Access Token、Phone Number ID、WhatsApp Business Account ID
- 确保FastAPI服务可被公网访问(本地开发可使用ngrok临时暴露端口,生产环境部署到云服务器)
步骤1:FastAPI配置Webhook接收用户消息
WhatsApp会通过POST请求将用户消息推送到指定的Webhook端点,以下是核心实现代码:
from fastapi import FastAPI, Request, Response import json import requests app = FastAPI() # Webhook验证(Meta要求的必填验证步骤) @app.get("/webhook") async def verify_webhook(request: Request): mode = request.query_params.get("hub.mode") token = request.query_params.get("hub.verify_token") challenge = request.query_params.get("hub.challenge") # 替换为你自己设置的验证令牌 CUSTOM_VERIFY_TOKEN = "your_verify_token_here" if mode == "subscribe" and token == CUSTOM_VERIFY_TOKEN: return Response(content=challenge, media_type="text/plain") return Response(status_code=403) # 接收并处理用户消息 @app.post("/webhook") async def handle_messages(request: Request): data = await request.json() if data.get("object") != "whatsapp_business_account": return Response(status_code=404) for entry in data.get("entry", []): for change in entry.get("changes", []): if change.get("field") == "messages": msg_value = change.get("value", {}) incoming_msg = msg_value.get("messages", [{}])[0] user_phone = incoming_msg.get("from") user_text = incoming_msg.get("text", {}).get("body") # 调用你的聊天机器人逻辑生成回复 bot_reply = f"收到你的消息:{user_text}" # 发送回复到用户WhatsApp await send_reply(user_phone, bot_reply) return Response(status_code=200)
步骤2:实现消息发送逻辑
直接调用WhatsApp Business Platform的官方API发送消息,无需任何第三方工具:
async def send_reply(to_phone: str, reply_text: str): # 替换为你的Access Token和Phone Number ID ACCESS_TOKEN = "your_access_token_here" PHONE_NUMBER_ID = "your_phone_number_id_here" api_url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages" headers = { "Authorization": f"Bearer {ACCESS_TOKEN}", "Content-Type": "application/json" } payload = { "messaging_product": "whatsapp", "to": to_phone, "text": {"body": reply_text} } response = requests.post(api_url, headers=headers, json=payload) response.raise_for_status() # 抛出请求错误便于调试
关键注意事项
- 严格遵循Meta的API版本规范,避免因版本迭代导致接口调用失败
- 控制消息发送频率,遵守WhatsApp的限流规则,防止账号被限制
- 可扩展支持图片、按钮、模板消息等多种消息类型,具体参考官方API的payload结构
内容的提问来源于stack exchange,提问作者new_dev
相关产品推荐
相关产品推荐

