Google Sheet API:“消息”:“请求缺少有效的API密钥。”

时间:2018-06-15 18:31:37

标签: javascript google-chrome-extension google-sheets-api google-oauth2

我正在努力做一个扩展,将从页面获取一些数据并将其发送到谷歌表。 我的清单:

"oauth2": {
        "client_id": "client_id",
        "scopes": ["https://www.googleapis.com/auth/spreadsheets"] 
    },
    "permissions": [
        "activeTab",
        "tabs", 
        "https://*.*/*",
        "storage",
        "declarativeContent",
        "identity",
        "https://ssl.gstatic.com/",
        "https://www.googleapis.com/*",
        "https://accounts.google.com/",
        "https://sheets.googleapis.com/",
        "https://www.googleapis.com/auth/spreadsheets/"
    ],
    "key": {key}

背景页面:

var tokenS;
chrome.runtime.onInstalled.addListener(function() {
  chrome.storage.sync.set({number: value}, function(data) {
  });
    chrome.identity.getAuthToken({
        interactive: false
    }, function(token) { 
        tokenS = token
        console.log(token)
    });
});
function writeData(request, sender){
    myspreadsheetId = "myspreadsheetId " 
    var params = {
        "range":"Sheet1!A1:A",
        "majorDimension": "ROWS",
        "values": [
            [request.name]
        ],
    }
    var xhr = new XMLHttpRequest();
    xhr.open('PUT', 'https://sheets.googleapis.com/v4/spreadsheets/' + myspreadsheetId + '/values/Sheet1!A1:A1?valueInputOption=USER_ENTERED');
    console.log(tokenS)
    xhr.setRequestHeader('Authorization', 'Bearer '+tokenS);
    xhr.send(JSON.stringify(params));
};
chrome.runtime.onMessage.addListener(writeData)

我收到下一个错误:

{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

在谷歌云平台上我看到100%的错误率(http://prntscr.com/jvfl0c)。我不明白我做错了什么。请帮忙。

1 个答案:

答案 0 :(得分:0)

您将用在Google Cloud Console中为项目生成的API密钥替换"key": {key}中的第二个“密钥”(在第一个代码示例的最后一行)。 要生成您的API密钥,您需要导航到凭据页面,然后点击创建凭据>> API密钥


首先,确保选择了您选择的项目Example


下一步;从“导航菜单” >>“ API和服务” >>“凭据” >>“创建凭据” >>“ API密钥”