oauth 2.0 - OAuth2 with Google Cloud Print -


i had written google apps script connected google cloud print automate printing. script auto-run on time interval, search relevant files, , if found sent them printer. code used oauthconfig , working fine, class has been deprecated , after weekend of trial & error , scouring interwebs can't work oauth2.

here's oauthconfig code working fine:

function printdoc(docid, doctitle, myprinterid) {    var scope = 'https://www.googleapis.com/auth/cloudprint';   var url = 'https://www.google.com/cloudprint/submit';    var payloadofsubmit = {     "printerid" : myprinterid,      "title" : doctitle,     "content"  : docid,      "contenttype" : "google.kix"     };    var fetchargs = googleoauth_('google', scope, payloadofsubmit);    fetchargs.method = 'post';   var responseofsubmit = urlfetchapp.fetch(url, fetchargs);   var jsonofsubmit = json.parse(responseofsubmit.getcontenttext());     return jsonofsubmit; }  function googleoauth_(name, scope, payloaddata) {   var oauthconfig = urlfetchapp.addoauthservice(name);   oauthconfig.setauthorizationurl("https://www.google.com/accounts/oauthauthorizetoken");   oauthconfig.setrequesttokenurl("https://www.google.com/accounts/oauthgetrequesttoken?scope="+scope);   oauthconfig.setaccesstokenurl("https://www.google.com/accounts/oauthgetaccesstoken");   oauthconfig.setconsumerkey("anonymous");   oauthconfig.setconsumersecret("anonymous");   return {     oauthservicename:name,      oauthusetoken:"always",      mutehttpexceptions:true,      payload:payloaddata   };  }   

i've connected github library oauth2. however, what's different instructions provided there, , on many other sites, assume code deployed web service user prompted manually click authorize request. in case code saved on google apps script file, , cloud printer on same google account, never needed manual intervention or & forth original oauthconfig.

my first attempt adapting instructions was:

