How to generate Microsoft Developer Token? How to set up/register an app in Microsoft Azure – for generating access tokens and refresh tokens?
Hi, Hope you are doing well. Thank you so much for stopping by. It’s another day to learn something fruitful. To give you an idea of what we will be learning here. The guide will help you in creating a Microsoft Advertising developer account, creating Microsoft Azure App, enable API, and next, we will be generating tokens (access token, client id, etc) for OAuth Authentication through which we will be using Microsoft Advertising API (Bing Ads API) to get Microsoft Advertising Ads and Campaigns performance data.
What is Microsoft Advertising?
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 is used to display ads based on the keywords used in a user’s search query on Edge, Bing, and Yahoo! search engines.
What is Microsoft Advertising API (Bing Ads API)?
Microsoft Advertising API (i.e Bing Ads 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 (Bing Ads 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.
Resource for using Microsoft Advertising API :
Since you now have a 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.
- Sign in with Super Admin credentials at the Microsoft Advertising Developer Portal account tab.
- Choose the user that you want to be associated with the developer token. Typically an application only needs one universal token regardless of how many users will be supported.
- 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 crucial step. Register a native app in the Azure portal – App registrations page.
You can log in using either a personal Microsoft Account or a Work or School Account. For details see Register Your Application.
Create an 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 with easy management and maintenance ( updates/rectification).
If you want I can help you out with a python code to generate an access token and the entire process automated. Get in touch with me. This all can be done in 1 hour for you.
3. Getting Access Token and Refresh Token
The most awaited part of this article is 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 is 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 the logic to make a second call to Invoke-WebRequest as an example of how to restore 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
The 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 the 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.
Hope I was able to solve the problem. If you like this article and think it was easy to understand do share it with your friends and connection. Thank you! see you soon.
For any suggestions or doubts ~ Get In Touch
Checkout out my other API Integration and Coding Solution Guide