How to Get Microsoft Advertising Account ID?

How to Get Microsoft Advertising Account details?

In order to get Microsoft Advertising (Formerly Bing Ads) account details, especially the account ID, there are 2 ways. First directly getting it from Microsoft advertising account dashboard, second using python code and Microsoft Advertising API to get account ID along with rest of account details.

Let’s get started.

Method1~ Getting Account ID from MS Account:


First login to Microsoft Ads. On successful login, you will land upon the Microsoft Advertising dashboard. Next look at the URL.

The URL will look something like this -> (https://ui.ads.microsoft.com/campaign/vnext/overview?cid=251775011&aid=141346428&uid=98297581)

The account Id is the value of parameter aid. In our URL example account Id – aid = 141346428.

Method2~ Python code to retrieve Microsoft Advertising Account ID:

In this method, we will be building python logic to get Microsoft Account ID along with other Details (like location, currency, etc). Python code will be using Microsoft Advertising API calls. Hence it’s important you have completed the Microsoft Advertising API setup steps and you have all the tokes to create below credential file.

2.1- Create JSON file to store Tokens:

Before requesting the Microsft Advertising Account details using Microsoft Advertising API we need to OAuth authentication ourselves. To do this easy we will be creating a JSON file, which will store all authentication-related credentials -like Client ID, Client Secret, Access Token, Refresh Token, and Developer Token.

Creating a JSON file to store credentials makes it easy to maintain, update and track credentials as needed. This practice also provides security to your credentials from other team members or one can easily exclude this file from keeping it in public reposirty.

Proceed by saving below JSON as “ms_ads_cred.json”.

{
   "client_id":"Replace with Client ID",
   "access_token":"Replace with Access Token ",
   "refresh_token":"Replace with Refresh Token",
   "developer_token" :"Replace with Developer Token",
   "client_secret" : "Replace with Client Secret"
}

2.2- Python Logic for OAuth Authentication :

In this step, we are going to create a python module with a function to carry out the process of Oauth Authentication using the above credentials. Save the below code as “ms_authentication.py”.

#!/usr/local/bin/python3
import sys
from bingads.authorization import *
from bingads.service_client import ServiceClient
 
def ms_auth(refresh_token,client_id,client_secrect,developer_token):
    try:
        authorization_data=AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=developer_token,
        authentication=None,
        )
        authentication=OAuthDesktopMobileAuthCodeGrant(
        client_id=client_id,
        env='production'
        )
 
        authentication.state='[email protected]_amp'
        authentication.client_secret=client_secrect
        # Assign this authentication instance to the authorization_data. 
        authorization_data.authentication=authentication  
 
        authorization_data.authentication.request_oauth_tokens_by_refresh_token(refresh_token)
 
        print("MS_AUTHENTICATION: authentication process finished successfully\n")
        
        return authorization_data
    except:
        print("\nMS_AUTHENTICATION: authentication process Failed : ",sys.exc_info())
 

2.3- Building Python Logic to get Account ID :

Here first we are going to read the credentials from the above JSON file (line number: 83 – 90). Next, we are going to import the above authentication module (line number: 8) followed by calling its function for authenticating ourselves (line number: 93) so that we can make an API call to get Microsft Advertising Account details along with Account ID. (line number: 95)

Consider going through the code, and try to get a basic understanding of what’s going on. Don’t forget to save the code file as “ms_ads_accounts.py”.

#!/usr/local/bin/python3
# command to run this code $ python3 ./source/ms_ads_accounts.py
import getopt
import sys
import os.path
import json
from datetime import datetime, timedelta
from ms_authentication import *
 
from bingads.service_client import ServiceClient
 
def get_account(authorization_data):
    try:
        customer_service=ServiceClient(
        service='CustomerManagementService', 
        version=13,
        authorization_data=authorization_data, 
        environment='production',
        )
 
        user=get_user_response=customer_service.GetUser(
            UserId=None
        ).User
 
        accounts=search_accounts_by_user_id(customer_service,user.Id)
        #authorization_data.account_id=accounts['AdvertiserAccount'][0].Id
        #authorization_data.customer_id=accounts['AdvertiserAccount'][0].ParentCustomerId
        return accounts
    except:
        print("\nBING_GET_ACCOUNT : process Failed %s ",sys.exc_info())
 
def set_elements_to_none(suds_object):
    
    for (element) in suds_object:
        suds_object.__setitem__(element[0], None)
    return suds_object
 
def search_accounts_by_user_id(customer_service, user_id):
 
    predicates={
        'Predicate': [
            {
                'Field': 'UserId',
                'Operator': 'Equals',
                'Value': user_id,
            },
        ]
    }
 
    accounts=[]
 
    page_index = 0
    PAGE_SIZE=100
    found_last_page = False
 
    while (not found_last_page):
        paging=set_elements_to_none(customer_service.factory.create('ns5:Paging'))
        paging.Index=page_index
        paging.Size=PAGE_SIZE
        search_accounts_response = customer_service.SearchAccounts(
            PageInfo=paging,
            Predicates=predicates
        )
        
        if search_accounts_response is not None and hasattr(search_accounts_response, 'AdvertiserAccount'):
            accounts.extend(search_accounts_response['AdvertiserAccount'])
            found_last_page = PAGE_SIZE > len(search_accounts_response['AdvertiserAccount'])
            page_index += 1
        else:
            found_last_page=True
    
    return {
        'AdvertiserAccount': accounts
    }
 
if __name__ == '__main__':
    try:
        timestamp = datetime.strftime(datetime.now(),'%Y-%m-%d : %H:%M')
        print("DATE : ",timestamp,"\n")
        print("Microsoft Advertising data extraction process Starts")
 
        #loading and reading crdentials from JSON file.
        ms_cred_file = "./ms_ads_cred.json"
        ms_cred= open(ms_cred_file, 'r')
        cred_json = json.load(ms_cred)
        client_id = cred_json["client_id"]
        client_secret = cred_json["client_secret"]
        developer_token = cred_json["developer_token"]
        access_secret = cred_json["access_token"]
        refresh_token = cred_json["refresh_token"]
 
        #call authentication function
        authorization_data = ms_auth(refresh_token,client_id,client_secret,developer_token)

        accounts = get_account(authorization_data)
        print("\nMicrosoft Advertising Account Details : ",accounts)
        account_id = accounts['AdvertiserAccount'][0].Id
        print("\nMicrosoft Advertising Account ID : ",account_id)
 
        print("MICROSOFT_ADVERTISING_MAIN : data extraction Process Finished \n")
    except:
        print("\n*** MICROSOFT_ADVERTISING_MAIN : data extraction processing Failed !!!!:", sys.exc_info())
 

Run above file with command -> python3 ./ms_ads_accounts.py

You see output giving you Account Details along with Account ID (that’s important).

Hope I was able to explain both the method of getting Microsoft Advertising Account Id simple enough, especially to get the Account Id by building a python code using Microsoft Advertising API.

If you have any questions or comments feel free to reach me at ->

Leave a Reply

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