Auth.html:
<a href='<?!= getAuthURL(); ?>' target='_blank'>
<button>Authorize!</button>
</a>
授权。
function test() {
var html = HtmlService.createTemplateFromFile("Auth").evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE).setTitle("Test");
SpreadsheetApp.getUi().showModalDialog(html, "Test");
}
function getAuthURL() {
var options= {
client_id : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", // your id
scope : "https://www.googleapis.com/auth/cloudprint",
redirect_uri : "https://script.google.com/macros/d/MDYeOxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/usercallback", // your uri
state : ScriptApp.newStateToken().withMethod("getAuthResponse").createToken()
};
var url = "https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline";
for(var i in options)
url += "&"+i+"="+encodeURIComponent(options[i]);
return url;
}
获取 oAuth 令牌并调用 Google Cloud Print
function getAuthResponse(q) {
var options = {
method: "post",
muteHttpExceptions: true,
payload: {
code: q.parameter.code,
client_id : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", // your id
client_secret : "xxxxxxxxxxxxxxxxxxxxxxxx", // your secret
redirect_uri: "https://script.google.com/macros/d/MDYeOxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/usercallback", // your uri
grant_type: "authorization_code"
}
}
var response = JSON.parse(UrlFetchApp.fetch("https://accounts.google.com/o/oauth2/token", options));
var auth_string = response.token_type+" "+response.access_token;
options.method = "get";
options.payload = null;
options.headers = {Authorization: auth_string};
response = UrlFetchApp.fetch("https://www.google.com/cloudprint/search",options);
return ContentService.createTextOutput(response.getContentText());
}