Skip to main content
RapidDev - Software Development Agency
lovable-integrationsEdge Function Integration

How to Integrate Lovable with Microsoft Advertising (Bing Ads)

To integrate Microsoft Advertising (Bing Ads) with Lovable, create Supabase Edge Functions that authenticate using OAuth2 with a developer token, then proxy calls to the Microsoft Advertising API for campaign management and reporting. Store OAuth credentials and developer token in Cloud Secrets to build Bing search campaign dashboards in Lovable.

What you'll learn

  • How to register a Microsoft Advertising app and obtain a developer token and OAuth2 credentials
  • How to implement OAuth2 token refresh in a Supabase Edge Function for Microsoft Advertising
  • How to query the Microsoft Advertising Reporting Service for campaign performance data
  • How to build a Bing search campaign analytics dashboard with spend, click, and conversion metrics
  • How to handle Microsoft Advertising's multi-account structure for agencies managing multiple clients
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate14 min read90 minutesMarketingMarch 2026RapidDev Engineering Team
TL;DR

To integrate Microsoft Advertising (Bing Ads) with Lovable, create Supabase Edge Functions that authenticate using OAuth2 with a developer token, then proxy calls to the Microsoft Advertising API for campaign management and reporting. Store OAuth credentials and developer token in Cloud Secrets to build Bing search campaign dashboards in Lovable.

Build Microsoft Advertising Campaign Dashboards in Lovable with Bing Ads API

Microsoft Advertising reaches a distinct audience that Google Ads often misses — Bing's user base skews older, higher income, and more likely to be in B2B buying roles. Many advertisers run Microsoft Advertising as a complement to Google Ads, but reporting across both platforms typically means switching between two separate interfaces and manually combining data. Building a unified dashboard in Lovable that pulls Microsoft Advertising data via the API lets your team see Bing campaign performance alongside Google and other channels in a single view.

Microsoft Advertising's API structure requires two things beyond a standard OAuth2 setup: a developer token that identifies your application as authorized to call the API, and either your own account's customer ID and account ID or, for agencies, the ability to specify which managed account to query. The authentication pattern is similar to Google Ads in complexity — requiring both OAuth2 user credentials and a developer token — but once set up, the Reporting Service API returns detailed campaign data with flexible date ranges, granularity levels, and metric selections.

Microsoft Advertising also offers an audience network that extends beyond Bing search to display ads on MSN, Outlook, and Microsoft Edge. The API covers search campaigns, shopping campaigns, audience campaigns, and app install ads. This guide focuses on the search campaign reporting use case, which is the highest-traffic scenario, but the same Edge Function pattern supports all campaign types available through the API.

Integration method

Edge Function Integration

Microsoft Advertising integration in Lovable uses Supabase Edge Functions that handle OAuth2 token exchange using a developer token, client credentials, and refresh tokens. All credentials are encrypted in Cloud Secrets and accessed via Deno.env.get(). Edge Functions proxy Reporting Service API calls and return campaign performance data to React dashboard components without exposing any credentials to the browser.

Prerequisites

  • A Microsoft Advertising account with at least one active campaign (or a sandbox test account)
  • A Microsoft Azure AD application registered at portal.azure.com with OAuth2 credentials — client ID and client secret
  • A Microsoft Advertising developer token — apply at the Microsoft Advertising API portal after registering your Azure AD app
  • Your Microsoft Advertising account ID and customer ID (visible in the Ads Manager URL or under Settings)
  • A Lovable project with Lovable Cloud enabled, and patience for the developer token approval process which typically takes 1-3 business days

Step-by-step guide

1

Register an Azure AD application and request a developer token

