# How to Integrate Lovable with Microsoft Advertising (Bing Ads)

- Tool: Lovable
- Difficulty: Intermediate
- Time required: 90 minutes
- Last updated: March 2026

## 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.

## Before you start

- 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.

**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.

**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.

```
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

let tokenCache: { token: string; expiry: number } | null = null;

async function getAccessToken(): Promise<string> {
  if (tokenCache && Date.now() < tokenCache.expiry) return tokenCache.token;

  const response = await fetch(
    "https://login.microsoftonline.com/common/oauth2/v2.0/token",
    {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        grant_type: "refresh_token",
        client_id: Deno.env.get("MSADS_CLIENT_ID")!,
        client_secret: Deno.env.get("MSADS_CLIENT_SECRET")!,
        refresh_token: Deno.env.get("MSADS_REFRESH_TOKEN")!,
        scope: "https://ads.microsoft.com/msads.manage offline_access",
      }),
    }
  );

  const data = await response.json();
  if (!data.access_token) throw new Error(data.error_description || "Token refresh failed");

  tokenCache = {
    token: data.access_token,
    expiry: Date.now() + 55 * 60 * 1000,
  };
  return tokenCache.token;
}

serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

  try {
    const accessToken = await getAccessToken();
    const developerToken = Deno.env.get("MSADS_DEVELOPER_TOKEN")!;
    const accountId = Deno.env.get("MSADS_ACCOUNT_ID")!;

    const { path, method = "GET", body: reqBody } = await req.json();
    if (!path) throw new Error("path is required");

    const url = `https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/V13/${path}`;

    const fetchOptions: RequestInit = {
      method,
      headers: {
        "AuthenticationToken": `Bearer ${accessToken}`,
        "DeveloperToken": developerToken,
        "CustomerAccountId": accountId,
        "Content-Type": "application/json",
      },
    };

    if (reqBody && method !== "GET") {
      fetchOptions.body = JSON.stringify(reqBody);
    }

    const response = await fetch(url, fetchOptions);
    const data = await response.json();

    if (!response.ok) throw new Error(JSON.stringify(data));

    return new Response(JSON.stringify(data), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (error) {
    return new Response(
      JSON.stringify({ error: error.message }),
      { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
```

**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.

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

## 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

## 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.

Prompt example:

```
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.
```

### 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.

Prompt example:

```
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.
```

### 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.

Prompt example:

```
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.
```

## 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.

## 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.

---

Source: https://www.rapidevelopers.com/lovable-integration/bing-ads
© RapidDev — https://www.rapidevelopers.com/lovable-integration/bing-ads
