2

I am very new to using API and getting JSON data using OAuth. Could anybody help me? I am trying to access clients google photos and read them. These code snippets are from google photos documentation. I modified it but still having error: "Failed to load resource: the server responded with a status of 401 ()" and "Uncaught {error: "idpiframe_initialization_failed", details: "Not a valid origin for the client: http://127.0.0.…itelist this origin for your project's client ID."}" Thank you!!!

<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>
Asyl
  • 65
  • 1
  • 1
  • 11

3 Answers3

4

use this link to get more details

On right side there is button Execute, on click that button you will get all photos , you can also find code just clicking a icon right side square icon of text Try this API, a popup will open, click on JAVASCRIPT Tab , you will find code

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

3

Accessing Google Photo API with your standard Google Apps Script token

I believe you can use the token that you already have with Google Apps Script.

I did go into the Console and setup the credentials for this project but I'm not using them.

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
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • 1
    Without required Authorization Scopes (`https://www.googleapis.com/auth/photoslibrary.readonly`) the above code will not work. To add scopes you need to use appsscript.json(manifest file). Check here: https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes – Ivan Gusev May 30 '19 at 08:35
  • @Cooper where did you find to use '?pageSize=100%s' in the url? I see without it that the first request will only grab 25 media items – Kayracer Sep 06 '19 at 03:51
  • the %s is a substitution parameter within Utilities.formatString() and it's filled with this `(token!=null)?"&pageToken=" + token:""` which just says that if token is not null than add &pageToken=token which is null at first and could become nextpageToken . If it is null then don't add the additional parameter. – Cooper Sep 06 '19 at 04:08
1

Try This Code

call onAuthPhotoApiLoad function on button click

**also include js of google **

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);
    });
}
  • All I need is a bearer token to send for firebase messaging and I can't get one for the life of me. I'm trying to use this to get a token but I don't think it would work. A window comes up when I try and says I don't have an authorized redirect URL but I do. I have my localhost and port as an authorized redirect. So I'm just going crazy because the only thing I need to use cloud messaging is the only thing Google won't tell me how to get. It's insane. – Daniel Jackson Dec 18 '18 at 14:48