Microsoft Advertising API requires two separate credentials: OAuth2 credentials from Azure Active Directory and a developer token from Microsoft Advertising. Start with the Azure AD registration. Go to portal.azure.com and log in with your Microsoft account. Navigate to Azure Active Directory → App registrations → New registration. Name your app (e.g., 'Lovable Bing Ads Dashboard'), select 'Accounts in any organizational directory and personal Microsoft accounts' for the supported account types so it works with both consumer and work accounts, and set a redirect URI to your application's OAuth callback URL — use https://login.microsoftonline.com/common/oauth2/nativeclient as a temporary redirect for initial token generation if you do not have a callback endpoint yet. After registering, note your Application (client) ID from the overview page. Go to Certificates & secrets → New client secret, set an expiry, and copy the secret value immediately — it is only shown once. Now for the developer token: log in to Microsoft Advertising at ads.microsoft.com with the same Microsoft account used for Azure AD, navigate to Tools → API Center, click 'Request developer token', fill in the application details, select your purpose (reporting and analytics), and submit. Approval typically takes 1-3 business days. You will start with a sandbox developer token immediately for testing and receive the production token after approval.

Pro tip: Microsoft Advertising has a sandbox environment at https://sandbox.bingads.microsoft.com with free test accounts. Use the sandbox to test your Edge Function and dashboard before connecting to your production account.

Expected result: You have an Azure AD client ID, client secret, and a Microsoft Advertising developer token (sandbox or production) ready to store in Cloud Secrets.

2

Complete the OAuth2 flow and store credentials in Cloud Secrets

Microsoft Advertising uses OAuth2 with the Microsoft identity platform endpoint. To get your first refresh token, you need to complete an authorization code flow. The authorization URL is https://login.microsoftonline.com/common/oauth2/v2.0/authorize with parameters: client_id (your Azure AD app ID), response_type=code, redirect_uri (the same URI you registered), scope=openid profile email https://ads.microsoft.com/msads.manage offline_access, and response_mode=query. Open this URL in a browser, log in with your Microsoft Advertising credentials, grant consent, and copy the authorization code from the redirect URL. Exchange this code for tokens by POSTing to https://login.microsoftonline.com/common/oauth2/v2.0/token with the code, client_id, client_secret, redirect_uri, and grant_type=authorization_code. You receive an access token (valid 1 hour) and a refresh token (valid until revoked). Now open the Cloud tab in Lovable, navigate to Secrets, and add five secrets: MSADS_CLIENT_ID (Azure AD app client ID), MSADS_CLIENT_SECRET (Azure AD client secret), MSADS_REFRESH_TOKEN (refresh token from the OAuth2 flow), MSADS_DEVELOPER_TOKEN (the token from Microsoft Advertising API Center), and MSADS_ACCOUNT_ID (your 10-digit Microsoft Advertising account ID). Lovable's SOC 2 Type II certified Cloud Secrets store protects these credentials from any client-side exposure.

Pro tip: Use Microsoft's OAuth 2.0 Playground or a tool like Postman to complete the initial authorization flow and get your first refresh token without writing code. The refresh token is long-lived and only needs to be regenerated if it is explicitly revoked.

Expected result: All five Microsoft Advertising secrets are stored in Cloud Secrets: client ID, client secret, refresh token, developer token, and account ID.

3

Create the Microsoft Advertising API Edge Function with token refresh

Ask Lovable to create a Supabase Edge Function called bing-ads-api that handles Microsoft Advertising API calls. The function must first exchange the stored refresh token for a fresh access token using the Microsoft identity platform, since access tokens expire after 1 hour. POST to https://login.microsoftonline.com/common/oauth2/v2.0/token with grant_type=refresh_token, the stored refresh token, client_id, and client_secret to receive a new access token. Cache the access token at the module level along with its expiry time to avoid redundant token refreshes on every call. For the Microsoft Advertising REST API, all requests go to https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/V13/ for reporting or https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/v13/ for campaign management. Every API request needs three headers: AuthenticationToken (the Bearer access token), DeveloperToken (your developer token), and CustomerAccountId (your account ID). The function accepts a service (reporting or campaign), a path, HTTP method, and optional request body, routes to the correct base URL, and returns the response. For reporting, requests are submitted asynchronously — submit a report request, poll for completion, then download the report — which the Edge Function should handle as a single synchronous call by polling until ready.

Lovable Prompt

