I could use some help with creating a script when a Google Form is submitted.
Once the form submitted, the script automatically prints a Google Spreadsheet to a Google Cloud-based printer without bringing up the print dialog window.
I've read through Google Cloud Print Info
The idea behind the script is simple:
User fills out form
Form is then submitted
Script updates cells with information user put in
Script then prints to google cloud printer
Shipping label is ready
The below script will print a ticket but how do i add the printer capabilities to the POST request?
The code I have so far:
function onsubmit(e) {
var pid = "123456789"; //place printer id here
var sheetid = "123456789"; //place sheet id here
var ss = SpreadsheetApp.getActiveSpreadsheet();
var info = ss.getSheetByName('Form responses 1');
var lastRow = info.getLastRow();
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName('TICKET'))
authorize();
var url = "https://www.google.com/cloudprint/submit?printerid="+pid+"&contentType=google.spreadsheet&content="+sheetid+"&title=PrintingTicket";
var options = {
method: "post",
oAuthServiceName : "print",
oAuthUseToken : "always"
};
info.hideSheet();
var response = UrlFetchApp.fetch(url, options);
return Utilities.jsonParse(response.getContentText());
}
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("print");
var scope = "https://www.googleapis.com/auth/cloudprint";
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
}
Related
I created add-ons with the card service.
All I wanted is to run the function refresh() to clear data in Spreadsheet and add-on should refresh once I press Logout Button.
I use the below code to try running the function refresh() and my Add-ons should reload to display some details. Redirect URL (cardFooter1Button1OpenLink1) is working fine, but it's not calling the function refresh
function refresh(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var clear = sheet.getSheetByName('OfficeUsers');
var range = clear.getRange('D3:I').clearContent()
}
function newdemo(){
var cardFooter1Button1Action1 = CardService.newAction()
.setFunctionName('refresh');
var cardFooter1Button1OpenLink1 = CardService.newOpenLink()
.setUrl('www.office.com/logout')
.setOnClose(CardService.OnClose.RELOAD_ADD_ON);
var cardFooter1Button1 = CardService.newTextButton()
.setText('Logout')
.setOnClickAction(cardFooter1Button1Action1)
.setOpenLink(cardFooter1Button1OpenLink1);
var cardFooter1 = CardService.newFixedFooter()
.setPrimaryButton(cardFooter1Button1);
var cardSection1 = CardService.newCardSection();
var card = CardService.newCardBuilder()
.setFixedFooter(cardFooter1)
.addSection(cardSection1)
.build();
return card;
}
Please help me, When I press Logout, It's redirecting to URL and when I close the pop up, it's refreshing the add-on also as I expected but function refresh() is not calling.
function callHsapi() {
var API_KEY = "YOUR_HUBSPOT_API_KEY"; // Replace YOUR_HUBSPOT_API_KEY with your API Key
var url = "https://api.hubapi.com/crm/v3/objects/contacts?limit=100&archived=false&hapikey=YOUR_HUBSPOT_API_KEY"; // Replace YOUR_HUBSPOT_API_KEY with your API Key
var response = UrlFetchApp.fetch(url);
var data = JSON.parse(response.getContentText());
var results = data['results'];
var sheet = SpreadsheetApp.getActiveSheet();
var header = ["Email", "First Name", "Last Name", "id"];
var items = [header];
results.forEach(function (result) {
items.push([result['properties'].email, result['properties'].firstname, result['properties'].lastname, result['id']]);
});
sheet.getRange(10,1,items.length,items[0].length).setValues(items);
results.forEach(function (result) {
Logger.log(result['properties']);
});
}
Hello all, i'm trying to get contact properties from HubSpot to Google Spreadsheet, but i have more that 7000+ contacts in hubspot but from the above code i can get maximum 100 contacts, can anyone help me get all the contacts from Hubspot to google spread sheet?, also in the URL if i increase limit=100 i'm getting the error. Any suggestions is appreciated.
thank you.
I've written a custom Google Apps Script that will pull some data (2 columns wide, 50-100 rows long but this varies)in an array 2 from an API, parse it into JSON and then paste into a google sheet.
I can run the script from the editor and it works ok. But when I try to run it from a custom menu or when I run the debugger I get the following error:
'Cannot find method getRange(number,number,(class),number) (line 43)'
Line 43 is the last line of the code.
sheet.getRange(3,1,dataSet.length,2).setValues(rows);
It seems that the issue is that getRange is not able to use the variable of length of the dataset (number of rows) to set the number of rows to use in the range in which the data is to be pasted.
I cannot work out how to fix this - can anyone else see what I am doing wrong? Thanks for taking a look.
//custom menu
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('XXXX Data')
.addItem('Credit Limits','CREDITLIMITS')
.addToUi();
}
function CREDITLIMITS() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //get active spreadsheet
var sheet = ss.getActiveSheet();
// var sheet = ss.getSheetByName('data'); //get sheet by name from active spreadsheet
// URL and params for the API
var USERNAME = 'XXXXXXX';
var PASSWORD = 'XXXXXXXXXXXXX';
var url = 'https://api.XXXX.com/api/v1/XXX/?where=type=%27XXXXXXX%27'; // var url="http://example.com/feeds?type=json"; // Paste your JSON URL here
var authHeader = 'Basic ' + Utilities.base64Encode(USERNAME + ':' + PASSWORD);
var params = {'method': 'GET','muteHttpExceptions': true,'headers': {'Authorization': authHeader,} };
//call the XXXX API
var response = UrlFetchApp.fetch(url, params); // get api endpoint
var json = response.getContentText(); // get the response content as text
var dataAll = JSON.parse(json); //parse text into json
var dataSet = dataAll;
//create empty array to hold data points
var rows=[],
data;
//loop over the retrun events
for (i=0; i < dataSet.length; i++) {
data = dataSet[i];
//push a row of data as 2d array
rows.push([data.company, data.creditLimit]);
}
// clear any previous content
sheet.getRange(1,1,500,10).clearContent();
// write data to sheet
sheet.getRange(3,1,dataSet.length,2).setValues(rows);
}
I've read through all of the relevant pages in the Admin ADK Directory API documentation and several questions on stackoverflow, and I'm still stuck.
I am the super admin of my Google Apps domain, and I want users in my domain to be able to create their own Google Groups. I made a Google Form where the user specifies the name and email of the group. Then the Google Form Responses sheet has an "On form submit" trigger that invokes my code to create the group.
This code works when I run createGroupTest() from the Script Editor. It creates the group in my Google apps domain immediately.
This code does not work when the "On form submit" trigger runs the onFormSubmit(e) function. I get the email from the catch(e) saying Exception: Failed to authenticate for service: Groups.
Does anyone know what is causing the oauth authentication to work from within the Script Editor but not when invoked by the onFormSubmit function?
function onFormSubmitTest() {
var t = new Date();
t = t.getTime();
onFormSubmit([t, "AAA Test Group " + t], ["aaa.testgroup." + t + "#mydomain.com"], ["me#mydomain.com"]);
}
var consumerKey = "mydomain.com";
var consumerSecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
var domainName = "mydomain.com";
function onFormSubmit(e) {
var timestamp = e.values[0];
var groupName = e.values[1];
var groupEmail = e.values[2];
var owner = e.values[3];
owner = owner.split("#")[0];
var description = 'test';
var requestBody = {email: groupEmail, name: groupName, description: description};
var scope = "https://www.googleapis.com/auth/admin.directory.group";
var fetchArgs = googleOAuth_("Groups", scope);
fetchArgs.method = "POST";
fetchArgs.contentType = "application/json";
fetchArgs.payload = JSON.stringify(requestBody);
fetchArgs.muteHttpExceptions = true;
var url = 'https://www.googleapis.com/admin/directory/v1/groups?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
UrlFetchApp.fetch(url, fetchArgs);
}
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name)
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey(consumerKey);
oAuthConfig.setConsumerSecret(consumerSecret);
return {oAuthServiceName:name, oAuthUseToken:'always'};
}
I figured it out: I had failed to include the domain extension in the groupEmail string (because my Google Form only asks the user to fill in the group email name without the domain extension).
I'm having problems saving to google drive after printing a google spreadsheet to pdf.
If i just put the "printurl" string into a browser, it will automatically give me the file. But I want it to be saved to google drive automatically. I've tried this code by borrowing code from other posts that emails a spreadsheet as PDF. But this produces a pdf that is unable to be opened. What am I doing wrong?
function printpdf() {
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var settings = '&fitw=true&portrait=false&exportFormat=pdf&gid=0&gridlines=false';
var printurl = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export? key=' + spreadsheet_id + settings;
var result=UrlFetchApp.fetch(printurl);
var content=result.getContent();
var file=DocsList.createFile("temp",content,"application/pdf");
}
Here is an update to this question under the new oauth2 format.
Printing spreadsheet to PDF then saving file in Drive using OAuth2
You can do it in a much simpler fashion
function printpdf(){
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var spreadsheetFile = DocsList.getFileById(spreadsheet_id);
var blob = spreadsheetFile.getAs('application/pdf');
DocsList.createFile(blob);
}
Note that the DocsList.createFile(blob) works only with Google Apps accounts.
did you mean it like that?
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = getConfig(SHEET_NAME_CELL);
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!dataSheet) {
Browser.msgBox("Can't find sheet named:" + sheetName);
return;
}
var dataSheetIndex = dataSheet.getSheetId();
//this is three level authorization
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
//even better code
//oauthConfig.setConsumerKey(ScriptProperties.getProperty("consumerKey"));
//oauthConfig.setConsumerSecret(ScriptProperties.getProperty("consumerSecret"));
var requestData = {
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + id + "&gid=" + dataSheetIndex + "&fitw=true&size=A4&portrait=true&sheetnames=false&printtitle=false&exportFormat=pdf&format=pdf&gridlines=false";
//Save File to Google Drive
var seplogoBlob = UrlFetchApp.fetch(url, requestData).getBlob().setName("Filename.pdf");
DocsList.createFile(seplogoBlob);