我想在谷歌云存储上存储谷歌文档。我是管理员用户,可以访问Google云端存储。 我使用这段代码:
function myFunction() {
var base="https://www.googleapis.com/auth/devstorage.full_control"
var fetchArgs=googleOAuth_('provisioning',base)
fetchArgs.payload=<content_data_that you want to put on GCS>
fetchArgs.method='PUT'
fetchArgs. contentType=<content_type>
fetchArgs.host="<bucket_name>.storage.googleapis.com"
var url='https://storage.googleapis.com/<bucket_name>/<file_name>'
var result=UrlFetchApp.fetch(url,fetchArgs)
}
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey(consumerKey);
oAuthConfig.setConsumerSecret(consumerSecret);
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
当我运行此代码时,它会给出503服务器错误。 任何建议对我都有帮助。
这个问题已经解决了。通过更正更新了代码。
答案 0 :(得分:0)
Google云端存储文档提到,如果您使用OAuth 1.0,则还需要传递API密钥。
https://developers.google.com/storage/docs/json_api/v1/how-tos/authorizing
答案 1 :(得分:0)
我还没试过,但看起来它可能会简化你的生活:
OAuthService
作者:James Ferreira - GoogleScriptExamples.com
此库不需要使用OAuth。它有一种方法 getAuth('',optUserScope)并适用于所有 Google API。见这里的例子。
项目密钥:MM5uQxqjwkMiuJW2zE50SgUF7jOZt2NQ8
请参阅: https://sites.google.com/site/scriptsexamples/custom-methods/google-oauth
答案 2 :(得分:0)
我还尝试通过 Google Apps Script 使用 Google Cloud Storage API。我找到了以下库:
https://github.com/googleworkspace/apps-script-oauth2
那里的文档实际上更有帮助,因为它向我展示了我根本不需要图书馆:
<块引用>即使您的 API 不在其中之一,您仍然可以使用 Apps 脚本为您获取 OAuth2 令牌。只需编辑脚本的清单以包含您的 API 所需的其他范围。当用户授权您的脚本时,他们也会被要求批准这些额外的范围。然后在您的代码中使用 ScriptApp.getOAuthToken() 方法访问脚本获取的 OAuth2 访问令牌,并将其传递到 UrlFetchApp.fetch() 调用的 Authorization 标头中。
访问示例 NoLibrary 以查看如何完成此操作的示例。
对我(和后代)的主要收获:
使 appsscript.json
可见并添加 oauthScopes
和所有想要的 API scopes 加上 https://www.googleapis.com/auth/script.external_request
。
将 UrlFetchApp.fetch()
第二个参数设置为 headers: {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()}
忽略 Google API 示例中的 &key=[YOUR_API_KEY]
。