我正在尝试从Node.js应用程序写入Sheet文档,该应用程序响应webhook。我被困在认证部分。我有以下代码:
'use strict';
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var request = require('request');
var moment = require('moment');
var mz = require('moment-timezone');
var unirest = require('unirest');
var onfleetWorkersUrl = "https://onfleet.com/api/v2/workers/";
var sheetsApiKey = 'MY_API_KEY';
function handleGET (req, res) {
// Do something with the GET request
res.send(req.query.check);
}
function handlePUT (req, res) {
// Do something with the PUT request
res.status(403).send('Forbidden!');
}
function appendNameApiKey(name) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.append({
auth: sheetsApiKey,
spreadsheetId: MY_SPREADHSEET_ID,
range: 'Sheet1!A:A',
body: {
"values": [
[
name
]
]
},
}, function(err, response) {
if (err) {
console.log('append request returned an error: ' + err);
return;
} else {
console.log(response);
}
});
}
function handleNewTaskPOST (req, res) {
unirest.get(onfleetWorkersUrl+req.body.workerId)
.auth(apiKey, "")
.end(function (response) {
var driverName = response.body.name;
var triggerId = req.body.triggerId;
var timeMilli = req.body.time;
var driverName = response.body.name;
var formattedTime = mz.tz(timeMilli, "America/Los_Angeles").format('h:mm a');
switch (triggerId) {
case 5:
console.log('triggerId: 5');
appendNameApiKey(driverName)
res.status(200).end();
break;
default:
console.log('Something went wrong.');
break;
}
});
}
/**
* Responds to a GET request with "Hello World!". Forbids a PUT request.
*
* @example
* gcloud alpha functions call helloHttp
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.eat24TimesheetCF = function eat24TimesheetCF (req, res) {
switch (req.method) {
case 'GET':
handleGET(req, res);
break;
case 'PUT':
handlePUT(req, res);
break;
case 'POST':
handleNewTaskPOST(req, res);
break;
default:
res.status(500).send({ error: 'Something blew up!' });
break;
}
};
这很遗憾地返回一个错误,指出我没有提供有效密钥。有人可以给我一些指示,告诉我如何使用API密钥通过Node.js验证Sheet API请求吗?
答案 0 :(得分:0)
基于文档:
您的应用程序发送到Google表格API的每个请求都需要向Google标识您的应用程序。有两种方法可以识别您的应用程序:使用OAuth 2.0令牌(也授权请求)和/或使用应用程序的API密钥。以下是如何确定使用哪些选项:
- 如果请求需要授权(例如请求个人的私有数据),则应用程序必须为请求提供OAuth 2.0令牌。应用程序也可以提供API密钥,但不必提供。
- 如果请求不需要授权(例如请求公开数据),则应用程序必须提供API密钥或OAuth 2.0令牌,或两者兼而有之 - 无论选项最多方便你。
为此,您需要创建一个http request,如下所示:
https://sheets.googleapis.com/v4/spreadsheets/1p7sFt.....gRu9A/values/Sheet1A1:L7**&majorDimension=COLUMNS**&key=AIza.....oTXg