feat: Instagram Inbox using Instagram Business Login (#11054)
This PR introduces basic minimum version of **Instagram Business Login**, making Instagram inbox setup more straightforward by removing the Facebook Page dependency. This update enhances user experience and aligns with Meta’s recommended best practices. Fixes https://linear.app/chatwoot/issue/CW-3728/instagram-login-how-to-implement-the-changes ## Why Introduce Instagram as a Separate Inbox? Currently, our Instagram integration requires linking an Instagram account to a Facebook Page, making setup complex. To simplify this process, Instagram now offers **Instagram Business Login**, which allows users to authenticate directly with their Instagram credentials. The **Instagram API with Instagram Login** enables businesses and creators to send and receive messages without needing a Facebook Page connection. While an Instagram Business or Creator account is still required, this approach provides a more straightforward integration process. | **Existing Approach (Facebook Login for Business)** | **New Approach (Instagram Business Login)** | | --- | --- | | Requires linking Instagram to a Facebook Page | No Facebook Page required | | Users log in via Facebook credentials | Users log in via Instagram credentials | | Configuration is more complex | Simpler setup | Meta recommends using **Instagram Business Login** as the preferred authentication method due to its easier configuration and improved developer experience. --- ## Implementation Plan The core messaging functionality is already in place, but the transition to **Instagram Business Login** requires adjustments. ### Changes & Considerations - **API Adjustments**: The Instagram API uses `graph.instagram`, whereas Koala (our existing library) interacts with `graph.facebook`. We may need to modify API calls accordingly. - **Three Main Modules**: 1. **Instagram Business Login** – Handle authentication flow. 2. **Permissions & Features** – Ensure necessary API scopes are granted. 3. **Webhooks** – Enable real-time message retrieval.  --- ## Instagram Login Flow 1. User clicks **"Create Inbox"** for Instagram. 2. App redirects to the [Instagram Authorization URL](https://developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login/business-login#embed-the-business-login-url). 3. After authentication, Instagram returns an authorization code. 5. The app exchanges the code for a **long-lived token** (valid for 60 days). 6. Tokens are refreshed periodically to maintain access. 7. Once completed, the app creates an inbox and redirects to the Chatwoot dashboard. --- ## How to Test the Instagram Inbox 1. Create a new app on [Meta's Developer Portal](https://developers.facebook.com/apps/). 2. Select **Business** as the app type and configure it. 3. Add the Instagram product and connect a business account. 4. Copy Instagram app ID and Instagram app secret 5. Add the Instagram app ID and Instagram app secret to your app config via `{Chatwoot installation url}/super_admin/app_config?config=instagram` 6. Configure Webhooks: - Callback URL: `{your_chatwoot_url}/webhooks/instagram` - Verify Token: `INSTAGRAM_VERIFY_TOKEN` - Subscribe to `messages`, `messaging_seen`, and `message_reactions` events. 7. Set up **Instagram Business Login**: - Redirect URL: `{your_chatwoot_url}/instagram/callback` 8. Test inbox creation via the Chatwoot dashboard. ## Troubleshooting & Common Errors ### Insufficient Developer Role Error - Ensure the Instagram user is added as a developer: - **Meta Dashboard → App Roles → Roles → Add People → Enter Instagram ID** ### API Access Deactivated - Ensure the **Privacy Policy URL** is valid and correctly set. ### Invalid request: Request parameters are invalid: Invalid redirect_uri - Please configure the Frontend URL. The Frontend URL does not match the authorization URL. --- ## To-Do List - [x] Basic integration setup completed. - [x] Enable sending messages via [Messaging API](https://developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login/messaging-api). - [x] Implement automatic webhook subscriptions on inbox creation. - [x] Handle **canceled authorization errors**. - [x] Handle all the errors https://developers.facebook.com/docs/instagram-platform/instagram-graph-api/reference/error-codes - [x] Dynamically fetch **account IDs** instead of hardcoding them. - [x] Prevent duplicate Instagram channel creation for the same account. - [x] Use **Global Config** instead of environment variables. - [x] Explore **Human Agent feature** for message handling. - [x] Write and refine **test cases** for all scenarios. - [x] Implement **token refresh mechanism** (tokens expire after 60 days). Fixes https://github.com/chatwoot/chatwoot/issues/10440 --------- Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
This commit is contained in:
@@ -63,9 +63,33 @@ class ContactInboxWithContactBuilder
|
||||
contact = find_contact_by_identifier(contact_attributes[:identifier])
|
||||
contact ||= find_contact_by_email(contact_attributes[:email])
|
||||
contact ||= find_contact_by_phone_number(contact_attributes[:phone_number])
|
||||
contact ||= find_contact_by_instagram_source_id(source_id) if instagram_channel?
|
||||
|
||||
contact
|
||||
end
|
||||
|
||||
def instagram_channel?
|
||||
inbox.channel_type == 'Channel::Instagram'
|
||||
end
|
||||
|
||||
# There might be existing contact_inboxes created through Channel::FacebookPage
|
||||
# with the same Instagram source_id. New Instagram interactions should create fresh contact_inboxes
|
||||
# while still reusing contacts if found in Facebook channels so that we can create
|
||||
# new conversations with the same contact.
|
||||
def find_contact_by_instagram_source_id(instagram_id)
|
||||
return if instagram_id.blank?
|
||||
|
||||
existing_contact_inbox = ContactInbox.joins(:inbox)
|
||||
.where(source_id: instagram_id)
|
||||
.where(
|
||||
'inboxes.channel_type = ? AND inboxes.account_id = ?',
|
||||
'Channel::FacebookPage',
|
||||
account.id
|
||||
).first
|
||||
|
||||
existing_contact_inbox&.contact
|
||||
end
|
||||
|
||||
def find_contact_by_identifier(identifier)
|
||||
return if identifier.blank?
|
||||
|
||||
|
||||
179
app/builders/messages/instagram/base_message_builder.rb
Normal file
179
app/builders/messages/instagram/base_message_builder.rb
Normal file
@@ -0,0 +1,179 @@
|
||||
class Messages::Instagram::BaseMessageBuilder < Messages::Messenger::MessageBuilder
|
||||
attr_reader :messaging
|
||||
|
||||
def initialize(messaging, inbox, outgoing_echo: false)
|
||||
super()
|
||||
@messaging = messaging
|
||||
@inbox = inbox
|
||||
@outgoing_echo = outgoing_echo
|
||||
end
|
||||
|
||||
def perform
|
||||
return if @inbox.channel.reauthorization_required?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
build_message
|
||||
end
|
||||
rescue StandardError => e
|
||||
handle_error(e)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def attachments
|
||||
@messaging[:message][:attachments] || {}
|
||||
end
|
||||
|
||||
def message_type
|
||||
@outgoing_echo ? :outgoing : :incoming
|
||||
end
|
||||
|
||||
def message_identifier
|
||||
message[:mid]
|
||||
end
|
||||
|
||||
def message_source_id
|
||||
@outgoing_echo ? recipient_id : sender_id
|
||||
end
|
||||
|
||||
def message_is_unsupported?
|
||||
message[:is_unsupported].present? && @messaging[:message][:is_unsupported] == true
|
||||
end
|
||||
|
||||
def sender_id
|
||||
@messaging[:sender][:id]
|
||||
end
|
||||
|
||||
def recipient_id
|
||||
@messaging[:recipient][:id]
|
||||
end
|
||||
|
||||
def message
|
||||
@messaging[:message]
|
||||
end
|
||||
|
||||
def contact
|
||||
@contact ||= @inbox.contact_inboxes.find_by(source_id: message_source_id)&.contact
|
||||
end
|
||||
|
||||
def conversation
|
||||
@conversation ||= set_conversation_based_on_inbox_config
|
||||
end
|
||||
|
||||
def set_conversation_based_on_inbox_config
|
||||
if @inbox.lock_to_single_conversation
|
||||
find_conversation_scope.order(created_at: :desc).first || build_conversation
|
||||
else
|
||||
find_or_build_for_multiple_conversations
|
||||
end
|
||||
end
|
||||
|
||||
def find_conversation_scope
|
||||
Conversation.where(conversation_params)
|
||||
end
|
||||
|
||||
def find_or_build_for_multiple_conversations
|
||||
last_conversation = find_conversation_scope.where.not(status: :resolved).order(created_at: :desc).first
|
||||
return build_conversation if last_conversation.nil?
|
||||
|
||||
last_conversation
|
||||
end
|
||||
|
||||
def message_content
|
||||
@messaging[:message][:text]
|
||||
end
|
||||
|
||||
def story_reply_attributes
|
||||
message[:reply_to][:story] if message[:reply_to].present? && message[:reply_to][:story].present?
|
||||
end
|
||||
|
||||
def message_reply_attributes
|
||||
message[:reply_to][:mid] if message[:reply_to].present? && message[:reply_to][:mid].present?
|
||||
end
|
||||
|
||||
def build_message
|
||||
# Duplicate webhook events may be sent for the same message
|
||||
# when a user is connected to the Instagram account through both Messenger and Instagram login.
|
||||
# Therefore, we need to check if the message already exists before creating it.
|
||||
return if message_already_exists?
|
||||
|
||||
return if @outgoing_echo
|
||||
|
||||
return if message_content.blank? && all_unsupported_files?
|
||||
|
||||
@message = conversation.messages.create!(message_params)
|
||||
save_story_id
|
||||
|
||||
attachments.each do |attachment|
|
||||
process_attachment(attachment)
|
||||
end
|
||||
end
|
||||
|
||||
def save_story_id
|
||||
return if story_reply_attributes.blank?
|
||||
|
||||
@message.save_story_info(story_reply_attributes)
|
||||
end
|
||||
|
||||
def build_conversation
|
||||
@contact_inbox ||= contact.contact_inboxes.find_by!(source_id: message_source_id)
|
||||
Conversation.create!(conversation_params.merge(
|
||||
contact_inbox_id: @contact_inbox.id,
|
||||
additional_attributes: additional_conversation_attributes
|
||||
))
|
||||
end
|
||||
|
||||
def additional_conversation_attributes
|
||||
{}
|
||||
end
|
||||
|
||||
def conversation_params
|
||||
{
|
||||
account_id: @inbox.account_id,
|
||||
inbox_id: @inbox.id,
|
||||
contact_id: contact.id
|
||||
}
|
||||
end
|
||||
|
||||
def message_params
|
||||
params = {
|
||||
account_id: conversation.account_id,
|
||||
inbox_id: conversation.inbox_id,
|
||||
message_type: message_type,
|
||||
source_id: message_identifier,
|
||||
content: message_content,
|
||||
sender: @outgoing_echo ? nil : contact,
|
||||
content_attributes: {
|
||||
in_reply_to_external_id: message_reply_attributes
|
||||
}
|
||||
}
|
||||
|
||||
params[:content_attributes][:is_unsupported] = true if message_is_unsupported?
|
||||
params
|
||||
end
|
||||
|
||||
def message_already_exists?
|
||||
cw_message = conversation.messages.where(
|
||||
source_id: @messaging[:message][:mid]
|
||||
).first
|
||||
|
||||
cw_message.present?
|
||||
end
|
||||
|
||||
def all_unsupported_files?
|
||||
return if attachments.empty?
|
||||
|
||||
attachments_type = attachments.pluck(:type).uniq.first
|
||||
unsupported_file_type?(attachments_type)
|
||||
end
|
||||
|
||||
def handle_error(error)
|
||||
ChatwootExceptionTracker.new(error, account: @inbox.account).capture_exception
|
||||
true
|
||||
end
|
||||
|
||||
# Abstract methods to be implemented by subclasses
|
||||
def get_story_object_from_source_id(source_id)
|
||||
raise NotImplementedError
|
||||
end
|
||||
end
|
||||
@@ -1,200 +1,42 @@
|
||||
# This class creates both outgoing messages from chatwoot and echo outgoing messages based on the flag `outgoing_echo`
|
||||
# Assumptions
|
||||
# 1. Incase of an outgoing message which is echo, source_id will NOT be nil,
|
||||
# based on this we are showing "not sent from chatwoot" message in frontend
|
||||
# Hence there is no need to set user_id in message for outgoing echo messages.
|
||||
|
||||
class Messages::Instagram::MessageBuilder < Messages::Messenger::MessageBuilder
|
||||
attr_reader :messaging
|
||||
|
||||
class Messages::Instagram::MessageBuilder < Messages::Instagram::BaseMessageBuilder
|
||||
def initialize(messaging, inbox, outgoing_echo: false)
|
||||
super()
|
||||
@messaging = messaging
|
||||
@inbox = inbox
|
||||
@outgoing_echo = outgoing_echo
|
||||
end
|
||||
|
||||
def perform
|
||||
return if @inbox.channel.reauthorization_required?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
build_message
|
||||
end
|
||||
rescue Koala::Facebook::AuthenticationError => e
|
||||
Rails.logger.warn("Instagram authentication error for inbox: #{@inbox.id} with error: #{e.message}")
|
||||
Rails.logger.error e
|
||||
@inbox.channel.authorization_error!
|
||||
raise
|
||||
rescue StandardError => e
|
||||
ChatwootExceptionTracker.new(e, account: @inbox.account).capture_exception
|
||||
true
|
||||
super(messaging, inbox, outgoing_echo: outgoing_echo)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def attachments
|
||||
@messaging[:message][:attachments] || {}
|
||||
def get_story_object_from_source_id(source_id)
|
||||
url = "#{base_uri}/#{source_id}?fields=story,from&access_token=#{@inbox.channel.access_token}"
|
||||
|
||||
response = HTTParty.get(url)
|
||||
|
||||
return JSON.parse(response.body).with_indifferent_access if response.success?
|
||||
|
||||
# Create message first if it doesn't exist
|
||||
@message ||= conversation.messages.create!(message_params)
|
||||
handle_error_response(response)
|
||||
nil
|
||||
end
|
||||
|
||||
def message_type
|
||||
@outgoing_echo ? :outgoing : :incoming
|
||||
end
|
||||
def handle_error_response(response)
|
||||
parsed_response = JSON.parse(response.body)
|
||||
error_code = parsed_response.dig('error', 'code')
|
||||
|
||||
def message_identifier
|
||||
message[:mid]
|
||||
end
|
||||
# https://developers.facebook.com/docs/messenger-platform/error-codes
|
||||
# Access token has expired or become invalid.
|
||||
channel.authorization_error! if error_code == 190
|
||||
|
||||
def message_source_id
|
||||
@outgoing_echo ? recipient_id : sender_id
|
||||
end
|
||||
|
||||
def message_is_unsupported?
|
||||
message[:is_unsupported].present? && @messaging[:message][:is_unsupported] == true
|
||||
end
|
||||
|
||||
def sender_id
|
||||
@messaging[:sender][:id]
|
||||
end
|
||||
|
||||
def recipient_id
|
||||
@messaging[:recipient][:id]
|
||||
end
|
||||
|
||||
def message
|
||||
@messaging[:message]
|
||||
end
|
||||
|
||||
def contact
|
||||
@contact ||= @inbox.contact_inboxes.find_by(source_id: message_source_id)&.contact
|
||||
end
|
||||
|
||||
def conversation
|
||||
@conversation ||= set_conversation_based_on_inbox_config
|
||||
end
|
||||
|
||||
def instagram_direct_message_conversation
|
||||
Conversation.where(conversation_params)
|
||||
.where("additional_attributes ->> 'type' = 'instagram_direct_message'")
|
||||
end
|
||||
|
||||
def set_conversation_based_on_inbox_config
|
||||
if @inbox.lock_to_single_conversation
|
||||
instagram_direct_message_conversation.order(created_at: :desc).first || build_conversation
|
||||
else
|
||||
find_or_build_for_multiple_conversations
|
||||
# There was a problem scraping data from the provided link.
|
||||
# https://developers.facebook.com/docs/graph-api/guides/error-handling/ search for error code 1609005
|
||||
if error_code == 1_609_005
|
||||
@message.attachments.destroy_all
|
||||
@message.update(content: I18n.t('conversations.messages.instagram_deleted_story_content'))
|
||||
end
|
||||
|
||||
Rails.logger.error("[InstagramStoryFetchError]: #{parsed_response.dig('error', 'message')} #{error_code}")
|
||||
end
|
||||
|
||||
def find_or_build_for_multiple_conversations
|
||||
last_conversation = instagram_direct_message_conversation.where.not(status: :resolved).order(created_at: :desc).first
|
||||
|
||||
return build_conversation if last_conversation.nil?
|
||||
|
||||
last_conversation
|
||||
def base_uri
|
||||
"https://graph.instagram.com/#{GlobalConfigService.load('INSTAGRAM_API_VERSION', 'v22.0')}"
|
||||
end
|
||||
|
||||
def message_content
|
||||
@messaging[:message][:text]
|
||||
end
|
||||
|
||||
def story_reply_attributes
|
||||
message[:reply_to][:story] if message[:reply_to].present? && message[:reply_to][:story].present?
|
||||
end
|
||||
|
||||
def message_reply_attributes
|
||||
message[:reply_to][:mid] if message[:reply_to].present? && message[:reply_to][:mid].present?
|
||||
end
|
||||
|
||||
def build_message
|
||||
return if @outgoing_echo && already_sent_from_chatwoot?
|
||||
return if message_content.blank? && all_unsupported_files?
|
||||
|
||||
@message = conversation.messages.create!(message_params)
|
||||
save_story_id
|
||||
|
||||
attachments.each do |attachment|
|
||||
process_attachment(attachment)
|
||||
end
|
||||
end
|
||||
|
||||
def save_story_id
|
||||
return if story_reply_attributes.blank?
|
||||
|
||||
@message.save_story_info(story_reply_attributes)
|
||||
end
|
||||
|
||||
def build_conversation
|
||||
@contact_inbox ||= contact.contact_inboxes.find_by!(source_id: message_source_id)
|
||||
|
||||
Conversation.create!(conversation_params.merge(
|
||||
contact_inbox_id: @contact_inbox.id,
|
||||
additional_attributes: { type: 'instagram_direct_message' }
|
||||
))
|
||||
end
|
||||
|
||||
def conversation_params
|
||||
{
|
||||
account_id: @inbox.account_id,
|
||||
inbox_id: @inbox.id,
|
||||
contact_id: contact.id
|
||||
}
|
||||
end
|
||||
|
||||
def message_params
|
||||
params = {
|
||||
account_id: conversation.account_id,
|
||||
inbox_id: conversation.inbox_id,
|
||||
message_type: message_type,
|
||||
source_id: message_identifier,
|
||||
content: message_content,
|
||||
sender: @outgoing_echo ? nil : contact,
|
||||
content_attributes: {
|
||||
in_reply_to_external_id: message_reply_attributes
|
||||
}
|
||||
}
|
||||
|
||||
params[:content_attributes][:is_unsupported] = true if message_is_unsupported?
|
||||
params
|
||||
end
|
||||
|
||||
def already_sent_from_chatwoot?
|
||||
cw_message = conversation.messages.where(
|
||||
source_id: @messaging[:message][:mid]
|
||||
).first
|
||||
|
||||
cw_message.present?
|
||||
end
|
||||
|
||||
def all_unsupported_files?
|
||||
return if attachments.empty?
|
||||
|
||||
attachments_type = attachments.pluck(:type).uniq.first
|
||||
unsupported_file_type?(attachments_type)
|
||||
end
|
||||
|
||||
### Sample response
|
||||
# {
|
||||
# "object": "instagram",
|
||||
# "entry": [
|
||||
# {
|
||||
# "id": "<IGID>",// ig id of the business
|
||||
# "time": 1569262486134,
|
||||
# "messaging": [
|
||||
# {
|
||||
# "sender": {
|
||||
# "id": "<IGSID>"
|
||||
# },
|
||||
# "recipient": {
|
||||
# "id": "<IGID>"
|
||||
# },
|
||||
# "timestamp": 1569262485349,
|
||||
# "message": {
|
||||
# "mid": "<MESSAGE_ID>",
|
||||
# "text": "<MESSAGE_CONTENT>"
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# ],
|
||||
# }
|
||||
end
|
||||
|
||||
33
app/builders/messages/instagram/messenger/message_builder.rb
Normal file
33
app/builders/messages/instagram/messenger/message_builder.rb
Normal file
@@ -0,0 +1,33 @@
|
||||
class Messages::Instagram::Messenger::MessageBuilder < Messages::Instagram::BaseMessageBuilder
|
||||
def initialize(messaging, inbox, outgoing_echo: false)
|
||||
super(messaging, inbox, outgoing_echo: outgoing_echo)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def get_story_object_from_source_id(source_id)
|
||||
k = Koala::Facebook::API.new(@inbox.channel.page_access_token) if @inbox.facebook?
|
||||
k.get_object(source_id, fields: %w[story from]) || {}
|
||||
rescue Koala::Facebook::AuthenticationError
|
||||
@inbox.channel.authorization_error!
|
||||
raise
|
||||
rescue Koala::Facebook::ClientError => e
|
||||
# The exception occurs when we are trying fetch the deleted story or blocked story.
|
||||
@message.attachments.destroy_all
|
||||
@message.update(content: I18n.t('conversations.messages.instagram_deleted_story_content'))
|
||||
Rails.logger.error e
|
||||
{}
|
||||
rescue StandardError => e
|
||||
ChatwootExceptionTracker.new(e, account: @inbox.account).capture_exception
|
||||
{}
|
||||
end
|
||||
|
||||
def find_conversation_scope
|
||||
Conversation.where(conversation_params)
|
||||
.where("additional_attributes ->> 'type' = 'instagram_direct_message'")
|
||||
end
|
||||
|
||||
def additional_conversation_attributes
|
||||
{ type: 'instagram_direct_message' }
|
||||
end
|
||||
end
|
||||
@@ -68,20 +68,8 @@ class Messages::Messenger::MessageBuilder
|
||||
message.save!
|
||||
end
|
||||
|
||||
def get_story_object_from_source_id(source_id)
|
||||
k = Koala::Facebook::API.new(@inbox.channel.page_access_token) if @inbox.facebook?
|
||||
k.get_object(source_id, fields: %w[story from]) || {}
|
||||
rescue Koala::Facebook::AuthenticationError
|
||||
@inbox.channel.authorization_error!
|
||||
raise
|
||||
rescue Koala::Facebook::ClientError => e
|
||||
# The exception occurs when we are trying fetch the deleted story or blocked story.
|
||||
@message.attachments.destroy_all
|
||||
@message.update(content: I18n.t('conversations.messages.instagram_deleted_story_content'))
|
||||
Rails.logger.error e
|
||||
{}
|
||||
rescue StandardError => e
|
||||
ChatwootExceptionTracker.new(e, account: @inbox.account).capture_exception
|
||||
# This is a placeholder method to be overridden by child classes
|
||||
def get_story_object_from_source_id(_source_id)
|
||||
{}
|
||||
end
|
||||
|
||||
|
||||
Reference in New Issue
Block a user