Get Started with Bing Ads API – Setup for Authentication with OAuth

Get Started with Microsoft Advertising API – OAuth Authentication Setup | First API call (Formerly Bing Ads)

How to generate Microsoft Developer Token? How to set up/register an app in Microsoft Azure – for generating access token and refresh token?

Hi Everyone, Hope you are doing well. This article will walk you through the steps to set up a developer account and get started with Bing Ads API (currently known as Microsoft Advertising API).

Microsoft- Bing Ads API

Digital Advertisement is a must nowadays and some advertising platform is the giants of this world. One of them is Microsoft Advertising. This platform works on a pay-per-click (PPC) advertising modal and used to display ads based on the keywords used in a user’s search query on Bing and Yahoo! search engines.

Microsoft Advertising API provides a programmatic interface to Microsoft Advertising insights and is used by advertisers placing a large number of ads or developers building advertising tools. Using the Microsoft Advertising API is the most efficient way to manage many large campaigns or to integrate your marketing with other in-house systems. And the best thing is one can write your Microsoft Advertising API application in any language that supports web services.

Steps you need to go through to get started with Microsoft Advertising API:

Since you now have basic background understanding. Let’s get Started

1. Sign UP and get Microsoft Developer Token:

Here we are going to sign up for a Microsoft Advertising production account and with the same credentials get a developer token.

To get a developer token for production, follow these steps.

  1. Sign in with Super Admin credentials at the Microsoft Advertising Developer Portal account tab.
  2. Choose the user that you want associated with the developer token. Typically an application only needs one universal token regardless of how many users will be supported.
  3. Click on the Request Token button.

You should see a Developer Token now, mostly on the same screen. Store it in a safe place, I recommend creating a JSON file to store all credentials.

2. Register/Create an APP in Azure:

Now let’s do the second most important steps. Register a native app in the Azure portal – App registrations page. 

For this, you can log in using either a personal Microsoft Account or a Work or School Account. For details see Register Your Application.

Create a Application by clicking on “New Registration”.

Type in an application name, in my case it is “Demo MS App”. Be mindful while selecting the option from the “Support accounts types” Tab and click on “Register”. I’m going to select the 3rd option shown below.

After successfully registering the app, you will see all the cred – like client id, client secret, etc.

Note down all these credentials. Again I recommend storing credentials in a JSON file. This will help in for easy management and easy maintenance ( updates/rectification).

3. Getting Access Token and Refresh Token:

Here comes the most awaited part of this article, generating Access Token and Refresh Token programmatically.

Why do we need it? Each Microsoft Advertising user must grant consent for your application to access their accounts. 

In this quick start, effectively you will need to grant your own application permission to access your own Microsoft Advertising account via the following Get-Tokens-Production.ps1 PowerShell script. 

Open Notepad or your favorite editor. And as I always say understand and copy the below PowerShell script to the editor. 

Set $clientId to the Application Id of your registered app. If you registered a web application with client secret, then you’ll also need to include $client_secret=YourWebAppClientSecret when requesting the access tokens.

# Replace the Tutorial Sample App ID with your registered application ID. 
$clientId = "replace With Client ID"
 
Start-Process "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=$clientId&scope=openid%20profile%20https://ads.microsoft.com/ads.manage%20offline_access&response_type=code&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient&state=ClientStateGoesHere&prompt=login"
 
$code = Read-Host "Grant consent in the browser, and then enter the code here (see ?code=UseThisCode&...)"
 
# Get the initial access and refresh tokens. 
 
$response = Invoke-WebRequest https://login.microsoftonline.com/common/oauth2/v2.0/token -ContentType application/x-www-form-urlencoded -Method POST -Body "client_id=$clientId&scope=https://ads.microsoft.com/ads.manage%20offline_access&code=$code&grant_type=authorization_code&redirect_uri=https%3A%2F%2Flogin.microsoftonline.com%2Fcommon%2Foauth2%2Fnativeclient"
 
$oauthTokens = ($response.Content | ConvertFrom-Json)  
Write-Output "Access token: " $oauthTokens.access_token  
Write-Output "Access token expires in: " $oauthTokens.expires_in  
Write-Output "Refresh token: " $oauthTokens.refresh_token 
 
# The access token will expire e.g., after one hour. 
# Use the refresh token to get new access and refresh tokens. 
 
