Я хоть убей не могу понять, что я делаю не так. Я тестировал с помощью Graph Explorer, и та же самая полезная нагрузка не работает в Python. Он ссылается на параметр '', которого нет в теле.
Созданный мною шаблон служебного сообщения состоит из двух текстовых компонентов:
def send_template_message(
self,
phone_number: str,
template_name: str,
language_code: str,
template_args: list = [],
):
# API endpoint
url = (
f"https://graph.facebook.com/v21.0/{self. ... }/messages"
)
# Construct the payload
payload = {
"messaging_product": "whatsapp",
"to": phone_number,
"type": "template",
"template": {
"name": template_name,
"language": {"code": language_code},
},
}
if template_args:
payload["template"]["components"] = [
{
"type": "body",
"parameters": [json.dumps(arg) for arg in template_args],
}
]
# Headers
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.whatsapp_api_token}",
}
# Log payload and headers for debugging
logging.info(f"Payload being sent: {payload}")
logging.info(f"Headers being sent: {headers}")
# Send the POST request
response = requests.post(url, headers=headers, json=payload)
# Handle response
if response.status_code != 200:
logging.error(
f"Error sending template message: {response.text}", exc_info=True
)
raise MessageSendError(f"Error sending template message: {response.text}")
return response.json()
Отправляемая полезная нагрузка:
{'messaging_product': 'whatsapp', 'to': '525555555555', 'type': 'template', 'template': {'name': 'rsvp_1', 'language': {'code': 'es'}, 'components': [{'type': 'body', 'parameters': ['{"type": "text", "text": "Hello"}', '{"type": "text", "text": "Hello"}']}]}}
Отправляемые заголовки:
{'Content-Type': 'application/json', 'Authorization': 'Bearer token'}
Ответ:
Ошибка отправки шаблонного сообщения:
{"error":{
"message":"(#100) Invalid parameter",
"type":"OAuthException",
"code":100,
"error_data":{
"messaging_product":"whatsapp","details":"For component BODY, parameter '' does not have a valid phone_number format. Length Limit is 20 characters and detailed format requirements can be found at https:\/\/developers.facebook.com\/docs\/whatsapp\/cloud-api\/guides\/send-message-templates\/utility-templates#template-parameters-and-restrictions."},
"fbtrace_id":"APKhyoUByZY40ni5OA6Nz9o"}
}
Точно такой же запрос в Graph Explorer возвращает это
{
"messaging_product": "whatsapp",
"contacts": [
{
"input": "525555555555",
"wa_id": "525555555555"
}
],
"messages": [
{
"id": "wamid.HBgLMTk3O2323TI1MDc1MzIVAgARGBIwMDQ0NzM3MzQ4MjNERDA2MjIA",
"message_status": "accepted"
}
]
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -cloud-api
Неверный параметр для WhatsApp Cloud API? ⇐ Python
Программы на Python
1733382600
Anonymous
Я хоть убей не могу понять, что я делаю не так. Я тестировал с помощью [b]Graph[/b] Explorer, и та же самая полезная нагрузка не работает в Python. Он ссылается на параметр '', которого нет в теле.
Созданный мною шаблон служебного сообщения состоит из двух текстовых компонентов:
def send_template_message(
self,
phone_number: str,
template_name: str,
language_code: str,
template_args: list = [],
):
# API endpoint
url = (
f"https://graph.facebook.com/v21.0/{self.whatsapp_cloud_number_id}/messages"
)
# Construct the payload
payload = {
"messaging_product": "whatsapp",
"to": phone_number,
"type": "template",
"template": {
"name": template_name,
"language": {"code": language_code},
},
}
if template_args:
payload["template"]["components"] = [
{
"type": "body",
"parameters": [json.dumps(arg) for arg in template_args],
}
]
# Headers
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.whatsapp_api_token}",
}
# Log payload and headers for debugging
logging.info(f"Payload being sent: {payload}")
logging.info(f"Headers being sent: {headers}")
# Send the POST request
response = requests.post(url, headers=headers, json=payload)
# Handle response
if response.status_code != 200:
logging.error(
f"Error sending template message: {response.text}", exc_info=True
)
raise MessageSendError(f"Error sending template message: {response.text}")
return response.json()
[b]Отправляемая полезная нагрузка:[/b]
{'messaging_product': 'whatsapp', 'to': '525555555555', 'type': 'template', 'template': {'name': 'rsvp_1', 'language': {'code': 'es'}, 'components': [{'type': 'body', 'parameters': ['{"type": "text", "text": "Hello"}', '{"type": "text", "text": "Hello"}']}]}}
[b]Отправляемые заголовки:[/b]
{'Content-Type': 'application/json', 'Authorization': 'Bearer token'}
Ответ:
Ошибка отправки шаблонного сообщения:
{"error":{
"message":"(#100) Invalid parameter",
"type":"OAuthException",
"code":100,
"error_data":{
"messaging_product":"whatsapp","details":"For component BODY, parameter '' does not have a valid phone_number format. Length Limit is 20 characters and detailed format requirements can be found at https:\/\/developers.facebook.com\/docs\/whatsapp\/cloud-api\/guides\/send-message-templates\/utility-templates#template-parameters-and-restrictions."},
"fbtrace_id":"APKhyoUByZY40ni5OA6Nz9o"}
}
Точно такой же запрос в Graph Explorer возвращает это
{
"messaging_product": "whatsapp",
"contacts": [
{
"input": "525555555555",
"wa_id": "525555555555"
}
],
"messages": [
{
"id": "wamid.HBgLMTk3O2323TI1MDc1MzIVAgARGBIwMDQ0NzM3MzQ4MjNERDA2MjIA",
"message_status": "accepted"
}
]
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79250011/invalid-parameter-for-whatsapp-cloud-api[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия