Hubspot API - 如何循环获取所有交易

Hubspot API - how to loop to get all deals

循环一直返回相同的 JSON-object,但我更改了偏移量...有人知道出了什么问题吗?

我就把整个函数都写出来吧,可能不会很干。

function getDeals (api_key) {

  //get the right spreadsheet & sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Blad1');
  sheet.clear();
  sheet.appendRow(["Dealname", "Dealstage", "Close date", "Amount"]);

  //set up API variables

  var offset = 0;
  var queryParams = '&limit=250&offset=' + offset + '&properties=dealname&properties=dealstage&properties=closedate&properties=amount'
  var _url = 'https://api.hubapi.com/deals/v1/deal/paged?hapikey=' + api_key;
  var options = {
    "method": "GET",
    "muteHttpExceptions": true
  };

  //set up functions for call
  var apiCall = function(url, endpoint){
    var apiResponse = UrlFetchApp.fetch(url + endpoint,options);
    var json = JSON.parse(apiResponse);
    return json
  };

  var filterDeals = function (url, unfiltered_deals){
    var i = 0;
    while (unfiltered_deals.status !== "error" && i < (unfiltered_deals.deals).length) {
      if (unfiltered_deals.deals[i].properties.dealstage.value == "closedwon") {
        var dealname = unfiltered_deals.deals[i].properties.dealname.value;
        var dealstage = unfiltered_deals.deals[i].properties.dealstage.value;
        var closedate = new Date((unfiltered_deals.deals[i].properties.closedate.value)*1000);
        var amount = unfiltered_deals.deals[i].properties.amount.value;
        var deals = [dealname, dealstage, closedate, amount];
        // Append Hubspot data to Spreadsheet
        sheet.appendRow(deals);
      }
      i++;
     }
    if (unfiltered_deals.hasMore) {
      offset = unfiltered_deals.offset;
      var newDeals = apiCall(url, queryParams);
      filterDeals(_url, newDeals, offset, queryParams);
    } else {
      return
    }
  }

   //Api call to get deals  
  var dealCall = apiCall(_url, queryParams);
  var filteredDeals = filterDeals(_url, dealCall);

};

我用 API 键调用这个函数。

你总是得到相同 JSON 参数的原因是你永远不会用新的偏移值更新你的变量 queryParams。在您的代码片段中:

if (unfiltered_deals.hasMore) {
      offset = unfiltered_deals.offset; 
      var newDeals = apiCall(url, queryParams);
      filterDeals(_url, newDeals, offset, queryParams);
    }

您将获得新的偏移值,即 offset = unfiltered_deals.offset;。但是你需要像这样重新初始化它的值来更新你的 queryParams

  if (unfiltered_deals.hasMore) {
      offset = unfiltered_deals.offset; 
      queryParams = '&limit=250&offset=' + offset + '&properties=dealname&properties=dealstage&properties=closedate&properties=amount'
      var newDeals = apiCall(url, queryParams);
      filterDeals(_url, newDeals, offset, queryParams);
    }