$response = Invoke-WebRequest https://login.microsoftonline.com/common/oauth2/v2.0/token -ContentType application/x-www-form-urlencoded -Method POST -Body "client_id=$clientId&scope=https://ads.microsoft.com/ads.manage%20offline_access&code=$code&grant_type=refresh_token&refresh_token=$($oauthTokens.refresh_token)"
 
$oauthTokens = ($response.Content | ConvertFrom-Json)  
Write-Output "Access token: " $oauthTokens.access_token  
Write-Output "Access token expires in: " $oauthTokens.expires_in  
Write-Output "Refresh token: " $oauthTokens.refresh_token

Save the file and name to Get-Tokens-Production.ps1 (you can name it anything you want but the extension must be .ps1).

Some extra Information better to know. To programmatically manage a Microsoft Advertising account, you must provide consent at least once through the web application consent flow. Thereafter you can use the latest refresh token to request new access and refresh tokens without any further user interaction.

Now to run Get-Tokens-Production.ps1 open a console window. At the command prompt, navigate to the folder where you saved Get-Tokens-Production.ps1 and enter the following command:

powershell.exe -File .\Get-Tokens-Production.ps1

When the PowerShell script successfully runs, it starts a browser session where you enter your Microsoft Advertising credentials. After consenting, the browser’s address bar contains the grant code (see ?code=UseThisCode&…). For eg:-https://login.microsoftonline.com/common/oauth2/nativeclient?code=M7ab570e5-a1c0-32e5-a946-e490c82954

Copy the grant code (the code you get by running the above file, not M7ab570e5-a1c0-32e5-a946-e490c82954) and enter it in the console window at the prompt. 

The PowerShell script then returns the access and refresh tokens. The script also has logic to make a second call to Invoke-WebRequest as an example of how to refresh the tokens. 

Remember all these credentials are very important, especially refresh tokens. You should treat them like you would a password. If someone gets hold of it, they have access to your resources. 

The refresh token is long-lived but it can become invalid. If you ever receive an invalid_grant error, your refresh token is no longer valid and you’ll need to run the Get-Tokens-Production.ps1 PowerShell script again to get user consent and a new refresh token.

I know many of you will be looking for python code for the above process. I will be coming up with it soon. Till then you can use the above one.

4. Using Access Token – First API Call:

Last part, but don’t ignore it. Testing all the credentials we got till now. Here we need to create a new file and paste into it the following script. Here set the AccessToken to the value you received from Get-Tokens-Production.ps1 and set $developerToken to the developer token you received from Step 1 above.

$accessToken = "Replace with Access Token You got";
$developerToken = "Replace with Developer Token You have";
 
[xml]$getUserRequest = 
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v13="https://bingads.microsoft.com/Customer/v13">
<soapenv:Header>
   <v13:DeveloperToken>{0}</v13:DeveloperToken>
   <v13:AuthenticationToken>{1}</v13:AuthenticationToken>
</soapenv:Header>
<soapenv:Body>
   <v13:GetUserRequest>
      <v13:UserId xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
   </v13:GetUserRequest>
</soapenv:Body>
</soapenv:Envelope>' -f $developerToken, $accessToken
 
$headers = @{"SOAPAction" = "GetUser"}
 
$uri = "https://clientcenter.api.bingads.microsoft.com/Api/CustomerManagement/v13/CustomerManagementService.svc"
$response = Invoke-WebRequest $uri -Method post -ContentType 'text/xml' -Body $getUserRequest -Headers $headers
Write-Output $response.Content

Save the file and name it Get-User.ps1 (you can name it anything you want but the extension must be .ps1).

Now to run Get-User.ps1 open a console window. At the command prompt, navigate to the folder where you saved Get-User.ps1 and enter the following command:

powershell.exe -File .\Get-User.ps1

When the PowerShell script successfully runs it should print out the details of your Microsoft Advertising user, including customer roles.

Congratulation! now you can use all the above credentials to build Microsoft Advertising API applications. You can make different API calls to extract data from Bing using access token and refresh token.

Since you have set up Microsoft Advertising and generated all credentials needed for Authentication with OAuth. The next thing that comes to mind is how to use them?

Here’s a guide to help you develop a complete Python code for OAuth Authentication and extracting data from Microsoft Advertising Account (Bing Ads) using Microsoft Advertising API. Check out other API Set-Up Guide.

For any suggestions or doubts ~ Get In Touch

Leave a Reply

Your email address will not be published. Required fields are marked *