Tools

Connect n8n with Facebook Messenger API via Webhook: A Comprehensive Guide 2025 

Automating communication on messaging platforms has become an essential need for modern businesses. Among the available solutions, n8n stands out as a powerful tool that allows you to connect and automate workflows without requiring in-depth programming skills. This article will guide you on how to connect n8n with the Facebook Messenger API via Webhook, unlocking countless automation possibilities for your business. 

1. What is n8n? 

n8n is an open-source workflow automation platform that provides a visual interface to connect various applications and services. Unlike many other solutions, n8n allows you to store data locally, ensuring maximum control and security. 

Key benefits of using n8n compared to other tools on the market: 

  • Free and open-source: Significant cost savings compared to commercial platforms. 

  • Data autonomy: Full control over data flow and customer information. 

  • Unlimited customization: Build complex workflows tailored to specific needs. 

  • Multi-platform integration: Easily connect with various services in a single workflow. 

2. Webhook and API: Key Technical Concepts to Understand 

Before diving into the detailed guide, it's important to understand two fundamental concepts: 

2.1 What is a Webhook? 

A webhook acts as a "digital listener," monitoring events and notifying your application when something happens. In the context of Facebook Messenger, the webhook will receive notifications when a new message is received and pass them to n8n for processing. 

2.2 API in the Messenger Context 

The Facebook Messenger API is a set of rules and protocols that allows your application to interact with the Messenger platform. Through this API, you can receive and send messages, access user information, and many other features. 

3. Detailed Guide: Connecting n8n with Facebook Messenger 

Step 1: Set up a Facebook Developer Application 

  1. Create a new application: 

Visit the Facebook Developer Portal. 

Log in, then go to "My Apps" and click "Create App." 

Fill in the basic information: app name, contact email, then click "Next." 

Tao Ung Dung

In the Use Case section, select Other, then click Next. 

In the Choose an App Type section, select Business, then click Next. 

Then click Create App. 

Step 2: Install and Initialize n8n 

Open Terminal and type the following commands: 

a. Install n8n: 

bash 

npm install n8n -g 

b. Start n8n: 

bash 

n8n start 

By default, the web interface will be available at http://localhost:5678. 

Create a new workflow: 

a. Click Create New Workflow from the dashboard. 

b. Give it a recognizable name, e.g., [BNC] fbMessChatbot. 

Step 3: Set up Webhook in n8n  

  1. Add the Webhook node: 

Find and add the "Webhook" node from the list 

The configuration is as follows:  

  • Authentication: None (temporary) 

  • HTTP Method: GET 

  • Save the webhook URL again 

At this time, you copy the Test URL to test first. After running ok, use the Production URL. 

Tao Webhook

Important: Facebook requires webhooks to use HTTPS. If you're running locally, you'll need to use a tunneling service like ngrok or Cloudflare Tunnel, or you can deploy n8n on a server to run and attach a domain to it, but this will cost you to rent a server. 

Here, I will explain a little about how tunneling works.The tunneling service works by: 

  • Create a connection from your local computer to an intermediary server on the internet 

  • The intermediary server provides a public URL (usually in the form of: random-name.service-name.com) 

  • Any requests sent to this public URL will be forwarded to your local computer 

  • The local computer processes the request and sends the reverse response through the tunnel 

Step 4: Configure Webhooks on Facebook Developer Portal 

  1. Webhook Setup: 

From the Dashboard, click "Settings" in the "Messenger" section 

After going to the "Messenger API Setup" section, in the callback URL box, paste the webhook URL you just created earlier 

In the code verification box, create any string 

Dat Cau Hinh Webhook

Then click the drop-down arrow (in the same row as "Configure webhook") and register the items that you want to give permission for the webhook to make. Here I still choose "massages". 

Go back to n8n and click "Listen for test event". 

Then, go back to Facebook Developer and click "Verify and Save."  

At this point, you'll see the error "Unable to validate callback URL or verification code. Verify the information provided or try again later.", that's okay, because we need to go back to n8n and set up the "Responese webhook". 

Ket Qua Nhan Ve Tu Webhook

Despite the error, the webhook received the data. It's just that we need to set up a response so that Facebook recognizes that the data has been successfully transmitted. 

Now, we need to add the "Edit Fields" node and drag the hub.chanllenge value (the left column) into the Fields to Set box and click "Test step" so that this node receives the previous data. 

Thiet Lap Node Edit Field

Then, add a "Response to webhook" node. In the "Respond with" section, select "Text", then drag the "hub.challenge" value in the left column to the "Respone Body" box, then click "Test step". 

Cai Dat Node Respone to Webhook

Now, you need to go back to the original webhook node, in the "Respond" section, select "Using 'Respond to Webhook node'". 

Then you go out and click "Test workkflow" and then go to Facebook Developer in the "Configure webhook" earlier, click "Verify and save" 

  1. Generate access tokens 

At this time, we need to connect to the page that we want to receive/send messages, so in the "Create access code" section, click connect then select and confirm the page as required. 

Next, you click "Add Subscription" to register the items that this webhook is allowed to do. In case I want to set up a chatbot for Facebook Messenger, I will select at least the "messages" section. 

