简体   繁体   中英

OAuth 2.0 Authorization: GAS and Google Maps Engine

I have a Google Maps Engine project where a datasource can be updated via Google Forms/Google Apps Script. I know that there is a way to configure OAuth in GAS ( https://developers.google.com/apps-script/reference/url-fetch/o-auth-config ) but I can't figure out how to make it work after spending hours reading through the GAS and GME documentation. I have been able to get around it using the OAuth Playground to obtain an access token, but I need to manually refresh each hour. I know the answer is probably simple, but I am new to OAuth and I can't find a simple guide out there to help me.

How can I get my Google Apps Script to play nicely with Google Maps Engine through OAuth?

I have included how I currently access GME below:

    /* This function is called when a new provider is added through the "Medical Providers" form
   It sends an HTTP request to Google Maps Engine to add the new provider to the map */
function addNewtoTable(row){
  var aPIKey = "MY_API_KEY";
  var bearer = "ACCESS_TOKEN_FROM_OAUTH_PLAYGROUND";
  var projectID = "MY_PROJECT_ID";
  var tableID = "MY_TABLE_ID";
  //tutorial here https://developers.google.com/maps-engine/documentation/tutorial
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Providers");

  var address = sheet.getRange(row,2).getValue();
  var response = Maps.newGeocoder().geocode(address);
  for (var j = 0; j < response.results.length; j++) {
    var result = response.results[j];
    //Logger.log('%s: %s, %s', result.formatted_address, result.geometry.location.lat,
    //             result.geometry.location.lng);
  };
  var lat = result.geometry.location.lat;
  var long = result.geometry.location.lng;
  var name= '"'+sheet.getRange(row,1).getValue()+'"';
  var phone= '"'+sheet.getRange(row,4).getValue().toString()+'"';
  var email= '"'+sheet.getRange(row,3).getValue()+'"';
  var inbounds= '"'+sheet.getRange(row,5).getValue().toString()+'"';
  var outbounds = '"'+sheet.getRange(row,6).getValue().toString()+'"';
  var lastIn = '" '+sheet.getRange(row,7).getValue().toString()+' "';
  var lastOut = '" '+sheet.getRange(row,8).getValue().toString()+' "';
  var gxid = '"'+sheet.getRange(row,9).getValue().toString()+'"';

  //HTTP request goes here
  var payload = '{features:[{type: "Feature",geometry:{type: "Point",coordinates: ['+long+','+lat+']},properties: {gx_id: '+gxid+',name: '+name+',phone:'+phone+',email:'+email+',inbound:'+inbounds+',outbound:'+outbounds+',last_inbound:'+lastIn+',last_outbound:'+lastOut+'}}]}';
  Logger.log(payload);


  var headers = {"Authorization": "Bearer ACCESS_TOKEN_FROM_OAUTH_PLAYGROUND", "Content-type": "application/json"};
  var options ={"method" : "post","headers" : headers, "payload" : payload, "muteHttpExceptions" : true};
  var httpresponse = UrlFetchApp.fetch("https://www.googleapis.com/mapsengine/v1/tables/MY_TABLE_ID/features/batchInsert",options);
  Logger.log(httpresponse);

  if (httpresponse!=""){
    MailApp.sendEmail('MY_EMAIL', 'HTTP Request Failed to Send', httpresponse);
  };
};

It's certainly possible. The App Script docs have a tutorial explaining how to connect to a remote service using OAuth that uses the Twitter API as an example. This example also shows an OAuth-authorized call being executed.

The main difference in the tutorial for Maps Engine is the first step, where you don't set up with Twitter, you set up in the Developers Console .

  • You want to create a new OAuth client ID, under APIs & Auth -> Credentials. It's a web application.
  • Instead of setting the "Callback URL" in Twitter, you'll set the "Authorized Redirect URI" in the console, when creating the client ID. Set the authorized origins to docs.google.com too, just in case.
  • You'll get your "Consumer Key" and "Consumer Secret" through console.developers.google.com too, they correspond to the Client ID and Client Secret that are referred to in this GME doc .

In addition to the set up, these pointers may help you.

  • The UrlFetchApp.addOauthService("twitter") calls can use any string as an identifier, there's nothing special about the phrase "twitter", but it needs to match oAuthServiceName
  • The URLs you need look like they should be these (grabbed from here ):
    • oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
    • oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope); Scope is explained here .
    • oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");

A little too late for my purposes, but I found that Google themselves made a library for GAS that enables OAuth 2.0 . Why this is not included within GAS is beyond me. This also looks to be pretty recent, with some updates as of 5 days ago.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM