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 […]
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.
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.
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:
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.
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.
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}
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}
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.
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.
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
Navigate to your Project Overview and select the </> icon to initiate the setup for your app on the web.
Follow the on-screen instructions to configure your app for web integration.
Ensure you have Firebase set up in your project.
Follow the prompts to configure your Firestore database, including setting up security rules.
This collection will serve as a secure repository for your access tokens.
To ensure your Instagram integration remains seamless, set up a cron job for automatic token renewal. Follow these steps to implement the cron API:
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.
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!
Hear what our customers have to say about our services and how we helped them succeed.
Have a project in mind or need expert guidance? We're here to help you turn your ideas into reality.
Have a project in mind or need expert guidance? We're here to help you turn your ideas into reality.