"Invalid OAuth Access Token - Cannot Parse Access Token" Error when Creating Facebook Campaign using Facebook Ad API

375 Views Asked by At

I am trying to create a Facebook campaign using the Facebook Ad API in my Node.js application. However, I keep encountering the error "Invalid OAuth access token - Cannot parse access token" when attempting to create the campaign.

I have included the necessary fields such as the access token, app secret, app ID, ad account ID, and campaign ID. Despite passing these values correctly, I am unable to resolve the issue.Here is the relevant code snippet that pertains to the campaign creation: Campaign.js:


'use strict';
const bizSdk = require('facebook-nodejs-business-sdk');
const AdAccount = bizSdk.AdAccount;
const { AdsInsights, Campaign } = bizSdk;
const express = require('express');
const router = express.Router();

const access_token = '';
const app_secret = '<App secret>';
const app_id = '<app_Id>';
const showDebugingInfo = true; 
const ad_account_id = '<Ad_Account_Id>'; 
const campaign_id = '<YOUR_CAMPAIGN_ID>'; 
const api = bizSdk.FacebookAdsApi.init(access_token);

if (showDebugingInfo) {
  api.setDebug(true);
}

const logApiCallResult = (apiCallName, data) => {
  console.log(apiCallName);
  if (showDebugingInfo) {
    console.log('Data:' + JSON.stringify(data));
  }
};

router.get('/getcampaign', (req, res) => {
  const fields = [
    AdsInsights.Fields.impressions,
    AdsInsights.Fields.inlineLinkClicks,
    AdsInsights.Fields.spend,
  ];

  const params = {
    'time_range': {'since': 'yesterday', 'until': 'today'},
  };

  const campaign = new Campaign(campaign_id, ad_account_id);
  campaign.getInsights(fields, params)
    .then((insights) => {
      res.json(insights);
    })
    .catch((error) => {
      res.status(500).json({ error: error });
    });
});

router.post('/createcampaign', (req, res) => {
  const AdAccount = new bizSdk.AdAccount(ad_account_id);
  const campaign = new Campaign(null, ad_account_id);
  const campaignParams = {
    name: 'My Campaign', 
    objective: 'LINK_CLICKS', 
    status: 'PAUSED', 
    special_ad_categories: ['NONE'], 
  };

  AdAccount.createCampaign([], campaignParams, { access_token: access_token })
    .then((result) => {
      console.log('Campaign created successfully: ', result);
      res.json({ success: true, campaignId: result._data.id });
    })
    .catch((error) => {
      console.error('Error creating campaign: ', error);
      res.status(500).json({ error: error });
    });
});

router.post('/updatecampaign', (req, res) => {
  const campaign = new Campaign(campaign_id, ad_account_id);
  const campaignParams = {
    name: 'Updated Campaign Name', 
    status: 'PAUSED',
  };

  campaign
    .update(campaignParams)
    .then((result) => {
      console.log('Campaign updated successfully: ', result);
      res.json({ success: true });
    })
    .catch((error) => {
      console.error('Error updating campaign: ', error);
      res.status(500).json({ error: error });
    });
});

module.exports = router;

app.js:

const http = require("http")
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyparser = require('body-parser');
const facebookRoute = require('../Mediation/Service/FacebookAdService');
const campaignRoutes = require('./Campaign');
const adsetRoutes = require('./Adset');


app.use(morgan('dev'));
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
        return res.status(200).json({});
    }
    next();
});

app.use('/FacebookAdService', facebookRoute);
app.use('/', adsetRoutes);
app.use('/', campaignRoutes);
app.use((req, res, next) => {
    const error = new Error("Not Found");
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});

module.exports = app;


Here's the response i am getting in postman after i am passing the token in the header and passing the body:

{
    
  "id": "353365098746250",
  "name": "test campaign",
  "objective": "LINK_CLICKS",
  "status": "PAUSED",
  "special_ad_categories": ["NONE"]
}

The response i am getting:

