Ayrshare Messaging API for Facebook, Instagram, and X/Twitter

[ad_1]
In the world of digital marketing, apps and platforms are always looking for new tools to improve their interactions with users on their platforms. For years, Ayrshare has provided the industry-leading social media API for editing posts, retrieving statistics, and managing comments.
Now we’re excited to introduce our first social media offering: the Ayrshare Messaging API – a complete solution for managing real-time direct messages (DM) on Facebook Messenger, Instagram Messaging, and X/Twitter Direct Messaging.
Many of our customers have requested the ability to communicate with their users through real-time messaging. Some need support desk chat messages, others to send notifications like order updates, and in many cases to increase sales leads. Now with the new Messaging API, you can manage your user direct messages to your contacts across their preferred channels, allowing them to provide a seamless customer experience. Additionally, the convenience of using a single API to manage messages across different platforms simplifies your deployment and brings all the benefits of the Ayrshare platform.
This guide, with code examples, will walk you through the features, usage, and potential applications of the Messaging API DM capabilities. If you want to get started quickly, you can use the GUI version of messaging in the new Messages tab on the Ayrshare Dashboard. It’s a great example of how to integrate messages into your app.
Using the Messaging API
The Messaging API is designed to provide businesses with a variety of messaging services, including sending and receiving DMs through multiple social media platforms. This includes sending messages (including text, images, videos, and emojis), receiving messages, setting up automatic replies, and subscribing to webhooks to be notified of new messages.
1. Managing the Conversation
The DM API allows you to easily retrieve and manage conversations and receive messages on multiple channels: Facebook Messenger, Instagram Messages, or Direct X Messages.
Retrieving Messages
Using the GET messages endpoint, you can retrieve all messages for a specific platform. Here’s an example that uses cURL to get Facebook DMs using the GET messages endpoint:
curl
-H "Authorization: Bearer API_KEY"
-X GET
The API returns complete data, including:
- Message content
- Attachments (videos, images)
- Reactions (eg, likes, hearts)
- Time stamps
- Sender and recipient information
Here is an example of the returned JSON:
{
"status": "success",
"messages": [
{
"senderId": "106638148652444",
"senderDetails": {
"name": "Ayrshare"
},
"conversationId": "t_10161117434308444",
"created": "2024-06-06T00:54:32.455Z",
"action": "sent",
"recipientId": "7101149746568444",
"id": "m_JH6o-yS83JoxWmQaLrmgSaHwGtfTgQ",
"message": "Howdy!",
"platform": "facebook",
"reactions": {
"7101149746568522": "😆". // Reaction by the customer on the Howdy! message
}
},
{
"senderId": "7101149746568444",
"senderDetails": {
"name": "John Smith",
"profileImage": "
},
"conversationId": "t_10161117434308444",
"created": "2024-06-06T00:54:28.102Z",
"action": "received",
"recipientId": "106638148652329",
"id": "m_HGbotYJUmf4AzyPlJ-2uZqHwGtfTgQihX",
"message": "Look up!",
"platform": "facebook"
},
{
"senderId": "7101149746568444",
"senderDetails": {
"name": "John Smith",
"profileImage": "
},
"conversationId": "t_10161117434308444",
"created": "2024-06-06T00:49:11.679Z",
"action": "received",
"recipientId": "106638148652444",
"id": "m_jXoYQIwTXaq2u06PG6Z8vaHwGtfTgQ",
"message": "How is the weather?",
"platform": "facebook"
}
],
"lastUpdated": "2024-06-09T21:46:04.233Z",
"nextUpdate": "2024-06-09T21:47:04.233Z"
}
Returns Conversations
Sometimes you need to find a list of forum chats. Just add to the query parameter discussionOnly=true. Here’s an example when you get an Instagram chat in Node.js:
const apiKey = 'API_KEY';
const url = 'https://app.ayrshare.com/api/messages/instagram?conversationsOnly=true';
const headers = {
'Authorization': `Bearer ${apiKey}`,
};
fetch(url, {
method: 'GET',
headers: headers,
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Request failed. Status code: ${response.status}`);
}
})
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error.message);
});
And the JSON response for the session ids:
{
"status": "success",
"conversationIds": [
"t_10161117434308444",
"t_356759043857444"
],
"converstationsDetails": [
{
"id": "t_10161117434308444",
"participant": {
"name": "John Smith",
"id": "7101149746568444",
"picture": "
},
"status": "active",
"watermark": 1717889607444
},
{
"id": "t_356759043857444",
"participant": {
"name": "Sara Johnson",
"id": "7365320280173444",
"picture": "
},
"status": "active"
}
],
"lastUpdated": "2024-06-09T21:46:04.233Z",
"nextUpdate": "2024-06-09T21:47:04.233Z"
}
2. Sending a Mass Message
The POST message terminal enables you to send messages with different types of content, including SMS and MMS, to your recipients. This includes images, GIFs, videos, or emojis. Here’s a JavaScript example for sending an image message to an Instagram DM using the POST messages API endpoint:
const apiKey = 'API_KEY';
const url = 'https://app.ayrshare.com/api/messages/instagram';
const data = {
message: "What's up!",
recipientId: '283j839222',
"mediaUrl": ["img.ayrshare.com/012/gb.jpg"]
};
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error);
});
3. Automated Responses
One of the most powerful features is the ability to set up automatic responses. This ensures that your users always get instant recognition, even when you are not immediately available. For example, you can send responses when customer service agents are offline or send one-time passcodes for secure communications. Here’s how to set it up using Python and the API end of an autoresponder to respond with “Howdy!” and with a delay of 1 hour before an automatic reply to that person will be sent again:
import json
import requests
url = '
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer API_KEY'
}
data = {
'autoResponseActive': True,
'autoResponseWaitSeconds': 3600, // 1 hour before next auot response
'autoResponseMessage': 'Howdy!'
}
response = requests.post(url, headers=headers, data=json.dumps(data))
try:
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print('Error:', e)
4. Real-Time Notifications with Webhooks
You can stay on top of your conversations across all communication channels by signing up for a messaging webhook. On Facebook and Instagram, you can register a Messages Action Webhook to receive notifications of new messages, read receipts, or reactions, i.e. snaps to a message. IX requires a higher level program, so contact us if you are interested in that.
Here’s an example of the JSON payload you’ll get when the message is read:
{
"action": "messages",
"code": 200,
"conversationId": "t_10161117434308936",
"created": "2024-06-08T23:33:30Z",
"hookId": "CviPBMXEy3cdJnK0EESd",
"mediaUrls": [],
"platform": "facebook",
"read": 1717889607802,
"readerDetails": {
"name": "John Smith",
"id": "7101149746568444",
"picture": "
},
"recipientId": "106638148652329",
"refId": "9abf1426d6ce9122ef11c8932",
"scheduleDate": "2024-06-08T23:33:30Z",
"senderId": "7101149746568522",
"subAction": "messageRead",
"timeStamp": 1717889610,
"title": "Primary Profile",
"type": "read",
"url": "
}
Using the Ayrshare Messages API
As with all Ayrshare APIs, you can get up and running quickly with the Ayrshare Messaging API:
- Make sure you have a subscription to the Ayrshare Business Plan. If you have not yet registered for the Business Plan, please contact us.
- Enable messaging in your account settings within the dashboard. Please note that texting is a paid add-on.
- Go to the user profiles page and click the “Enable Messaging” box to enable messaging for each user profile. Users will need to reconnect Facebook, Instagram, and X to open messages.
- You are now ready to start using the Messaging API. Now your users can communicate with customers through their preferred channels.
You can also enable messaging to create a user profile by adding messagingActive: true to the profiles endpoint:
const API_KEY = "API_KEY";
fetch("https://app.ayrshare.com/api/profiles", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
title: "ACME Profile", // required
messagingActive: true
}),
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch(console.error);
Why Integrate a Messaging API?
Integrating the Ayrshare Messaging API opens up possibilities and offerings for your platform. Here are some examples, but you probably have even better ones for your business.
- Improved Customer Support: Use a chatbot that handles initial inquiries and easily transfers to human agents if needed. This is where an automated message reply comes in very handy.
- Personalized Marketing: Send targeted product recommendations based on user interactions and preferences.
- Automatic Notifications: Keep users informed about order status, account updates, or upcoming events.
- Lead Generation: Create a funnel of messages that guides potential customers through the sales process. We use this ourselves!
- Public Administration: Connect with your audience across multiple platforms from a single interface.
- A Personalized Experience: Deliver interactions and personalized content, such as alerts, reminders, and notifications, to improve user engagement.
The Ayrshare Messaging API is a great way to offer different messaging capabilities. By providing a unified interface for Facebook Messenger, Instagram Messaging, and X/Twitter Direct Messaging, your business can create engaging, responsive, and personalized communication opportunities.
We’re excited about Ayrshare’s new Messaging API capabilities and are here to help you as you integrate. For more information on all Ayrshare products, detailed documentation, and support, visit the Ayrshare website.