How to display an Instagram user's followers in a text box?

Question:
How can I use the Instagram API to display a user’s follower count on my website?

Product:
Velo in Wix Studio

What are you trying to achieve:
I want to have a text object on the page which displays the follower count of a given user’s Instagram account. The user will have to authorize via OAuth before this can be done.

What have you already tried:
I have tried using Velo (code attached below) to achieve the desired result, but with no results. What I did was create a backend file containing code to pull the temporary authorization code from the URL after the user approves the connection on Instagram. Then, the temporary authorization code is exchanged for a long-lived access token. I also created a frontend file which is supposed to make a request to the Instagram API using the long-lived access token that was acquired, and then update the text element on the page which the follower count that it retrieves. As far as I can tell neither of these scripts are working, and I cannot see any errors in the console log, nor any requests being made to Instagram via the network tab.

I have included the code I’m using (with sensitive information censored) in the additional information section of this post.

Additional information:
code for my backend file:

import { fetch } from 'wix-fetch';

export async function getAccessToken(code) {
  console.log(`Received authorization code: ${code}`);
  
  const response = await fetch('https://api.instagram.com/oauth/access_token', {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: `client_id=CLIENT_ID&client_secret=SECRET&grant_type=authorization_code&redirect_uri=REDIRECT_URI&code=${code}`
  });

  if (!response.ok) {
    const error = await response.text();
    console.error(`Error fetching access token: ${error}`);
    throw new Error(`Error fetching access token: ${error}`);
  }

  const result = await response.json();
  console.log(`Access token received: ${result.access_token}`);
  return result.access_token;
}

export async function getUserProfile(accessToken) {
  console.log(`Using access token to fetch user profile: ${accessToken}`);
  
  const response = await fetch(`https://graph.instagram.com/me?fields=id,username,account_type,media_count&access_token=${accessToken}`);

  if (!response.ok) {
    const error = await response.text();
    console.error(`Error fetching user profile: ${error}`);
    throw new Error(`Error fetching user profile: ${error}`);
  }

  const result = await response.json();
  console.log(`User profile received: ${JSON.stringify(result)}`);
  return result;
}

and here is the code for my frontend file:

import { getAccessToken, getUserProfile } from 'backend/instagram.jsw';

$w.onReady(function () {
  console.log("Running the dashboard.js script");

  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get('code');

  console.log(`Authorization code from URL: ${code}`);

  if (code) {
    getAccessToken(code)
      .then(accessToken => {
        console.log(`Access token: ${accessToken}`);
        return getUserProfile(accessToken);
      })
      .then(userProfile => {
        console.log(`User profile: ${JSON.stringify(userProfile)}`);
        $w('#followerCount').text = `Follower Count: ${userProfile.media_count}`;
      })
      .catch(error => {
        console.error(`Error fetching Instagram data: ${error.message}`);
        $w('#followerCount').text = 'Error fetching follower count.';
      });
  } else {
    console.log("No authorization code found in the URL");
  }

  // Redirect user to Instagram authorization URL on button click
  $w('#oauthButton').onClick(() => {
    const clientId = 'CLIENT_ID';
    const redirectUri = encodeURIComponent('MY_URI');
    const scope = 'user_profile,user_media';
    const responseType = 'code';
    const authUrl = `https://api.instagram.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=${responseType}`;
    console.log(`Redirecting to Instagram OAuth URL: ${authUrl}`);
    window.location.href = authUrl;
  });
});

and for those of you with a discerning eye, yes I used ChatGPT for much of the code. I am not a developer and would not call myself one, but I am trying to learn.

Hello Jacob,

Chat GPT is an amazing thing, right?! To be honest, the code is not wrong but you are missing some important steps. All in all, my (brief) response still ended up being an essay in length, but I do want to call out that you would have a better outcome doing this in a custom web application over Wix (because you can add the facebook SDK to your package.json). But if you want to try Wix, you can utilize the steps below as a guideline.

First off, have you reviewed Meta’s documentation regarding this API? I have built my own integrations with Meta and can tell you right away that your best bet is to follow their oAuth flow for their Graph APIThis text will be hidden. Here is a high level breakdown of what you would need to consider:

  1. An important thing to note is you need to create your own App inside of Facebook and obtain a Client ID and Client Secret. (You may have those in your secret manager but it is unclear to me). In addition, once you take your app to production you will need to list a series of scopes that your users need to accept in order for your access tokens to exchange with specific parts of the Meta API. The scopes in production need to go under app review (which is more complex than one may think since Meta is very strict with their app approvals- you will need to list how you are using the data/api scopes, provide demos, and access for a member of the meta team to personally review your application before being accepted.

  2. Once you have your FB App set up, no need to take it to production yet as you can test it locally with a test account/your own account. Only take it to production when it is working as needed. You would create a “login with facebook” oAuth workflow. See their documentation here. I recommend building this oAuth in an iFrame so you can at least try and add the JS SDK this way (no guarantee that this will work) – or you may need to add it into your site public file headers via your dashboard. Velo will not accept this SDK in the code panel and there is no NPM you can use in lieu of.

  3. If you are able to complete the oAuth workflow, your next step is to exchange the short lived access token for a refresh token. That way you can encrypt or store the token so they do not need to login again and can use this token repeatedly without any issues. Access tokens are considered sensitive data and you should not share these tokens under any circumstances. Especially if you have sensitive scopes enabled in your oAuth workflow. If you only want them to login with Facebook, see their follower count then have the token expire in ~1 hour then leave everything on the client side. Make sure this call is in your backend. The only client call being made is the “login with Facebook” flow.

  4. Once you have your token, you need to get their IG ID. More importantly, if their Facebook page is synced with their Facebook page, then this is easier to obtain. Their Instagram account also MUST BE A BUSINESS INSTAGRAM ACCOUNT – NO PERSONAL ACCOUNTS WILL HAVE ACCESS TO THIS ENDPOINT. You can get their IG ID by reviewing their documentation. I typically get the IG ID around the oAuth flow along with the Pages Show List scope.

  5. Now that you have a valid long token and IG ID you would use this fetch url to obtain the IG Business overview (including total followers and unfollowers). Again you 100% should review the documentation with this endpoint for query parameter customizations. You would not need all of the fields I listed for you…

let url = `https://graph.facebook.com/v19.0/${igId}?fields=username,name,profile_picture_url,followers_count,follows_count,biography,website,media_count,ig_id,id&access_token=${access_token}`

Again this a guideline, as you have some grinding to do but I hope it helps if any. I strongly recommend looking into wix apps before you try and do this yourself. If you are committed, skip wix– build a CRA or Next JS app and give it a go. If you do the latter, you can officially call yourself a web developer! :wink:

2 Likes