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.