{
    "error": {
        "name": "FacebookRequestError",
        "message": "Invalid OAuth access token - Cannot parse access token",
        "stack": "Error\n    at FacebookRequestError.FacebookError [as constructor] (D:\\Work\\Mediation\\node_modules\\facebook-nodejs-business-sdk\\dist\\cjs.js:349:16)\n    at new FacebookRequestError (D:\\Work\\Mediation\\node_modules\\facebook-nodejs-business-sdk\\dist\\cjs.js:371:129)\n    at D:\\Work\\Mediation\\node_modules\\facebook-nodejs-business-sdk\\dist\\cjs.js:674:15\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)",
        "status": 400,
        "response": {
            "message": "Invalid OAuth access token - Cannot parse access token",
            "type": "OAuthException",
            "code": 190,
            "fbtrace_id": "AVX0udiCC95QfUIH1ZR33Dk"
        },
        "headers": {
            "vary": "Origin",
            "access-control-allow-origin": "*",
            "content-type": "application/json",
            "www-authenticate": "OAuth \"Facebook Platform\" \"invalid_token\" \"Invalid OAuth access token - Cannot parse access token\"",
            "strict-transport-security": "max-age=15552000; preload",
            "pragma": "no-cache",
            "cache-control": "no-store",
            "expires": "Sat, 01 Jan 2000 00:00:00 GMT",
            "x-fb-request-id": "AVX0udiCC95QfUIH1ZR33Dk",
            "x-fb-trace-id": "AIVKNxkEDHh",
            "x-fb-rev": "1009526237",
            "x-fb-debug": "DEBurJXzasFL/gEcCZVr97F+HNa+Huqz7KW6qXF9EQxsRxUy97A5cQxmHGNWAQa1+ODwY/wa7m+W1QirkjjQDg==",
            "date": "Fri, 27 Oct 2023 10:54:37 GMT",
            "proxy-status": "http_request_error; e_clientaddr=\"AcIRXs3NId91_20G1RU7DBnxE8hlCHlzkZ7ioVmlDsuY8rSJSJliA1_N5tYJzfDWIL-s6uojcxK8JUgawA\"; e_fb_vipport=\"AcK-A9kQCHDVu2WeUUTR1zLySpH0ApNqj2d-_KduAggRtMRpeGCZTWBdereb\"; e_upip=\"AcKrXWXYTdRyWEO7rV2WjRz0pgdSZaPR-FNdiRH3LOKRzQuvJS-_c5oaTB-ojeBO7FELylvYetRAMs-lrRhH9bp0EIhsuGRlUg\"; e_fb_hostheader=\"AcJiEPQOpPUY1XutmWb5W6VKtYRtkGO4cW3CNZOGuKWw990wckTAdFWjjIhrSdpSq-bzGSWsqy7dK3jN\"; e_fb_vipaddr=\"AcKc5wNx4AhQ6MY1mfFXV8IcDAIX2LEjRYJwGVAOonO4ElVHNilWGtw4mmqorEgMo5dpEbAXyoE\"; e_fb_requesthandler=\"AcIKY4AjVqFnigXCwt3gT02vDgncdtkQYLBooURi-gYlzVPihc53QtiAjYnDuKqX-nC4WhYWMxI\"; e_fb_builduser=\"AcLChMilUMvwB1SrwgUddWV6dXyJ6gvTF-MerV69MWkybwjMSL6AgvSss6dCRhDavs4\"; e_fb_binaryversion=\"AcKXLNo1u3eSywrgTI_uWMlvoI_e1LxSsCfFIQSDVznYCXbBSnK0JFb57Zv27h5v9J9QNLrk_aauWgLWAlxNgUj9K7HYNr2UvuI\"; e_proxy=\"AcL5olnCd6aeWWDfv9UdNoHmoDZuiMQVDkzOvPs3MOaorQwfLS5vrNrKI-6dhE_JLxyACUgr6D7zO_Q2\"",
            "alt-svc": "h3=\":443\"; ma=86400",
            "connection": "keep-alive",
            "content-length": "152"
        },
        "method": "POST",
        "url": "https://graph.facebook.com/v18.0?access_token=%3CACCESS_TOKEN%3E",
        "data": {
            "name": "My Campaign",
            "objective": "LINK_CLICKS",
            "status": "PAUSED",
            "special_ad_categories": [
                "NONE"
            ],
            "id": "353365098746250"
        }
    }
}
I have verified that the access token is generated from Meta for developers and is being passed in the Authorization header.
I have checked that the app secret, app ID, ad account ID, and campaign ID are accurate and correctly passed to the API.

Any insights or suggestions on why this error is occurring and how to resolve it would be greatly appreciated. Thank you in advance for your help!

0

There are 0 best solutions below