Hey there, JavaScript wizards! Ready to level up your Office 365 integration game? Let's dive into the world of webhooks and see how we can make our apps more responsive and user-friendly.
Webhooks in Office 365 are like having a personal assistant who taps you on the shoulder whenever something important happens. They're perfect for creating real-time, user-facing integrations that keep your app in sync with Office 365 events.
Make sure you've got:
We'll be using microsoft-graph-client
and express
, so let's get those installed:
npm install @microsoft/microsoft-graph-client express
First things first, we need to tell Azure AD about our awesome app:
Don't worry, it's easier than it sounds!
Now for the fun part - let's create a subscription using the Microsoft Graph API:
const { Client } = require('@microsoft/microsoft-graph-client'); require('isomorphic-fetch'); const client = Client.init({ authProvider: (done) => { // Your auth logic here done(null, 'YOUR_ACCESS_TOKEN'); } }); async function createSubscription() { const subscription = { changeType: 'created,updated', notificationUrl: 'https://your-app.com/webhook', resource: 'me/messages', expirationDateTime: new Date(Date.now() + 3600 * 1000).toISOString(), clientState: 'secretClientState' }; try { const result = await client.api('/subscriptions').post(subscription); console.log('Subscription created:', result); } catch (error) { console.error('Error creating subscription:', error); } } createSubscription();
Your app needs to be ready to receive notifications. Here's a quick Express route to handle incoming webhooks:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const validationToken = req.query.validationToken; if (validationToken) { console.log('Validating webhook'); res.set('Content-Type', 'text/plain'); res.send(validationToken); } else { console.log('Received notification:', req.body); res.sendStatus(202); } }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
Always validate those notifications! Here's a simple way to do it:
function validateNotification(notification) { // Check if the clientState matches your secret if (notification.clientState !== 'secretClientState') { throw new Error('Invalid clientState'); } // Add more validation as needed }
Once you've got your notifications, it's time to put them to work:
function processNotification(notification) { const changeType = notification.changeType; const resourceData = notification.resourceData; switch (changeType) { case 'created': console.log('New item created:', resourceData.id); break; case 'updated': console.log('Item updated:', resourceData.id); break; // Handle other change types } }
Subscriptions don't last forever, so let's keep them fresh:
async function renewSubscription(subscriptionId) { const expirationDateTime = new Date(Date.now() + 3600 * 1000).toISOString(); try { const result = await client.api(`/subscriptions/${subscriptionId}`) .patch({ expirationDateTime }); console.log('Subscription renewed:', result); } catch (error) { console.error('Error renewing subscription:', error); } }
And there you have it! You're now equipped to create some seriously cool, real-time Office 365 integrations. Remember to handle errors gracefully, keep your subscriptions renewed, and always validate those incoming notifications.
Keep experimenting and push the boundaries of what's possible with Office 365 webhooks. The sky's the limit!
Happy coding, and may your webhooks always be responsive! 🚀