Create a Supabase Edge Function called bing-ads-api. It should first get a fresh access token by POSTing to Microsoft's OAuth2 token endpoint using credentials from Deno.env.get(). Then accept a path, method, and optional body. Build the URL using https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/V13/{path} as the base. Add headers: AuthenticationToken with Bearer token, DeveloperToken from secrets, and CustomerAccountId from secrets. Return the API response JSON. Cache the access token with a 55-minute TTL to avoid re-fetching on every request.

Paste this in Lovable chat

supabase/functions/bing-ads-api/index.ts
1import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
2
3const corsHeaders = {
4 "Access-Control-Allow-Origin": "*",
5 "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6};
7
8let tokenCache: { token: string; expiry: number } | null = null;
9
10async function getAccessToken(): Promise<string> {
11 if (tokenCache && Date.now() < tokenCache.expiry) return tokenCache.token;
12
13 const response = await fetch(
14 "https://login.microsoftonline.com/common/oauth2/v2.0/token",
15 {
16 method: "POST",
17 headers: { "Content-Type": "application/x-www-form-urlencoded" },
18 body: new URLSearchParams({
19 grant_type: "refresh_token",
20 client_id: Deno.env.get("MSADS_CLIENT_ID")!,
21 client_secret: Deno.env.get("MSADS_CLIENT_SECRET")!,
22 refresh_token: Deno.env.get("MSADS_REFRESH_TOKEN")!,
23 scope: "https://ads.microsoft.com/msads.manage offline_access",
24 }),
25 }
26 );
27
28 const data = await response.json();
29 if (!data.access_token) throw new Error(data.error_description || "Token refresh failed");
30
31 tokenCache = {
32 token: data.access_token,
33 expiry: Date.now() + 55 * 60 * 1000,
34 };
35 return tokenCache.token;
36}
37
38serve(async (req) => {
39 if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
40
41 try {
42 const accessToken = await getAccessToken();
43 const developerToken = Deno.env.get("MSADS_DEVELOPER_TOKEN")!;
44 const accountId = Deno.env.get("MSADS_ACCOUNT_ID")!;
45
46 const { path, method = "GET", body: reqBody } = await req.json();
47 if (!path) throw new Error("path is required");
48
49 const url = `https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/V13/${path}`;
50
51 const fetchOptions: RequestInit = {
52 method,
53 headers: {
54 "AuthenticationToken": `Bearer ${accessToken}`,
55 "DeveloperToken": developerToken,
56 "CustomerAccountId": accountId,
57 "Content-Type": "application/json",
58 },
59 };
60
61 if (reqBody && method !== "GET") {
62 fetchOptions.body = JSON.stringify(reqBody);
63 }
64
65 const response = await fetch(url, fetchOptions);
66 const data = await response.json();
67
68 if (!response.ok) throw new Error(JSON.stringify(data));
69
70 return new Response(JSON.stringify(data), {
71 headers: { ...corsHeaders, "Content-Type": "application/json" },
72 });
73 } catch (error) {
74 return new Response(
75 JSON.stringify({ error: error.message }),
76 { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
77 );
78 }
79});

Pro tip: Microsoft Advertising's reporting API is asynchronous — you submit a report request and receive a request ID, then poll for completion before downloading. For simpler integrations, consider using the Bulk Service API which can return synchronous data for basic campaign stats.

Expected result: The bing-ads-api Edge Function is deployed, token refresh works, and the function returns valid API responses.

4

Build the Microsoft Advertising dashboard in Lovable

With the Edge Function deployed, ask Lovable to build a campaign performance dashboard for Microsoft Advertising. Microsoft Advertising's Reporting Service works asynchronously: you submit a report request body specifying report type (CampaignPerformanceReport), time period, columns (like CampaignName, Impressions, Clicks, Spend, Conversions), and aggregation level. The API returns a report request ID. You then poll a status endpoint until the report is ready, then download the report data as a CSV or XML. For the most developer-friendly approach, ask Lovable to handle this polling inside the Edge Function — submit the report, poll every 3 seconds up to a timeout of 60 seconds, and return the processed data. Alternatively, use the Campaign Management Service which has synchronous endpoints for fetching campaign lists and basic metadata, then combine with cached reporting data. The dashboard should display a summary metrics bar at the top with total impressions, clicks, spend, and conversions. Below this, show a table of campaigns with sortable columns. Add a date range selector defaulting to the last 30 days. For visual impact, include a spend vs. conversions scatter chart to help users visually identify campaigns with strong conversion efficiency.

Lovable Prompt

Build a Microsoft Advertising dashboard that calls my bing-ads-api Edge Function. Fetch campaign performance data for the last 30 days including impressions, clicks, CTR, average CPC, total spend, conversions, and CPA per campaign. Show summary totals in cards at the top. Display all campaigns in a sortable table. Add a date range selector and a refresh button. Show a loading state while the report is being fetched. Display a scatter chart with spend on X axis and conversions on Y axis, one dot per campaign.

Paste this in Lovable chat

Pro tip: Microsoft Advertising's report data has a processing delay of a few hours for recent data. Cache reporting results in your Supabase database to avoid repeated slow report generation — re-fetch only for new date ranges or when manually refreshed.

Expected result: A Microsoft Advertising dashboard displays campaign performance metrics with sortable tables, summary cards, and a scatter chart visualization.

Common use cases

Bing search campaign performance dashboard

Display key performance indicators for all Microsoft Advertising search campaigns including impressions, clicks, average CPC, total spend, and conversion rate. Filter by date range and campaign status, and show week-over-week performance comparisons to track whether campaigns are improving.

Lovable Prompt

Build a Microsoft Advertising campaign dashboard that calls my bing-ads-api Edge Function. Fetch campaign performance report for the last 30 days with metrics: impressions, clicks, CTR, average CPC, spend, conversions, and conversion rate. Show summary cards at the top with totals, then a sortable table with one row per campaign. Add a date range selector. Show campaigns sorted by spend descending. Color-code CTR column: above 3% green, below 1% red.

Copy this prompt to try it in Lovable

Cross-channel search advertising comparison

Show Microsoft Advertising performance data alongside equivalent Google Ads metrics in a side-by-side comparison view. Help media buyers understand the incremental reach and cost efficiency of running on both search networks, making the case for or against Microsoft Advertising budget allocation.

Lovable Prompt

Create a cross-channel search comparison page. On the left show Microsoft Advertising totals (impressions, clicks, spend, conversions, CPA) from my bing-ads-api Edge Function. On the right show the same metrics from my google-ads-api Edge Function. Use the same 30-day date range for both. Add percentage difference badges showing which channel performs better for each metric.

Copy this prompt to try it in Lovable

Keyword performance and quality score tracker

Analyze keyword-level performance from Microsoft Advertising to identify high-performing keywords to bid up and poor-performing keywords to pause or adjust. Show quality score, expected CTR, and landing page relevance alongside traditional performance metrics.

Lovable Prompt

Build a keyword performance tracker that fetches keyword report data from my bing-ads-api Edge Function for the last 30 days. Show keyword text, match type, quality score, impressions, clicks, CTR, average CPC, conversions, and CPA in a table. Add filters for match type and minimum impressions threshold. Sort by CPA ascending to show most efficient keywords first. Highlight keywords with quality score below 5 in orange.

Copy this prompt to try it in Lovable

Troubleshooting

Token refresh fails with 'invalid_client' error despite correct client ID and secret

Cause: The Azure AD application may not be configured to use 'Accounts in any organizational directory and personal Microsoft accounts' (common authority), or the client secret has expired.

Solution: In Azure portal → App registrations → your app → Authentication, verify the supported account types include personal Microsoft accounts. Check Certificates & secrets to confirm the secret has not expired — Azure AD secrets have configurable expiry (1 year, 2 years, or custom). Create a new secret if needed and update MSADS_CLIENT_SECRET in Cloud Secrets.

API calls return 'AuthenticationTokenExpired' or 401 errors even after the token refresh logic runs

Cause: The refresh token stored in MSADS_REFRESH_TOKEN has been invalidated, which happens when the user revokes consent, the application is modified in Azure AD, or the refresh token has been unused for 90 days.

Solution: Re-run the OAuth2 authorization flow to generate a new refresh token. Open the Microsoft authorization URL with your app credentials in a browser, complete the login and consent flow, and capture the new authorization code from the redirect URL. Exchange it for new tokens at the Microsoft token endpoint and update MSADS_REFRESH_TOKEN in Cloud Secrets.

The Reporting Service returns a report request ID but the report never shows status 'Success' when polling

Cause: Report generation can take several minutes for large date ranges or accounts with many campaigns. The polling timeout in the Edge Function may be too short, or the account has no data for the requested date range.

Solution: Increase the polling timeout to at least 120 seconds for production accounts. Add logic to check if the report is still in 'Pending' or 'InProgress' status and continue waiting. For the initial test, request a narrow date range (last 7 days) and a small number of columns to ensure report generation is fast.

The DeveloperToken header returns a 'Your developer token does not have production access' error

Cause: The developer token in MSADS_DEVELOPER_TOKEN is a sandbox token that can only be used against the Microsoft Advertising sandbox environment, not the production API endpoint.

Solution: Wait for Microsoft to approve your production developer token application, which typically takes 1-3 business days after submission. In the meantime, test against the Microsoft Advertising sandbox environment by changing the API base URL to the sandbox endpoint. Once approved, replace the MSADS_DEVELOPER_TOKEN secret value with the production token.

Best practices

  • Cache the OAuth2 access token in module-level state in your Edge Function with a 55-minute TTL to avoid redundant token refresh calls on every API request
  • Store all five Microsoft Advertising credentials — client ID, client secret, refresh token, developer token, and account ID — in Cloud Secrets and never hardcode any value in function code
  • Use the Microsoft Advertising sandbox environment for development and testing before connecting your production account, preventing accidental campaign changes
  • Add report caching in your Supabase database since Microsoft Advertising report generation is slow — store reports with a timestamp and only regenerate when the cache is more than 2 hours old or a new date range is requested
  • Request only the metric columns you actually display in your dashboard — Microsoft Advertising reports get slower as you add more columns, and unused data wastes processing time
  • For agencies managing multiple Microsoft Advertising accounts, store credentials per client in your Supabase database and use the CustomerAccountId header dynamically to query the correct account
  • Monitor your developer token usage in Microsoft Advertising API Center — excessive API calls can trigger throttling and in severe cases revocation of API access

Alternatives

Frequently asked questions

Do I need to apply for a developer token to use the Microsoft Advertising API?

Yes, every application that calls the Microsoft Advertising API requires a developer token. You apply for one in Microsoft Advertising under Tools → API Center. You receive a sandbox token immediately for testing, but the production token requires a review process that typically takes 1-3 business days. The developer token is separate from and in addition to the OAuth2 credentials from Azure AD.

Can I use the same Microsoft Advertising Edge Function to manage agency accounts for multiple clients?

Yes, if you manage a Microsoft Advertising agency account, you can query different client accounts by changing the CustomerAccountId header in your API requests. Store the agency account credentials once in Cloud Secrets and pass the specific client account ID as a parameter to your Edge Function. The customer ID (different from account ID) may also be needed for agency-level operations.

Why does the Microsoft Advertising Reporting Service use an asynchronous pattern instead of returning data immediately?

Microsoft Advertising reports can be very large — accounts with thousands of keywords and long date ranges generate millions of rows. The asynchronous pattern lets Microsoft pre-generate the report on their servers and let you download it when ready, rather than blocking your API call for potentially several minutes. For simple use cases, the Bulk Service API provides some synchronous data options.

Does Lovable support Microsoft Advertising as a native connector?

Microsoft Advertising is not one of Lovable's 17 native shared connectors. Integration requires manually creating Edge Functions that handle OAuth2 token management and API proxying, as described in this guide. This approach gives you full control over the data you fetch and display, at the cost of more initial setup compared to native connectors.

How do I access Microsoft Advertising's audience network data (MSN, Outlook ads) through the API?

Audience network campaigns are accessible through the same Microsoft Advertising API as search campaigns. When querying reports, specify AudienceAds as the campaign type filter. The Reporting Service supports audience-specific metrics like view-through conversions alongside standard click metrics. Set up a separate reporting query for audience campaigns versus search campaigns to compare performance across Microsoft's network types.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.