Implementing Webhooks in Business Central
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Implementing Webhooks in Business Central: Advanced Integration Patterns
Introduction: The Power of Event-Driven Integration
In the modern enterprise landscape, no software application lives in a vacuum. Dynamics 365 Business Central often serves as the "system of record" for financial and supply chain data, but it frequently needs to communicate with e-commerce platforms, CRM systems, warehouse management software, or custom internal portals. Historically, integrating these systems relied heavily on "polling"—where an external application repeatedly asks Business Central, "Has anything changed?" every few minutes. This approach is inefficient, creates unnecessary server load, and introduces latency between an event occurring and the downstream system reacting to it.
Webhooks change this paradigm by moving from a polling model to a "push" model. A webhook is essentially a notification sent from Business Central to an external URL whenever a specific event occurs—such as the creation of a new customer, the posting of a sales invoice, or a change in inventory levels. By implementing webhooks, your integrations become event-driven. Your external systems only perform work when an actual change occurs, saving processing power and ensuring that data synchronization happens in near real-time. Understanding how to implement, secure, and manage these webhooks is a critical skill for any developer or consultant working with the Business Central ecosystem.
Not read yet
Understanding the Subscription Model
Business Central utilizes the Microsoft Graph API to manage webhooks. Unlike custom-coded triggers that might exist within the AL (Application Language) environment, webhooks in this context are external subscriptions managed via REST API calls. When you want to listen for changes in Business Central, you register a "subscription" resource through the Graph API. This subscription tells Business Central: "Whenever a record in this specific table changes, send a POST request to this specific URL."
Key Concepts in Webhook Registration
To successfully implement a webhook, you must manage three distinct components: the source (Business Central), the subscription (the registration of intent), and the receiver (your external endpoint).
- The Resource: This is the entity in Business Central you are monitoring. It could be a
customer,salesInvoice,item, or any other entity exposed via the standard API v2.0 or custom APIs. - The Change Type: You can filter which actions trigger the webhook. The available types are
created,updated, anddeleted. - The Notification URL: This is the public-facing endpoint on your server that will receive the JSON payload from Business Central.
- The Client State: This is an optional, opaque string you provide during subscription. Business Central will include this string in the notification payload, allowing your receiver to verify the origin or context of the message.
Callout: Webhooks vs. Polling The fundamental difference between these two patterns is the initiator of the communication. In polling, the external application initiates the request, consuming resources even when no data has changed. In a webhook scenario, Business Central acts as the initiator, pushing data only when an actual state change occurs. This significantly reduces the overhead on the Business Central tenant and minimizes the risk of hitting API throttling limits by eliminating empty requests.
Not read yet
Step-by-Step: Registering a Webhook Subscription
To create a subscription, you must perform a POST request to the subscriptions endpoint of the Business Central API. You will need an OAuth2 access token with the necessary permissions to access the Business Central data.
1. Preparing the Request
Your POST request must be directed to the following endpoint:
https://api.businesscentral.dynamics.com/v2.0/{tenant-id}/{environment}/api/v2.0/subscriptions
The body of your request should look like this:
{
"resource": "api/v2.0/companies({company-id})/customers",
"notificationUrl": "https://your-external-service.com/api/webhook-receiver",
"changeType": "created,updated",
"clientState": "my-secret-verification-token",
"expirationDateTime": "2024-12-31T23:59:59Z"
}
2. The Validation Handshake
When you send this POST request, Business Central does not immediately confirm the subscription. Instead, it sends a validation request to the notificationUrl you provided. This is a security measure to ensure you actually own the endpoint.
Business Central will send a GET request to your URL with a validationToken query parameter. Your application must:
- Extract the
validationTokenfrom the query string. - Return a 200 OK response.
- Include the
validationTokenin the plain-text body of your response.
If your server does not respond with the token within a few seconds, the subscription attempt will fail.
3. Handling Notifications
Once the subscription is active, Business Central will begin pushing notifications. A notification payload typically includes the resource ID, the type of change, and the clientState you provided earlier. Note that the notification does not contain the full object data (e.g., the full customer record). It only provides the URI to the record that changed. Your receiver must then use that URI to perform a GET request to fetch the actual data.
Not read yet
Implementation Best Practices
Implementing webhooks is straightforward, but maintaining them in a production environment requires attention to detail. If your receiver goes down, you could lose important data updates.
Handling Retries and Failures
Business Central expects your endpoint to return a 200 OK or 202 Accepted status code quickly. If your server returns an error or fails to respond, Business Central will retry the request based on an exponential backoff strategy. However, if the endpoint remains unreachable for a prolonged period, the subscription will be automatically deleted.
Warning: Server Availability Never perform heavy processing inside the webhook receiver thread. If your logic involves complex calculations or writing to a slow database, your server might time out before Business Central receives a successful response. Instead, accept the incoming webhook, push the payload into a message queue (like RabbitMQ, Azure Service Bus, or a simple database table), and return the 200 OK response immediately. Process the queue asynchronously.
Security Considerations
Since your webhook endpoint is public-facing, it is vulnerable to malicious actors attempting to spoof notifications. To secure your endpoint:
- Use HTTPS: Never use plain HTTP. Ensure your SSL certificate is valid and issued by a trusted authority.
- Verify the Client State: Use the
clientStatefield as a shared secret or token to verify that the request truly originated from your Business Central integration. - IP Whitelisting: While Microsoft's IP ranges for Business Central can change, you can monitor their published service tags to restrict traffic to your endpoint to only those ranges.
Not read yet
Developing the Receiver: A Practical Example (Node.js)
Below is a simplified example of how to build a webhook receiver using Node.js and Express. This example demonstrates both the validation handshake and the notification handling.
const express = require('express');
const app = express();
app.use(express.json());
// Endpoint for the webhook
app.post('/api/webhook-receiver', (req, res) => {
// 1. Handle Validation Handshake
if (req.query.validationToken) {
return res.status(200).send(req.query.validationToken);
}
// 2. Process the Notification
const notifications = req.body.value;
notifications.forEach(notification => {
console.log(`Resource changed: ${notification.resource}`);
console.log(`Client State: ${notification.clientState}`);
// At this point, trigger a background job to fetch
// the data from Business Central using the resource link.
processUpdate(notification.resource);
});
// 3. Acknowledge receipt
res.status(202).send('Accepted');
});
function processUpdate(resourceUri) {
// Logic to call the GET API and fetch the updated record
console.log(`Fetching data from: ${resourceUri}`);
}
app.listen(3000, () => console.log('Webhook receiver running on port 3000'));
In this example, the validationToken logic is handled first. If the incoming request has the token, we return it immediately as required by the Business Central protocol. If it is a notification, we process the array of changes and return a 202 status, indicating that we have accepted the request and will process it asynchronously.
Not read yet
Comparison Table: Webhook Subscription Parameters
| Parameter | Required | Purpose |
|---|---|---|
resource |
Yes | The path to the entity (e.g., api/v2.0/companies(...)/items) |
notificationUrl |
Yes | The public URL where Business Central sends notifications |
changeType |
Yes | Comma-separated list: created, updated, or deleted |
clientState |
No | A custom string to verify the origin of the notification |
expirationDateTime |
No | When the subscription expires (max 3 days from creation) |
Common Pitfalls and How to Avoid Them
1. Subscription Expiration
A common mistake is forgetting that subscriptions expire. By default, they have a limited lifespan (usually up to 3 days). You must implement a "renewal" mechanism. This involves performing a PATCH request to the subscription endpoint to update the expirationDateTime before it lapses. Many developers schedule a background task that runs once a day to check all active subscriptions and extend their expiration dates.
2. Ignoring Throttling
Even with webhooks, if you have thousands of records updating simultaneously, your receiver might be bombarded with notifications, leading to a surge of GET requests back to Business Central. This can trigger API throttling. Always implement a rate-limiting mechanism in your receiver to ensure you don't exceed the Business Central API limits.
3. Misunderstanding "Change"
The updated change type triggers on any change to the record. This includes system-generated changes or updates to fields you might not care about. If you only care about changes to the Unit Price field, you must fetch the record, compare the new values with your local cache, and only then proceed with your business logic. Do not assume that every webhook notification implies a change to the specific data points you are interested in.
Note: API Limitations Not every table in Business Central is exposed via the API. If your business process requires monitoring a table that is not part of the standard API v2.0, you must create a custom API page in AL. Only then can you subscribe to that entity via webhooks.
Not read yet
Advanced Pattern: The "Sidecar" Architecture
In high-volume environments, it is often beneficial to implement a "sidecar" or "middleware" service. Instead of having Business Central talk directly to your primary application, the webhook is received by a lightweight, scalable microservice. This service is solely responsible for:
- Validating the incoming webhook.
- Storing the notification in a high-speed queue (like Redis or Kafka).
- Returning the 202 Accepted response to Business Central.
A separate worker service then consumes the queue, fetches the full record from Business Central, and performs the necessary business logic. This separation of concerns ensures that even if your primary application is undergoing maintenance or experiencing a heavy load, you do not lose the webhook notifications from Business Central.
Managing Subscriptions Programmatically
Since subscriptions expire, you need a robust way to manage them. Create a configuration table in your external database to store the subscriptionId, the resource being monitored, the companyId, and the expiryDate.
Example: Subscription Renewal Logic
async function renewSubscriptions() {
const subscriptions = await db.getAllSubscriptions();
for (const sub of subscriptions) {
if (isExpiringSoon(sub.expiryDate)) {
const newExpiry = new Date();
newExpiry.setDate(newExpiry.getDate() + 3);
await axios.patch(`${BC_API_BASE}/subscriptions/${sub.subscriptionId}`, {
expirationDateTime: newExpiry.toISOString()
});
await db.updateSubscriptionExpiry(sub.subscriptionId, newExpiry);
}
}
}
This pattern ensures that your integration remains "always-on" without manual intervention.
Not read yet
Why Some Entities Don't Support Webhooks
It is important to note that not all entities in Business Central are eligible for webhook subscriptions. The entity must be exposed via an API that supports the subscriptions resource. If you find that you cannot subscribe to a specific table, verify the following:
- Is it an API v2.0 entity? Standard API v2.0 entities are generally supported.
- Is it a custom API? If you created a custom API page, ensure the
ODataKeyFieldsproperty is set correctly, as this is required for the system to uniquely identify records for webhook notifications. - Is the entity read-only? Some system tables or read-only API projections may not support change tracking, which is the underlying mechanism for webhooks.
Security: Beyond the Basics
While HTTPS and clientState are the baseline, you can add an extra layer of security by implementing a "Signature" header. In your webhook sender configuration (if you were building a system), you would sign the payload with a secret key. Since you are receiving from Business Central, you cannot force them to send a signature. However, you can implement a "verification" step where your receiver immediately calls back to the Business Central API to confirm the resource state before acting on it. This "double-check" pattern ensures that even if a malicious actor sends a fake notification to your URL, your system will verify the actual state of the record in Business Central before executing any logic.
Not read yet
Best Practices Checklist for Integration
- Log Everything: Maintain a log of all incoming webhook requests, including the payload, the timestamp, and the result of the processing. This is invaluable for debugging issues when data seems out of sync.
- Idempotency: Design your processing logic to be idempotent. If you receive the same notification twice (which can happen due to network retries), your code should be able to handle it gracefully without creating duplicate entries or corrupting data.
- Monitor Expirations: Set up alerts for when a subscription renewal fails. If a subscription is deleted, you will stop receiving updates, leading to a silent data sync failure.
- Use Environment Variables: Never hardcode your
notificationUrlor API credentials in your source code. Use environment variables or a secure key management system. - Graceful Degradation: If your external system is down, ensure that you can "catch up" by performing a full sync (polling) once the system is back online. Webhooks should be your primary mechanism, but a manual or scheduled full-sync fallback is a sign of a mature integration.
Not read yet
Common Questions and Troubleshooting
Q: Why am I receiving the same webhook notification multiple times? A: Webhooks rely on network communication. If your server takes too long to respond with a 200/202 status, Business Central assumes the request failed and will retry. Ensure your receiver returns a response as quickly as possible.
Q: How do I know if my webhook is working? A: The most reliable way is to monitor your server logs for incoming POST requests. You can also use tools like RequestBin or Postman's mock server to test your endpoint's ability to handle the handshake and payload format before connecting it to Business Central.
Q: Can I subscribe to multiple companies at once? A: No, subscriptions are scoped to a specific company context. If you have a multi-tenant or multi-company environment, you must create a separate subscription for each company.
Q: What happens if the data changes while I am fetching it? A: This is a classic race condition. Because webhooks only provide a notification of a change, you should always rely on the data returned by the GET request as the "source of truth" at the time of your fetch. If the record changes again immediately after you fetch it, you will simply receive another webhook notification, which is the desired behavior.
Not read yet
Summary: Key Takeaways
- Shift to Event-Driven: Webhooks eliminate the need for polling, allowing your integrations to react to Business Central data changes in real-time while reducing server load and API consumption.
- The Handshake is Mandatory: Every webhook subscription requires a successful validation handshake. Ensure your endpoint is public and capable of returning the
validationTokenprovided by Business Central. - Asynchronous Processing: Always return a success status to Business Central immediately after receiving a notification. Offload the actual data processing to a background task or queue to prevent timeouts and ensure system stability.
- Subscription Maintenance: Subscriptions are not permanent. You must implement a strategy to monitor and renew them regularly, as they will expire and stop sending notifications if left unmanaged.
- Design for Idempotency: Because retries are a normal part of distributed systems, ensure that your integration logic can handle duplicate notifications without causing side effects.
- Security First: Use HTTPS for your receiver and leverage the
clientStatefield to verify that incoming payloads are legitimate. - Fallback Mechanism: Webhooks are great for real-time updates, but they should be supplemented with a full-sync process to handle edge cases or extended downtime, ensuring data integrity across your entire application stack.
Implementing webhooks in Business Central is an exercise in distributed systems design. By following these patterns, you move away from fragile, resource-heavy polling and toward a robust, scalable architecture that keeps your business data in sync across all your platforms. Take the time to build your receiver with reliability and security at its core, and you will have a high-performance integration that serves your business needs for years to come.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820