This guide will walk you through the process of setting up the Instagram API to fetch the latest posts and creating cron functions for automatic long-term access token updates.

Step 1: App Setup on Facebook Meta

Start by setting up your app on Facebook Meta. Fill in necessary details such as your app name and contact email. Choose “consumer” as your app type.

Step 2: Instagram Basic Display API Configuration

Find the Instagram Basic Display API on your dashboard and proceed with the setup. Let’s get started with these essential steps.

Select Instagram Graph Api from the Products in the Dashboard:

Step 3: Basic Display Configuration

Inside your Instagram Graph API’s Basic Display, add your website URL to Valid OAuth Redirect URIs, Deauthorize Callback URL, and Data Deletion Request URL.

  1. Click on “App Roles” in the left panel, then select “Roles.”
  2. Select “Add People” and choose “Instagram Tester.”

Step 4: Connecting Instagram Tester Account

Connect your Instagram Tester account to your Meta account through this link. Opt for “Tester Invites.”

Next paste this url into your browser:

https://api.instagram.com/oauth/authorize

?client_id={app-id}
&redirect_uri={redirect-uri}
&scope=user_profile,user_media
&response_type=code

Make sure to replace app-id with your app-id with your Instagram Basic Display app-id and the redirect-uri with the url of your website

Once you have obtained the URL, paste it onto your web browser address bar. You will then be redirected to the following screen to grant access to your Facebook app.

Once the permission is granted, you will be redirected to your provided URL with additional information.

Step 5: Obtaining Short-Term Access Token

Use the code provided in the URL below without the “#_” section:

https://jw-digital.co.uk/?code=accessToken

Now, open your terminal and paste the following curl command to retrieve your short-term access token:

curl -X POST \



https://api.instagram.com/oauth/access_token



\



-F client_id={client id}\



-F client_secret={client secret}\



-F grant_type=authorization_code \



-F redirect_uri={your website} \



-F code={your code}

Replace {yourCode}, with the code from the URL.

Your response will look something like this:

{"access_token": "access token will be here", "user_id": your user id will be here}

Step 6: Exchange for Long-Term Access Token

As the obtained token is short-term (1 hour), we need to exchange it for a long-term access token lasting 60 days. Run the following curl command in your terminal:

curl -i -X GET "https://graph.instagram.com/access_token

?grant_type=ig_exchange_token
&client_secret={yourClientSecret}
&access_token={yourAccessToken}"

Your response will include a long-term access token:

{"access_token":"{longTermAccessToken}","token_type":"bearer","expires_in":5184000}

Step 7: Using Long-Term Access Token

Now that we have our long-term access token, we can make API calls. Use the provided function as a hook in relevant components:

export async function useGetInstagramPosts(token) {

try {
const resp = await axios.get(
`https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,thumbnail_url,permalink,timestamp,username,like_count,comments_count,media_product_type,is_comment_enabled,children&limit=5&access_token=${token}`
);
return resp.data.data;
} catch (err) {
throw err;
}
}

Customize the fields section in the request URL based on the information you want to retrieve.

Step 7: Storing Long-Term Access Token in Firebase

To facilitate token refreshing, we’ll store the long-term access token in Firebase. This enables us to set up a cron function for automatic token renewal every month.

  1. Save the obtained long-term access token securely in your Firebase database.
  2. Set up a cron function to refresh the token monthly, ensuring uninterrupted API access.

This approach ensures your application maintains seamless connectivity to Instagram’s API over an extended period.

Go to https://console.firebase.google.com and add a new project.

Enter your project name


Step 8: Set Up Your App on the Web

Navigate to your Project Overview and select the </> icon to initiate the setup for your app on the web.

  1. Click on the project overview in your Firebase console.
  2. Look for the </> icon or any option related to setting up your app on the web.

Follow the on-screen instructions to configure your app for web integration.

Step 9: Set Up Firebase and Create Firestore Database

Ensure you have Firebase set up in your project.

  1. Click on “Build” in the Firebase console.
  2. Navigate to “Firestore Database.”
  3. Choose “Create Database.”

Follow the prompts to configure your Firestore database, including setting up security rules.

Step 10: Set Up Firestore Collection for Access Token

  1. Inside your Firestore Database, click on “Start Collection.”
  2. Name your collection, for example, “instagram.”
  3. Add a document within the collection.
  4. Create a field named “LongTerm” and store your long-term access token in this field.
  5. Configure additional fields as needed based on your application requirements.

This collection will serve as a secure repository for your access tokens.

Step 11: Automating Long-Term Access Token Refresh

To ensure your Instagram integration remains seamless, set up a cron job for automatic token renewal. Follow these steps to implement the cron API:

  1. Create a new file named cron.js in your API directory.
// api/cron.js


import axios from "axios";
import {
useGetInstagramToken,
useUpdateInstagramToken,
} from "../../hooks/hooks";

export default async function handler(req, res) {
const refreshTokenUrl = "https://graph.instagram.com/refresh_access_token";

try {
// Fetch the current long-term access token
const currentToken = await useGetInstagramToken();

// Make a request to refresh the token
const refreshResponse = await axios.post(refreshTokenUrl, {
grant_type: "ig_refresh_token",
access_token: currentToken.LongTerm,
});

// Extract the new access token from the response
const newToken = refreshResponse.data.access_token;

// Update the stored access token in Firestore
await useUpdateInstagramToken(newToken);

res.status(200).json({ message: "Cron job executed successfully" });
} catch (error) {
console.error("Error executing cron job:", error);
res.status(500).json({ error: "Internal Server Error" });
}
}

useGetInstagramToken hook:

export async function useGetInstagramToken() {

try {
const docRef = doc(db, "instagram", "key");
const docSnap = await getDoc(docRef);
return docSnap.data();
} catch (error) {
return error;
}
}

useUpdateInstagramToken hook:

export async function useUpdateInstagramToken(token) {

try {
const docRef = doc(db, "instagram", "key");
const docSnap = await updateDoc(docRef, {
LongTerm: token,
});
return docSnap.data();
} catch (error) {
return error;
}
}

This script fetches the current long-term access token, sends a request to refresh it, and updates the stored token in Firestore.

Schedule this cron job to run at intervals suitable for your application. You can use tools like cron or set up serverless functions in platforms like Vercel or Netlify.

Here is an example of a vercel.json file I have stored at the root of my project that runs my cron function at 08:00am of the 5th of every months

{

"crons": [
{
"path": "/api/cron",
"schedule": "0 8 5 * *"
}
]
}

Now, your application is equipped with an automated system to refresh the long-term access token, ensuring uninterrupted access to Instagram’s API.

Conclusion

Congratulations! You’ve successfully set up and automated the integration of the Instagram API in your application. By following these steps, you’ve established a robust system that fetches the latest posts and ensures uninterrupted access through the use of long-term access tokens.

Remember, staying connected with Instagram’s API requires a proactive approach. Utilizing cron jobs for automatic token renewal not only simplifies the process but also enhances the reliability of your application.

As technology evolves, always stay updated with the latest practices and guidelines provided by Instagram and Firebase. Feel free to explore additional features and functionalities offered by these platforms to further enhance your Instagram integration.

Thank you for joining us on this journey to streamline your Instagram API setup. If you have any questions or insights to share, feel free to leave a comment below.

Happy coding!

Leave a comment

Trending

Blog at WordPress.com.