Although the WhatsApp API integration in Twilio is still in beta and they're working with the WhatsApp Team for the best integration, I have successfully sent an MP3 audio message through the sandbox environment.
The logic is:
From the WhatsApp app I send a message to the Twilio sandbox number.
- Twilio receive the message and forward (POST) it through the webhook to a my Node.js app endpoint hosted in Heroku.
- The Heroku Node app receive the message and do some logic.
- After the logic is done I need to reply with a text message followed by an audio message, below the snippet that I've used:
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const twiml = new MessagingResponse();
//Text Message
var msg = twiml.message("Text Message");//Text Message
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
//Audio Message
client.messages
.create({
to: req.body.From,//req is the request arrived from the Twilio forward webhook
from: req.body.To,
body: "",
mediaUrl: "http://www.example.com/audio/test.mp3",
})
.then((message) => console.log(message.sid));
When the audio message arrives into the WhatsApp App you can listen it directly without browse the link where the audio is hosted.
Keep in mind that WhatsApp could block messages but in this case you should see the error logs in the Twilio Dashboard.