After that, click "Generate" to generate the code. This code acts as your house key, anyone with a difficult key can enter. Be sure to copy this code. 

Now if you want to test whether the webhook has received the message when someone sends a message to the fanpage, then you should go back to n8n, copy the "Production" link and then change the link again before changing the application to "Official". 

  1. Switch the app to "Official" 

Currently, our application is in the "Development" state, to switch to "Official", you go to the "Application Settings" section and select "Basic Information". 

Fill in the "Privacy policy URL" box, then click Save changes and change the status from "Development" to "Official." 

If you don't have this page available, visit this link to create a free copy. 

Chuyen Ung Dung Thanh Chinh Thuc
  1. Create an Access Token 

You can access the "Explore Graph API" section in Faceook Developer, which can be accessed directly here. 

Then select the app you just created under "Apps on Meta" (1). 

Next, select the page that you want to connect to under "Users or pages" (2). 

Then you give the permissions you want to give the app access and take the corresponding actions (3). 

Finally click "Generate Access Token" (4). 

Note, this is only a temporary token, which will expire for a period of time, so we need to set the validity period for this token. 

You can go to the "Access code debugger" section or go directly here. 

Paste the code you just came out earlier, then click "Debug" and then click the "Extended Access Code" button. 

At this time, a new code will be returned, this code will never expire, so please feel free to use it. Copy this code to use for setting up the n8n side API. 

Step 5: Build a simple chatbot with AI Agent 

  1. Reset webhooks 

First, if you have changed the webhook link to "Product URL", change it back to "Test URL" to make it easier to operate. (Still do the same as before, change the link -> Fill in the authentication code again -> click "Test workflow" (n8n side) -> click "Verify and save" (Facebook Developer side)). 

Now, go back to the webhook node, in the "Settings" tab, check "AllowMultiple HTTP Methods" and then go back to the Parameters tab to check if there are 2 forms in the "HTTP Methods" section, "POST" and "GET". 

