【问题标题】:How to Access Google Photos API with Javascript using google-api-javascript-client and read JSON data?如何使用 google-api-javascript-client 使用 Javascript 访问 Google Photos API 并读取 JSON 数据?
【发布时间】:2018-12-18 15:39:24
【问题描述】:

我对使用 API 和使用 OAuth 获取 JSON 数据非常陌生。有人可以帮助我吗?我正在尝试访问客户的谷歌照片并阅读它们。这些代码 sn-ps 来自谷歌照片文档。我对其进行了修改,但仍然出现错误:“加载资源失败:服务器响应状态为 401 ()”和“未捕获 {错误:“idpiframe_initialization_failed”,详细信息:“客户端的有效来源:http://127.0.0。 …为您的项目的客户端 ID 列出此来源。"}" 谢谢!!!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
        onload="this.onload=function(){};handleClientLoad()"
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

<script>
    var GoogleAuth;
    var SCOPE = 'https://www.googleapis.com/auth/drive.photos.readonly';

    function handleClientLoad() {
        // Load the API's client and auth2 modules.
        // Call the initClient function after the modules load.
        gapi.load('client:auth2', initClient);
    }

    function initClient() {
        // Retrieve the discovery document for version 3 of Google Drive API.
        // In practice, your app can retrieve one or more discovery documents.
        var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/photos/v1/rest';

        // Initialize the gapi.client object, which app uses to make API requests.
        // Get API key and client ID from API Console.
        // 'scope' field specifies space-delimited list of access scopes.
        gapi.client.init({
            'apiKey': 'XXXXXXXXXXXX',
            'discoveryDocs': [discoveryUrl],
            'clientId': 'XXXXXXXXXXXXXXXXXX',
            'scope': SCOPE
        }).then(function () {
            GoogleAuth = gapi.auth2.getAuthInstance();

            // Listen for sign-in state changes.
            GoogleAuth.isSignedIn.listen(updateSigninStatus);

            // Handle initial sign-in state. (Determine if user is already signed in.)
            var user = GoogleAuth.currentUser.get();
            setSigninStatus();

            // Call handleAuthClick function when user clicks on
            //      "Sign In/Authorize" button.
            $('#sign-in-or-out-button').click(function () {
                handleAuthClick();
            });
            $('#revoke-access-button').click(function () {
                revokeAccess();
            });
        });
    }

    function handleAuthClick() {
        if (GoogleAuth.isSignedIn.get()) {
            // User is authorized and has clicked 'Sign out' button.
            GoogleAuth.signOut();
        } else {
            // User is not signed in. Start Google auth flow.
            GoogleAuth.signIn();
        }
    }

    function revokeAccess() {
        GoogleAuth.disconnect();
    }

    function setSigninStatus(isSignedIn) {
        var user = GoogleAuth.currentUser.get();
        var isAuthorized = user.hasGrantedScopes(SCOPE);
        if (isAuthorized) {
            $('#sign-in-or-out-button').html('Sign out');
            $('#revoke-access-button').css('display', 'inline-block');
            $('#auth-status').html('You are currently signed in and have granted ' +
                'access to this app.');
        } else {
            $('#sign-in-or-out-button').html('Sign In/Authorize');
            $('#revoke-access-button').css('display', 'none');
            $('#auth-status').html('You have not authorized this app or you are ' +
                'signed out.');
        }
    }

    function updateSigninStatus(isSignedIn) {
        setSigninStatus();
    }
</script>
<button id="sign-in-or-out-button"
        style="margin-left: 25px">Sign In/Authorize
</button>
<button id="revoke-access-button"
        style="display: none; margin-left: 25px">Revoke access
</button>

<div id="auth-status" style="display: inline; padding-left: 25px"></div>

【问题讨论】:

  • 不重复。这是不同的问题。我尝试了该帖子中的一些步骤,但没有任何帮助。
  • 我仍然找不到任何问题的答案。

标签: javascript json api oauth google-photos


【解决方案1】:

使用此链接了解更多详情

右侧有按钮执行,单击该按钮您将获得所有照片, 你也可以找到代码只需点击一个图标右侧的文本方形图标试试这个API,会打开一个弹出窗口,点击 JAVASCRIPT Tab ,你会找到代码

https://developers.google.com/photos/library/reference/rest/v1/mediaItems/search

【讨论】:

    【解决方案2】:

    使用您的标准 Google Apps 脚本令牌访问 Google Photo API

    我相信您可以将已有的令牌用于 Google Apps 脚本。

    我确实进入了控制台并为此项目设置了凭据,但我没有使用它们。

    function listImages() {
      var token='';
      var html='';
      var n=0;
      do{
        var params = {muteHttpExceptions:true,headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
        var url=Utilities.formatString('https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100%s',(token!=null)?"&pageToken=" + token:"");
        var resp=UrlFetchApp.fetch(url,params);
        Logger.log(resp);
        var js=JSON.parse(resp.getContentText());
        for(var i=0;i<js.mediaItems.length;i++) {
          html+=Utilities.formatString('<br />%s - File Name: %s<br /><img src="%s" width="265"/>',++n,js.mediaItems[i].filename,js.mediaItems[i].baseUrl);
        }
        token=js.nextPageToken;
      }while(token!=null);
      var userInterface=HtmlService.createHtmlOutput(html).setWidth(1200).setHeight(500);
      //SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Images')//dialog
      SpreadsheetApp.getUi().showSidebar(userInterface);//sidebard
    }
    

    【讨论】:

    • 如果没有必需的授权范围 (https://www.googleapis.com/auth/photoslibrary.readonly),上述代码将无法工作。要添加范围,您需要使用 appsscript.json(清单文件)。在这里查看:developers.google.com/apps-script/concepts/…
    • @Cooper 您在哪里找到在 url 中使用 '?pageSize=100%s' 的地方?我看到没有它,第一个请求只会获取 25 个媒体项
    • %s 是 Utilities.formatString() 中的一个替换参数,它用这个 (token!=null)?"&amp;pageToken=" + token:"" 填充,它只是说如果 token 不为空,则添加 &pageToken=token 最初为空并且可以成为 nextpageToken 。如果为null,则不要添加附加参数。
    【解决方案3】:

    试试这个代码

    点击按钮调用 onAuthPhotoApiLoad 函数

    **还包括google的js **

    var scopeApi = ['https://www.googleapis.com/auth/photoslibrary', 'https://www.googleapis.com/auth/photoslibrary.readonly', 'https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata'];
    
    function onAuthPhotoApiLoad() {
        window.gapi.auth.authorize(
            {
                'client_id': "Put Client ID Here",
                'scope': scopeApi,
                'immediate': false
            },
            handlePhotoApiAuthResult);
    }
    
    
    function handlePhotoApiAuthResult(authResult) {
        if (authResult && !authResult.error) {
            oauthToken = authResult.access_token;
    
                   GetAllPhotoGoogleApi();
        }
    }
    
    
    function GetAllPhotoGoogleApi() {
           gapi.client.request({
            'path': 'https://photoslibrary.googleapis.com/v1/mediaItems:search',
            'method': 'POST',
            'body': {
                "filters": {
                    "mediaTypeFilter": {
                        "mediaTypes": ["PHOTO"]
                    }
                }
            }
        }).then(function (response) {
            console.log(response);     
    
        }, function (reason) {
            console.log(reason);
        });
    }
    

    【讨论】:

    • 我只需要一个不记名令牌来发送 Firebase 消息传递,而我这辈子都得不到。我正在尝试使用它来获取令牌,但我认为它不会起作用。当我尝试说我没有授权的重定向 URL 但我有时,会出现一个窗口。我有我的本地主机和端口作为授权重定向。所以我简直要疯了,因为我唯一需要使用云消息传递的是谷歌不会告诉我如何获得的唯一东西。太疯狂了。
    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多