function printdoc2(docid, doctitle, myprinterid) {    var url = 'https://www.google.com/cloudprint/submit';   var scope = 'https://www.googleapis.com/auth/cloudprint';    var payloadofsubmit = {     "printerid" : myprinterid,      "title" : doctitle,     "content"  : docid,      "contenttype" : "google.kix",   };    var accesstoken = googleoauth_('google', scope).getaccesstoken();    var params = {     method:"post",     headers: {"authorization": "bearer " + accesstoken},     mutehttpexceptions:true,     payload:payloadofsubmit   };    var responseofsubmit = urlfetchapp.fetch(url, params);   //logger.log(responseofsubmit);   var jsonofsubmit = json.parse(responseofsubmit.getcontenttext());     return jsonofsubmit; }  function googleoauth2_(name, scope) {    return oauth2.createservice(name)     .setauthorizationbaseurl('https://accounts.google.com/o/oauth2/auth')     .settokenurl('https://accounts.google.com/o/oauth2/token')     .setclientid("anonymous")     .setclientsecret("anonymous")     .setprojectkey(scriptapp.getprojectkey())     .setpropertystore(propertiesservice.getuserproperties())     .setscope(scope)     .setcallbackfunction('authcallback'); }  function authcallback(request) {   var driveservice = getdriveservice();   var isauthorized = driveservice.handlecallback(request);   if (isauthorized) {     return htmlservice.createhtmloutput('success! can close tab.');   } else {     return htmlservice.createhtmloutput('denied. can close tab');   } } 

but gives me error "access not granted or expired" when tries run line:

var accesstoken = googleoauth_('google', scope).getaccesstoken(); 

so found apps scriptapp method getoauthtoken seemed might give me token need. replaced above line with:

var accesstoken = scriptapp.getoauthtoken(); 

and code executes response server "error 403 user credentials required".

here's third attempt based on @mogsdad's suggestion:

function sendprintjob(docid,myprinterid,doctitle) {    var payloadofsubmit = {             "printerid" : myprinterid,              "title" : doctitle,             "content"  : docid,              "contenttype" : "google.kix" ,   };    var request = {     "method": "post",     "headers":{"authorization": "bearer "+scriptapp.getoauthtoken()},         "mutehttpexceptions": true   };    var responseofsubmit = urlfetchapp.fetch("https://www.google.com/cloudprint/submit", request);   logger.log(responseofsubmit); } 

i've tried number of variations, including creating developer console project , using client id provided there, keep getting stuck @ these 2 issues (access not granted, or credentials required). if can provide i'd appreciate it.

here steps allowed me connect google apps script google cloud print, submit gcp jobs (these steps started within google apps script):

  1. add oauth2 library (https://github.com/googlesamples/apps-script-oauth2) google apps script going to: resources > libraries > find library mswhxl8fvhtfuh_q3uojbxvxhmjh3sh48 > select
  2. create new web application in developer console resources > developer console project > click project link > apis & auth > credentials > add credentials > oauth2.0 client id > web application > set authorized redirect uris format
    https://script.google.com/macros/d/{project key}/usercallback project key under file > project properties , copy client id , client secret
  3. add id , secret "getcloudprintservice()" code below (replace client_id , client_secret)
  4. go run > showurl , authorize script.
  5. open logger (cmd + enter), copy url , paste in new browser tab complete authorization.
  6. go https://www.google.com/cloudprint/#printers , select printer, click details, expand advanced details, , copy printer id (it of format 555aa555-5a55-5555-5555-55555a55a555)
  7. add printer id "printgoogledocument()" code below (replace myprinterid)

this resource helpful in figuring steps out: http://ctrlq.org/code/20061-google-cloud-print-with-apps-script, , may find these links helpful:

function showurl() {    var cpservice = getcloudprintservice();    if (!cpservice.hasaccess()) {      logger.log(cpservice.getauthorizationurl());    } else {      logger.log("you have access service.");    }  }     function getcloudprintservice() {    return oauth2.createservice('print')      .setauthorizationbaseurl('https://accounts.google.com/o/oauth2/auth')      .settokenurl('https://accounts.google.com/o/oauth2/token')      .setclientid(client_id)      .setclientsecret(client_secret)      .setcallbackfunction('authcallback')      .setpropertystore(propertiesservice.getuserproperties())      .setscope('https://www.googleapis.com/auth/cloudprint')      .setparam('login_hint', session.getactiveuser().getemail())      .setparam('access_type', 'offline')      .setparam('approval_prompt', 'force');  }     function authcallback(request) {    var isauthorized = getcloudprintservice().handlecallback(request);    if (isauthorized) {      return htmlservice.createhtmloutput('you can use google cloud print apps script.');    } else {      return htmlservice.createhtmloutput('cloud print error: access denied');    }  }    function getprinterlist() {    var response = urlfetchapp.fetch('https://www.google.com/cloudprint/search', {      headers: {        authorization: 'bearer ' + getcloudprintservice().getaccesstoken()      },      mutehttpexceptions: true    }).getcontenttext();       var printers = json.parse(response).printers;       (var p in printers) {      logger.log("%s %s %s", printers[p].id, printers[p].name, printers[p].description);    }  }    function printgoogledocument(docid, doctitle) {      // notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en    var ticket = {      version: "1.0",      print: {        color: {          type: "standard_color"        },        duplex: {          type: "no_duplex"        },      }    };         var payload = {      "printerid" : myprinterid,      "content"   : docid,      "title"  : doctitle,      "contenttype" : "google.kix", // allows print google docs      "ticket"    : json.stringify(ticket),    };       var response = urlfetchapp.fetch('https://www.google.com/cloudprint/submit', {      method: "post",      payload: payload,      headers: {        authorization: 'bearer ' + getcloudprintservice().getaccesstoken()      },      "mutehttpexceptions": true    });       // if successful, should show job here: https://www.google.com/cloudprint/#jobs      response = json.parse(response);    if (response.success) {      logger.log("%s", response.message);    } else {      logger.log("error code: %s %s", response.errorcode, response.message);    }    return response;  }


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -