Categories
Facebook Web Development

How To Get All Ad Accounts in a Business via Facebook JavaScript SDK

Want to Support Me?
Get two free stocks valued up to $1,850 when you open a new Webull investment account through my referral link and fund the account with at least $100!

Have you ever needed to grab every ad account accessible to your Facebook Business account via the Facebook SDK for JavaScript? I will go through the process in this post!

Overview

There are two kinds of ad accounts your Business has access to:

  1. Ad accounts your Business owns
  2. Ad accounts shared to your Business

We want to view all these ad accounts via JavaScript, but we’ll start with the curl examples from the Facebook SDK documentation, then we’ll move to JavaScript code examples later.

Ad Accounts Owned by Your Business

Let’s first discuss how to get all ad accounts you own. There are a few documentation articles you can read in reference to the owned_ad_accounts edge:

curl -G \
-d "access_token=[ACCESS_TOKEN]" \
"https://graph.facebook.com/[API_VERSION]/[BUSINESS_ID]/owned_ad_accounts"

If you have made a request to gain ownership of an ad account, you can view those pending requests by making this call:

curl -G \
-d "access_token=[ACCESS_TOKEN]" \
"https://graph.facebook.com/[API_VERSION]/[BUSINESS_ID]/pending_owned_ad_accounts"

Ad Accounts Shared to Your Business

Next, let’s get access to ad accounts that have been shared to your business by a client, but you don’t own. Here are the related documentation articles:

curl -G \
-d "access_token=[ACCESS_TOKEN]" \
"https://graph.facebook.com/[API_VERSION]/[BUSINESS_ID]/client_ad_accounts"

JavaScript Code Example

Now let’s take this knowledge and turn it into JavaScript you can use on your site.

Let’s start by including a Facebook login button:

<fb:login-button size="large" scope="ads_read,business_management" returnscopes="true" onlogin="checkLoginState();">Login to Facebook</fb:login-button>

That gives us a login button that requests the necessary scopes, so we can read ad accounts.

Let’s also include a couple unordered lists, and we’ll fill them with the projects and ad accounts:

<ul id="owned-ad-accounts"></ul>
<ul id="shared-ad-accounts"></ul>

Next, here’s the most important part: the JavaScript! I’ll include it, then we can discuss the parts after.

(function(window) {
    var myAppId = 'YOUR_APP_ID_HERE';
    var businessId = 'YOUR_BUSINESS_ID_HERE';

    window.checkLoginState = function() {
        FB.getLoginStatus(function(response) {
            window.statusChangeCallback(response);
        });
    };

    window.statusChangeCallback = function(response) {
        console.log('running statusChangeCallback. received response: ', response);

        if (response.status === 'connected') {
            //owned ad accounts
            FB.api('/' + businessId + '/owned_ad_accounts', 'get', { fields: "id,name" }, function(response) {
                console.log('Owned:', response);
                if (!response || !response.data) return;
                for (var i = 0, len = response.data.length; i &lt; len; i++) {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(response.data[i].name));
                    document.getElementById('owned-ad-accounts').appendChild(li);
                }
            });

            //owned ad accounts
            FB.api('/' + businessId + '/client_ad_accounts', 'get', { fields: "id,name" }, function(response) {
                console.log('Shared:', response);
                if (!response || !response.data) return;
                for (var i = 0, len = response.data.length; i &lt; len; i++) {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(response.data[i].name));
                    document.getElementById('shared-ad-accounts').appendChild(li);
                }
            });
        }
        else {
            console.log("not logged in");
        }
    };

    window.fbAsyncInit = function() {
        //FB JavaScript SDK configuration and setup
        FB.init({
            appId: myAppId, //FB App ID
            cookie: true,  //enable cookies to allow the server to access the session
            xfbml: true,  //parse social plugins on this page
            version: 'v3.2' //use graph api version 3.2
        });

        //immediately go ahead and check whether the user already logged in
        FB.getLoginStatus(function(response) {
            window.statusChangeCallback(response);
        });
    };

    //Load the JavaScript SDK asynchronously
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
})(window);

You’ll need to input your Facebook App ID and Business ID in the top two variables to start.

When the SDK loads on your site, the SDK calls the window.fbAsyncInit function you define. In it, you need to first init your app. I am also checking to see if the user is already logged into your app, and if so, I go ahead and start off the process to get your Business’ ad accounts. You can disable that if you want by simply removing the FB.getLoginStatus call from within the window.fbAsyncInit function.

Whenever the user gets logged into your app, you’ll need it to call the statusChangeCallback function and pass in the authorization response that the SDK passed you.

Note that I am logging some information into the console, so you can see what’s going on. I would advise you to open up the DevTools console while you’re testing.

Get Owned Ad Accounts

We start out by making the API call to get all owned ad accounts:

FB.api('/' + businessId + '/owned_ad_accounts', 'get', { fields: "id,name" }, function (response) { }

We are requesting the id and name fields for each ad account. Once the call completes, it executes the callback function we gave it in the last parameter. In that callback function included in the big example above, we loop through response.data, get the name for each ad account, and add it as an li to the owned ad accounts ul.

Get Client Ad Accounts

Next, we make the API call to get all client ad accounts shared to your Business:

FB.api('/' + businessId + '/client_ad_accounts', 'get', { fields: "id,name" }, function (response) { }

Once we get back the ad accounts, we loop through them in the same way as above.

Your Turn!

Did this tutorial help you? Do you still have questions remaining after reading this post? Let’s discuss in the comments below!

Want to Support Me?
Get two free stocks valued up to $1,850 when you open a new Webull investment account through my referral link and fund the account with at least $100!