使用Javascript和OAuth2.0的Google电子表格API

12
我正在尝试使用Javascript访问一个私人的Google电子表格。我已经成功地进行了OAuth2.0授权,并可以看到所有我的Google驱动器文档的列表。但是,我似乎无法进入特定的电子表格。以下是相关电子表格代码在"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。控制台中没有任何错误消息,所以我无法确定发生了什么。

谢谢。


请问如何获取 SpreadSheets 的客户端 ID?谢谢! - VladL
前往Google开发者控制台。创建一个新项目或登录到现有项目。在左侧边栏中,转到“API和身份验证”下的“凭据”部分。它有一个名为“客户端ID”的部分,您应该能够在那里找到更多信息。 - Josh
1个回答

22

这是从许多不同来源编译的最终解决方案,希望能帮助到某些人。

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文档和大多数其他地方都说要使用docs URL中的key=值。因此,如果它是docs.google.com/spreadsheet/ccc?key=blahblah&gid=5,则urlLocation='blahblah',worksheetId=5,如下所示:'https://spreadsheets.google.com/feeds/list/blahblah/5/private/full?access_token='+token - jla
1
所以,我在这个例子中取得了相当大的进展,但是跨域安全限制阻止了我(即“没有‘Access-Control-Allow-Origin’头”等)。你从哪里运行这个脚本,以便让你的JS可以访问响应数据? - Eric Nguyen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接