我如何使用brevo api发送whatsapp消息?

问题描述 投票:0回答:2

遵循这些文档https://mukulsib.readme.io/reference/sendwhatsappmessage

我写了这段代码:

import axios from 'axios';

const API_KEY = '/i got api key from brevo SMTP & API page/';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { phoneNumbers, Message } = req.body;

    for (const phone of phoneNumbers) {
        const options = {
            method: 'POST',
            headers: {
              accept: 'application/json',
              'content-type': 'application/json',
              'api-key': API_KEY,
            },
            body: JSON.stringify({
                senderNumber: '123456789', 
                text: Message, 
                contactNumbers: [phone,]
            })
        };

            try {
                const response = await axios.request(options);
                console.log(`Message sent successfully to ${phone}`);
                console.log('Response data:', response.data);
            } catch (error) {
                console.error(`Error sending message to ${phone}:`, error.message);
            }
        }
    
            res.status(200).json({ message: 'Messages sent' });
        } else {
            res.status(405).json({ error: 'Method not allowed' });
        }
    }

当我在文档页面上尝试它时,我收到此错误: {"code": "permission_denied", "message": "您的帐户未注册"}

javascript api next.js whatsapp brevo
2个回答
0
投票
  1. 确保您的 API 密钥已正确分配。
  2. 使用 Axios,通常不需要将 Content-Type 设置为 application/json;当您提供数据对象时,Axios 会自动执行此操作。
  3. 您的错误处理似乎是合适的,但您可能希望记录 error.response.data 以获取更详细的 API 错误消息(如果有)

import axios from 'axios';

const API_KEY = '/i got api key from brevo SMTP & API page/';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { phoneNumbers, Message } = req.body;

    for (const phone of phoneNumbers) {
      try {
        // Construct the request configuration object
        const response = await axios.post('https://api.brevo.io/api/whatsapp/send-message', {
          senderNumber: '123456789',
          text: Message,
          contactNumbers: [phone],
        }, {
          headers: {
            accept: 'application/json',
            'api-key': API_KEY,
          },
        });

        console.log(`Message sent successfully to ${phone}`);
        console.log('Response data:', response.data);

      } catch (error) {
        console.error(`Error sending message to ${phone}:`, error.message);
        // More detailed logging if the response data is available
        if (error.response && error.response.data) {
          console.error('Detailed error:', error.response.data);
        }
      }
    }

    res.status(200).json({ message: 'Messages sent' });
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}


0
投票

您的 API 密钥似乎有问题。它可能不正确,或者有效期可能已过。您可以重新生成密钥并尝试吗?此外,如果不是 API 密钥(授权问题),在 catch 中记录正确格式的错误可以帮助您找到问题

© www.soinside.com 2019 - 2024. All rights reserved.