我在使用 Whatsapp Cloud API(已于 5 月 22 日向公众发布)时遇到问题。我做了一切在入门 https://developers.facebook.com/docs/whatsapp/cloud-api/get-started in "设置开发者资产和平台访问“部分,这样我就可以发送模板你好世界在 Ubuntu 20.04.4 LTS 中:
curl -i -X POST \
https://graph.facebook.com/v14.0/my_number/messages \
-H 'Authorization: Bearer my_token' \
-H 'Content-Type: application/json' \
-d '{ "messaging_product": "whatsapp",
"to": "my_reciever",
"type": "template",
"template": { "name": "hello_world", "language": { "code": "en_US" } }
}'
or with Python 3.10 and 请求2.27.1 with:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "template",
"template": {"name": "hello_world", "language": {"code": "en_US"}}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
然后,我尝试发送一个短信 https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-messages#text-messages有了这个:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "text",
"text": {
"preview_url": "false",
"body": "MESSAGE_CONTENT"
}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
而且,即使响应是正确的,也是这样的:
{'messaging_product': 'whatsapp', 'contacts': [{'input': 'my_reciever', 'wa_id': 'my_reciever'}], 'messages': [{'id': 'wamid.HBgMNTchangingMDYyM0I2AA=='}]}
我在 my_reciver 中没有收到任何消息。我不知道我做错了什么,我可能需要配置 webhook 才能正常工作?我是否需要在收到消息之前选择加入(可以在入门页面中阅读)?
我什至尝试在 python 中使用一些非官方包装器,例如heyoo https://pypi.org/project/heyoo/,但我得到了相同的结果。
希望有人能帮助我解决这个问题,谢谢。
Note: this https://stackoverflow.com/questions/72437657/whatsapp-cloud-api-dont-send-message-node是一篇类似的文章,但那篇文章是关于 Node 的,而不是 Python 或 Curl,所以我想这不算是转发。