0

I was using a Instagram basic api but it works only for limited accounts while using. I have created a new account and changed it to creator mode but still it was showing error that I have mentioned in the title. The problem was rising while exchanging the long lived token the short lived token is working fine. I have tried get method post method.

   this.baseUrl = 'https://graph.instagram.com';
    this.graphUrl = 'https://graph.facebook.com';
    this.apiVersion = 'v18.0';
    this.aiService = new AIService();
    this.auth = {
        getAccessToken: async (code, redirectUri) => {
            try {
                console.log('getAccessToken with code ', code, ' and redirectUri ', redirectUri);
                console.log('process.env.INSTAGRAM_APP_ID', process.env.INSTAGRAM_APP_ID);
                console.log('process.env.INSTAGRAM_APP_SECRET', process.env.INSTAGRAM_APP_SECRET);

                // First exchange the code for a short-lived token
                const response = await axios({
                    method: 'post',
                    url: 'https://api.instagram.com/oauth/access_token',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: new URLSearchParams({
                        client_id: process.env.INSTAGRAM_APP_ID,
                        client_secret: process.env.INSTAGRAM_APP_SECRET,
                        grant_type: 'authorization_code',
                        redirect_uri: redirectUri,
                        code: code
                    }).toString()
                });

                console.log('response from getAccessToken', response.data);
                return await this.auth.getLongLivedToken(response.data);
            } catch (error) {
                console.error('Error getting access token:', error);
                throw new Error('Failed to exchange Instagram code for token');
            }
        },

        getLongLivedToken: async (initialToken) => {
            try {
                // Ensure we have an object to work with
                let tokenData = initialToken;
                
                // If it's a string that looks like JSON, parse it
                if (typeof initialToken === 'string') {
                    try {
                        if (initialToken.startsWith('{')) {
                            tokenData = JSON.parse(initialToken);
                        }
                    } catch (e) {
                        console.log('Failed to parse token as JSON:', e.message);
                    }
                }

                const accessToken = typeof tokenData === 'object' ? tokenData.access_token : tokenData;
                const isBusinessToken = tokenData.permissions && 
                                     Array.isArray(tokenData.permissions) && 
                                     tokenData.permissions.some(p => p.startsWith('instagram_business_'));

                // For business accounts, use Facebook Graph API
                console.log(`${isBusinessToken ? 'Business' : 'Personal'} account detected, using ${isBusinessToken ? 'Facebook' : 'Instagram'} Graph API`);
                
                const endpoint = isBusinessToken ? 
                    `${this.graphUrl}/${this.apiVersion}/oauth/access_token` : 
                    `${this.baseUrl}/access_token`;

                const params = new URLSearchParams();
                if (isBusinessToken) {
                    params.append('grant_type', 'fb_exchange_token');
                    params.append('client_id', process.env.INSTAGRAM_APP_ID); // Use Instagram App ID
                    params.append('client_secret', process.env.INSTAGRAM_APP_SECRET); // Use Instagram App Secret
                    params.append('fb_exchange_token', accessToken);
                } else {
                    params.append('grant_type', 'ig_exchange_token');
                    params.append('client_secret', process.env.INSTAGRAM_APP_SECRET);
                    params.append('access_token', accessToken);
                }

                console.log('Token exchange params:', Object.fromEntries(params));

                // Exchange for long-lived token
                const response = await axios({
                    method: 'post',
                    url: endpoint,
                    data: params,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                });

                console.log('Token exchange response:', response.data);

                if (!response.data || !response.data.access_token) {
                    throw new Error('Invalid response from API');
                }

                // Get account details
                try {
                    const profileResponse = await axios({
                        method: 'get',
                        url: `${this.baseUrl}/me`,
                        params: {
                            fields: 'id,username,account_type',
                            access_token: response.data.access_token
                        }
                    });

                    return {
                        ...response.data,
                        token_type: 'LONG_LIVED_INSTAGRAM',
                        account_type: isBusinessToken ? 'business' : (profileResponse.data.account_type || 'personal'),
                        username: profileResponse.data.username,
                        user_id: profileResponse.data.id,
                        ...(isBusinessToken && { permissions: tokenData.permissions })
                    };
                } catch (profileError) {
                    console.log('Failed to get profile info:', profileError.message);
                    return {
                        ...response.data,
                        token_type: 'LONG_LIVED_INSTAGRAM',
                        account_type: isBusinessToken ? 'business' : 'personal',
                        user_id: tokenData.user_id,
                        ...(isBusinessToken && { permissions: tokenData.permissions })
                    };
                }
            } catch (error) {
                console.error('Token exchange failed:', {
                    message: error.message,
                    response: error.response?.data,
                    status: error.response?.status,
                    endpoint: error.config?.url,
                    method: error.config?.method,
                    params: error.config?.params
                });
                throw new Error(error.response?.data?.error?.message || error.message || 'Failed to exchange token');
            }
        },

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.