在Google Apps脚本中请求Facebook Graph API页面见解时访问令牌出现问题

时间:2019-06-30 19:17:53

标签: facebook facebook-graph-api google-apps-script

问题

我试图将信息从Facebook页面获取到Google Apps脚本中,以便在几个不同的项目中使用,并设法对用户进行身份验证,但是每当我尝试从Graph API检索某些数据时,会引发错误,说我应该使用页面访问令牌

[{"code":400,"body":"{\"error\":{\"message\":\"(#190) This method must be called with a Page Access Token\",\"type\":\"OAuthException\",\"code\":190,\"fbtrace_id\":\"AwSk6k26bAqpoYBJNk8bnQr\"}}"}]

调查

进行一些日志记录,我发现当我发出“我/帐户” 请求时,显示的访问令牌实际上不同于 getData 函数中使用的令牌,似乎是用户访问令牌,而不是第一页。在这一点上,我真的迷失了,一直在查看文档中的内容,以查看我可以做些什么,但是完全超出了我的能力,任何帮助将不胜感激。

代码示例

以下是Apps脚本项目中的代码。我已经对其进行了一些清理,因此您可以专注于此身份验证问题:

Code.gs

function getConfig(request) {
  var service = getService();
  var response = JSON.parse(UrlFetchApp.fetch('https://graph.facebook.com/v3.3/me/accounts', {
    headers: {
      Authorization: 'Bearer ' + service.getAccessToken()
    }
  }));
  var config = {
    configParams: [
      {
        type: 'SELECT_SINGLE',
        name: 'pageID',
        displayName: 'Page ID',
        helpText: 'Please select the Page ID for which you would like to retrieve the Statistics.',
        options: []
      }
    ],
    dateRangeRequired: true
  };
  response.data.forEach(function(field) {
    config.configParams[0].options.push({
      label: field.name,
      value: field.id
    });
  })
  return config;
};

// All good until here, gets everything right, the page and it's information




function getData(request) {
  var service = getService();

  // Define the interval wanted
  var dateStart = '2019-06-01';
  var dateFinish = '2019-06-15';

  // Set the information wanted: page fans and impressions
  var batch = [{'method': 'GET', 'relative_url': request.configParams.pageID + '/insights/page_fans,page_impressions?since=' + dateStart + '&until=' + dateFinish}];

  // Fetch the data with UrlFetchApp
  var url = 'https://graph.facebook.com?include_headers=false&batch=' + encodeURIComponent(JSON.stringify(batch))




  // Here is the actual request to Facebook, in which I'm getting the error
  var result = UrlFetchApp.fetch(url, {
    method: 'POST',
    headers: {    
      Authorization: 'Bearer ' + service.getAccessToken()
    }
  });
  console.log('Response: '+result); // Illustrating the response #190

  var response =  JSON.parse(result.getContentText()); 

};

// Returns the authentication method required.
function getAuthType() {
  var response = {
    'type': 'OAUTH2'
  };
  return response;
}

Oauth2_FB.gs

// Got it from https://github.com/gsuitedevs/apps-script-oauth2/blob/master/samples/Facebook.gs

// I've set this with my own information
var CLIENT_ID = '12345678901234'; 
var CLIENT_SECRET = 'abcdefghijklmnopqrstuvxyz';

// Authorizes and makes a request to the Facebook API.
function runFBAuth(e) {
  var service = getService();
  var html = '';
  if (service.hasAccess()) {
    var url = 'https://graph.facebook.com/v3.3/me';
    var response = UrlFetchApp.fetch(url, {
      headers: {
        'Authorization': 'Bearer ' + service.getAccessToken()
      }
    });
    var result = JSON.parse(response.getContentText());
    Logger.log(JSON.stringify(result, null, 2));
  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s',
        authorizationUrl);
  }
}

// Reset the authorization state, so that it can be re-tested.
function reset() {
  var service = getService();
  service.reset();
}

// Configures the service.
function getService() {
  return OAuth2.createService('Facebook')
      // Set the endpoint URLs.
      .setAuthorizationBaseUrl('https://www.facebook.com/dialog/oauth?scope=manage_pages,read_insights')
      .setTokenUrl('https://graph.facebook.com/v3.3/oauth/access_token')

      // Set the client ID and secret.
      .setClientId(CLIENT_ID)
      .setClientSecret(CLIENT_SECRET)

      // Set the name of the callback function that should be invoked to complete
      // the OAuth flow.
      .setCallbackFunction('authCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties());
}

// Handles the OAuth callback.
function authCallback(request) {
  var service = getService();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Success! Please close the tab and continue.');
  } else {
    return HtmlService.createHtmlOutput('Denied! Please close the tab and contact the developer.');
  }
}

function get3PAuthorizationUrls() {
  var service = getService();
  if (service == null) {
    return '';
  }
  return service.getAuthorizationUrl();
}

function isAuthValid() {
  var service = getService();
  if (service == null) {
    return false; 
  }
  return service.hasAccess();
}

我需要什么

我希望获得JSON格式的响应,可以按照我需要的任何方式进行处理,并且它应该与Facebook GRAPH EXPLORER的响应相同:

{
   "data": [
      {
         "name": "page_fans",
         "period": "day",
         "values": [
            {
               "value": 17633,
               "end_time": "2019-06-27T07:00:00+0000"
            },
            {
               "value": 17639,
               "end_time": "2019-06-28T07:00:00+0000"
            }
         ],
         "title": "Lifetime Total Likes",
         "description": "Lifetime: The total number of people who have liked your Page. (Unique Users)",
         "id": "{PAGE_ID}/insights/page_fans/day"
      },
      {
         "name": "page_impressions",
         "period": "day",
         "values": [
            {
               "value": 647,
               "end_time": "2019-06-27T07:00:00+0000"
            },
            {
               "value": 63508,
               "end_time": "2019-06-28T07:00:00+0000"
            }
         ],
         "title": "Daily Total Impressions",
         "description": "Daily: The number of times any content from your Page or about your Page entered a person's screen. This includes posts, check-ins, ads, social information from people who interact with your Page and more. (Total Count)",
         "id": "{PAGE_ID}/insights/page_impressions/day"
      }
   ]
}

0 个答案:

没有答案