【问题标题】:Google Spreadsheets API with OAuth2.0 using Javascript使用 Javascript 的带有 OAuth2.0 的 Google 电子表格 API
【发布时间】:2012-12-23 17:16:16
【问题描述】:

我正在尝试使用 Javascript 访问私有 Google 电子表格。我已成功获得 OAuth2.0 授权,并且可以看到我所有的 Google Drive 文档的列表。我似乎无法进入特定的电子表格。代码如下,函数“retrieveAllFiles”中的相关电子表格代码。其中很多内容来自 Google 教程。

var clientId = 'working';
var apiKey = 'working';
var scopes = 'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds';

function handleClientLoad() {
    console.log('inside handleClientLoad function');
    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuth,1);
}

function checkAuth() {
    console.log('inside checkAuth function');
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
    console.log('finished checkAuth function');
}

function handleAuthResult(authResult) {
    console.log('inside handleAuthResult function');
    var authButton = document.getElementById('authButton');
    authButton.style.display = 'none';
    if (authResult && !authResult.error) {
        //Access token has been succesfully retrieved, requests can be sent to the API.
        apiCalls();
    } else {
        //No access token could be retrieved, show the button to start the authorization flow.
        authButton.style.display = 'block';
        authButton.onclick = function() {
            gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        };
    }
}

function apiCalls() {
    console.log('inside apiCalls function');
    gapi.client.load('drive', 'v2', function() {
         retrieveAllFiles(callback);
    });
}

function retrieveAllFiles(callback) {
     $.get('http://spreadsheets.google.com/feeds/spreadsheets/private/full', function(data) {
        console.log('get request processed');
        console.log(data);
    });
    console.log('inside retrieveAllFiles function');
    var retrievePageOfFiles = function(request, result) {
        request.execute(function(resp) {
        result = result.concat(resp.items);
        var nextPageToken = resp.nextPageToken;
        if (nextPageToken) {
            request = gapi.client.drive.files.list({
                'pageToken': nextPageToken
            });
            retrievePageOfFiles(request, result);
        } else {
            callback(result);
        }
        });
    }
    var initialRequest = gapi.client.drive.files.list();
    retrievePageOfFiles(initialRequest, []);
}

function callback(result) {
    console.log('all should be loaded at this point');
    console.log(result);
    $('#drive-list').append('<ul class="items"></ul>');
    $.map(result, function(v,i){
        $('.items').append('<li>' + v.title + ':' + v.id + '</li>');
    });
}

需要明确的是,目前的最终结果是我所有的 Google Drive 文档的列表,但没有用于“获取数据处理”的 console.log。我在控制台中没有收到任何错误消息,所以我不知道发生了什么。

谢谢。

【问题讨论】:

  • 您能告诉我如何获取电子表格的客户端ID吗?谢谢!
  • 转到Google's Developers Console。创建一个新项目或登录到现有项目。在左侧边栏上,转到APIs &amp; auth 下标题为Credentials 的部分。它有一个名为 ClientID 的部分,您应该可以在那里找到更多信息。

标签: javascript oauth-2.0 google-spreadsheet-api


【解决方案1】:

从一堆不同来源编译的最终解决方案,希望这会对某人有所帮助。

var scopes = 'https://spreadsheets.google.com/feeds';
var clientId = 'working';
var apiKey = 'working';

function handleClientLoad() {
    console.log('inside handleClientLoad function');
    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuth,1);
}

function checkAuth() {
    console.log('inside checkAuth function');
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
    console.log('finished checkAuth function');
}

function handleAuthResult(authResult) {
    console.log('inside handleAuthResult function');
    console.log(gapi.auth.getToken());
    var authButton = document.getElementById('authButton');
    authButton.style.display = 'none';
    if (authResult && !authResult.error) {
        //Access token has been successfully retrieved, requests can be sent to the API.
        loadClient();
    } else {
        //No access token could be retrieved, show the button to start the authorization flow.
        authButton.style.display = 'block';
        authButton.onclick = function() {
            gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        };
    }
}

function loadClient() {
    console.log('inside loadClient function');
    var token = gapi.auth.getToken().access_token;
    var urlLocation = ''; //Get this from the URL of your Spreadsheet in the normal interface for Google Drive.

    //This gives a spitout of ALL spreadsheets that the user has access to.
    var url = 'https://spreadsheets.google.com/feeds/spreadsheets/private/full?access_token=' + token;

    //This gives a list of all worksheets inside the Spreadsheet, does not give actual data
    var url = 'https://spreadsheets.google.com/feeds/worksheets/' + urlLocation + '/private/full?access_token=' + token;

    //This gives the data in a list view - change the word list to cells to work from a cell view and see https://developers.google.com/google-apps/spreadsheets/#working_with_cell-based_feeds for details
    var url = 'https://spreadsheets.google.com/feeds/list/' + urlLocation + '/od6/private/full?access_token=' + token;

    console.log(url);
    $.get(url, function(data) {
        console.log(data);
    });
}

【讨论】:

  • 当我第一次放入 auth_token 时,我又开始收到“400 Bad Request”错误。原来是一个糟糕的worksheetId。当我从 docs.google.com url 为电子表格输入 gid= 的值时,它起作用了。我没有尝试 urlLocation 的完整 URL。 API 文档和大多数其他地方都说要使用文档 URL 中的 key= 值。所以如果是 docs.google.com/spreadsheet/ccc?key=blahblah&gid=5,那么 urlLocation='blahblah' 和 worksheetId=5 如:'spreadsheets.google.com/feeds/list/blahblah/5/private/…
  • 所以,我在这个例子中走得很远,但是跨域安全限制阻止了我(即“不存在'Access-Control-Allow-Origin'标头”等)你在哪里跑这个脚本是为了让你的 JS 访问响应数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多