使用Access Token替代API Key通过Google Apps Script调用HubSpot API
修复HubSpot API密钥弃用问题:改用Access Token导入联系人到Google Sheets
你的代码核心问题
你添加的请求认证头配置option位置错误,而且没有传递给UrlFetchApp.fetch()方法,导致HubSpot API无法识别你的身份,请求会失败。
修正后的完整代码
function callHsapi() { // 替换为你的HubSpot Access Token var ACCESS_TOKEN = "YOUR_HUBSPOT_ACCESS_TOKEN"; var url = "https://api.hubapi.com/crm/v3/objects/contacts?limit=10&archived=false"; // 配置认证请求头,放在fetch之前 var options = { "headers": { "Authorization": "Bearer " + ACCESS_TOKEN }, "contentType": "application/json" }; // 传入配置参数发起请求 var response = UrlFetchApp.fetch(url, options); var data = JSON.parse(response.getContentText()); var results = data['results']; var sheet = SpreadsheetApp.getActiveSheet(); var header = ["Company", "Create Date", "Email", "First Name", "Last Modified Date", "Last Name", "Phone", "Website"]; var items = [header]; results.forEach(function (result) { items.push([ result['properties'].company, result['properties'].createdate, result['properties'].email, result['properties'].firstname, result['properties'].lastmodifieddate, result['properties'].lastname, result['properties'].phone, result['properties'].website ]); }); sheet.getRange(1, 1, items.length, items[0].length).setValues(items); results.forEach(function (result) { Logger.log(result['properties']); }); }
关键修改点
- 移除了原代码中已弃用的
API_KEY变量和URL里的hapikey参数 - 将认证请求头配置提前,并作为第二个参数传入
UrlFetchApp.fetch(),这是身份认证的核心 - 确保
Authorization头的格式正确:Bearer+ 你的Access Token(注意Bearer后面有空格)
Access Token获取与配置步骤
- 登录HubSpot后台,进入设置 > 集成 > 私有应用
- 创建新的私有应用,设置名称并勾选读取联系人等所需权限
- 生成Access Token,复制该Token替换代码中的
YOUR_HUBSPOT_ACCESS_TOKEN - 注意:Access Token是敏感信息,不要分享给他人,也不要直接硬编码在公开代码中(如果需要更安全的方式,可以使用Google Apps Script的服务存储)
内容的提问来源于stack exchange,提问作者matteo montella
相关产品推荐
相关产品推荐