For those who don't understand why there must be 2 Methods here: 

  • GET is for you to receive messages from Facebook 

  • POST is for you to set up a chatbot to send data (specifically the chatbot's answer) to Facebook 

Then continue to click "Test workflow" and then message the fanpage again to receive the data returned. 

 
Data Tra Ve Cho Post Event

Then we continue to add the "Edit Fields" node in the POST branch, add 3 new fields and drag the "text" cells one by one and name them "text", "id" (just below the sender) and name them "sender_id", "id" (just below the recipent) and name them "page_id". 

The purpose is to take out this content and use it for later, then click "Test step". 

Cai Dat Node Edit Fields Cho Post
  1. Prevent constant messaging 

Similar to the GET webhook, in POST, Facebook also needs to receive a notification that the data has been sent successfully (within 1 minute), so before setting up the chatbot, we can add another node "Respond to webhook" to return the data to Facebook, avoiding the case that Facebook sends messages continuously because it does not receive a successful response. 

We'll still install the same node as above. In the "Respond With" section, select "Text", and drag the text in the left column to the "Respond Body" box. 

Thiet Lap Respond to Webhook Cho Post

Then we branch out the new branch behind the "Edit Fields" node and add the note "AI Agent" to it. You can refer to AI Agent in this article. 

  1. Setting up AI Agent 

n8n has a lot of built-in AI models that are trending today, most of which are free. The cost will depend on the developer but is generally not too expensive. In this article, I will demo with Google Gemini because this model has a free version. 

First, we will reset the AI Agent first. For the current case (making a chatbot), we just change the "Prompt" to "Define below" and then drag "text" (the message sent by the customer) to the "Text" box, the AI will know by itself to answer this dialogue. If you have a more specific prompt, you can write more. 

Thiet Lap Ai Agent

Then we set up the chat model for the Agent, here as I shared earlier, I will use Google Gemini because it is free. 

For those of you who have not created a Google Gemini Credential, n8n always provides instructions for obtaining API keys, if you are lazy to read, you can refer to our instructions.  

You go to this page, if you don't have an account, please create one. 

Then click the "Create API key" button and select "Create with new project" (or if you already have a project on Google Cloud and want to use it). 

Then copy this key and paste it and the API key box in the "Create New Credential" section. 

Next in the "Model" box, you can choose which model suits your needs. Here, I only reply to messages with customers, I can choose Model 2.0 or 2.5. 

  1. Set up a node to send AI answers to Facebook Messenger 

Before setting up this section, we need to process the data in the AI return section first. Due to the return format that Facebook specifies is Json, there will be downline paragraphs in the AI answer, so before using this answer to send, we need to remove these downline (\n) characters. 

Add the "Code" node. Select the code language as "JavaScript" and then paste this paragraph in: 

let data = $input.first().json.output.replace(/(\r\n|\n|\r)/g, ''); 

return { 'data': data }; 

$input.first().json.output is the output variable (AI's answer), you can drag the variable from the left column in to avoid confusion, then bruise "Test step" to check again. 

Loai Bo Ky Tu Xuong Dong

Add the "HTTP Request" node, select Method as POST. 

In the URL box, fill in this link: https://graph.facebook.com/v22.0//messages 

In which, page_id is the id of the recipient (the right-hand column - this is the recipient's id, i.e. your page id), you can drag in and replace this variable. 

Optionally, turn on the "Send Headers" button, in the "Name" box fill in "Authorization", in the "Value" box fill in "Bearer ". 

is the Page token you generated earlier. 

Thiet Lap Node Tra Ve Du Lieu Dau Ra Cua Ai Qua HTTP Node

Then you go out, click "Test workflow" and message the page to see if the message has been received and sent successfully! 

Now you enable the (active) workflow and change the URL of the webhook to "Production URL" and you are good to go. 

4. Expand and optimize chatbots 

After successfully establishing a basic connection, you can expand the chatbot's functionality: 

4.1 Integration with Databases  

Add Database nodes to store user information, interaction history, or other data. n8n supports a wide range of databases such as MongoDB, MySQL, PostgreSQL. This is the step to set up the memory (database) for the chatbot. You can also specify how many previous conversations the chatbot remembers, which is extremely convenient! 

4.2 Add natural language processing (NLP) 

Connect with NLP services like DialogFlow or OpenAI to create smarter chat experiences, understand user intent, and respond accordingly. 

4.3 Setting up MCP for AI Agent 

In addition, to make the chatbot work smarter and smoother, you can set up additional MCPs to process information and some other tasks. For example, if you want the chatbot to advise on goods and close orders, send order confirmation emails, you should find relevant MCPs to set up the chatbot. MCP allows AI Agents to connect discrete tools into a real brain, helping AI Agents know what to do next without having to write too many complex prompts. I will post a simple MCP AI Agent setup guide in the next n8n, please follow along! 

5. Challenges and Solutions 

When implementing a Messenger chatbot with n8n, you may encounter some challenges: 

5.1 Facebook API Limitations 

Problem: Facebook limits the number of messages and how often they are sent. 

Solution: Added queue handling logic and time spacing between message sends in n8n. 

5.2 Webhook authentication and security 

Problem: Webhooks can be hacked or abused. 

Solution: Add authentication to the webhook and check Facebook's signature in each request. 

5.3 Bug handling and retry 

Problem: An unstable network connection can cause message loss. 

Solution: Add an Error Trigger node and an automatic retry mechanism in n8n. 

5.4 Facebook Webhook Error When Reactivating a Workflow in n8n 

Problem: 

When you pause a workflow in n8n (deactivate) but keep the webhook in the Facebook Developer Portal active, Facebook continues to send events to the URL webhook. Since n8n workflow has been disabled, these events are not processed. Then, when you reactivate the workflow (activate), n8n will receive a series of cumulative requests from Facebook at the same time, causing a "trigger storm" - multiple executions that are triggered simultaneously. 

Solution: 

5.4.1 Use intermediary proxy webhooks 

Instead of giving the n8n webhook URL directly to Facebook, you can set up an intermediate proxy: 

Facebook → API Gateway/Proxy → n8n 

This proxy can: 

  • Always return HTTP 200 OK for Facebook (prevent retry) 

  • Queue requests when n8n is inactive 

  • Allows you to process or delete queues before reactivating n8n 

5.4.2. Toggle webhook subscriptions trên Facebook 

Disable n8n workflows, and disable Facebook webhook subscriptions 

5.4.3. Use a separate verification endpoint 

Create two different endpoint webhooks: 

  • An endpoint that always works only to verify with Facebook 

  • Another endpoint to handle events, which can be turned off/on as needed 

Try Now

6. Conclude 

Connecting n8n to the Facebook Messenger API via webhooks opens up a wealth of possibilities for automating customer communication. While the setup process may be more complex than some other platforms like Telegram, the benefits of reaching billions of Facebook users are undeniable. 

With this detailed guide, you already have a solid foundation for building a powerful Messenger chatbot using n8n - an open-source, flexible, and fully customizable solution for the specific needs of your business. 

Get started today and witness how automated chatbots can significantly improve your customer experience and business performance! 

0/5 - (0 vote)
Comment (0)
More than 500K+ users have signed up to receive daily article update notifications.
Leave your email to receive notifications about the latest tools and technology trends!
Popular
More on this topic
asana vs slack comparison which tool outperforms the other in 2025Asana vs Slack comparison: Which tool outperforms the other in 2025

In this era of rapid technological development, where people work remotely, meet online and manage projects via digital platforms, choosing the right team collaboration tool is a prerequisite to ensure productivity. With a series of work support software on the market, Asana and Slack are always two "big names" in the field of work management and team communication. The question is: Asana or Slack, which platform is really superior at the present time? Let's find out with BENOCODE which is the better choice for your needs in this article!

connect n8n with facebook messenger api via webhook a comprehensive guide 2025Connect n8n with Facebook Messenger API via Webhook: A Comprehensive Guide 2025 

Automating communication on messaging platforms has become an essential need for modern businesses. Among the available solutions, n8n stands out as a powerful tool that allows you to connect and automate workflows without requiring in-depth programming skills. This article will guide you on how to connect n8n with the Facebook Messenger API via Webhook, unlocking countless automation possibilities for your business.