Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been doing some research and for some reason can't find a good example showing this anywhere, and I am starting to wonder if it's even possible.
What's I'm looking to do is to have my extension write data within a Google Spreadsheet, so that the sheet is being used as a database.
Does anyone have any documentation that I could follow through? Considering that the Spreadsheet API doesn't seem to allow JavaScript, is that even possible?
THanks.
Yes, it is definitely possible. I have used the Spreadsheet API extensively using Javascript. You'll need to use the Protocol version of the API as documented here: https://developers.google.com/google-apps/spreadsheets/
This requires sending signed requests using OAuth2 (the older auth protocols aren't really reliable anymore.) so I suggest using an OAuth2 library like JSO.
https://github.com/andreassolberg/jso
When writing your javascript you'll need to write functions that create an XML string to interface with the Protocol API. Parsing the responses is pretty straight forward. I've included a snippet of the code I've used. You can also see my answer to a related question using JQuery here. JQuery .ajax POST to Spreadsheets API?
function appendSpreadsheet(){
//Constructs the XML string to interface with the Spreadsheet API.
//This function adds the value of the param foo to the cell in the first empty row in the column called 'columnTitle'.
//The Spreadsheet API will return an error if there isn't a column with that title.
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">',//'--END_OF_PART\r\n',
'<gsx:columnTitle>',foo,'</gsx:columnTitle>',//'--END_OF_PART\r\n',
'</entry>'].join('');
return atom;
};
var params = {
'method': 'POST',
'headers': {
'GData-Version': '3.0',
'Content-Type': 'application/atom+xml'
},
'body': constructAtomXML(foo)
};
var docId //Get this from the spreadsheet URL or from the Google Drive API.
var worksheetId = 'od6'; //The worksheet Id for the first sheet is 'od6' by default.
url = 'https://spreadsheets.google.com/feeds/list/'+docId+'/'+worksheetId+'/private/full';
sendSignedRequest(url, handleSuccess, params); //Use your OAuth2 lib
}
I think you are having same question which I had some months ago. I was looking for some library to do same but couldn't found any so I end up with creating one called gsloader. I am using this library in this jiraProgressTracker chrome extension. Chrome extension is under development but gsloader library is ready to use.
Here is what you need to do.
Create a google cloud project under this, https://cloud.google.com/console#/project. Be patient, it will take some time.
Under "Registered Apps", do not delete the "Service Account - Project".
Under "Registered Apps", register a new app, choose platform web application.
Under "APIs", select "Drive API".
In newly created app, paste your chrome application url(like chrome-extension://) for "web origin"
Copy "client id" from OAuth 2.0 Client ID from app created in step 3
Add gsloader library, into you html page. It needs require.js and js-logger and jQuery. If you can't use requirejs, please let me know I will try to create library by removing requirejs dependency, though it may take more time for me to do it.
Following is some code snippet to go with.
// Do Authorization
var clientId = "<your client id>";
GSLoader.setClientId(clientId);
// Load existing spreadsheet
GSLoader.loadSpreadsheet("spreadsheet id");
// Create spreadsheet
GSLoader.createSpreadsheet("spreadsheet id")
There are enough methods and objects available to work with, rather than mentioning all here I will try to make documentation available.
Please let me know, how does it works with you overall.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm making a website and there is a page on said website which I would like only certain people to access, with a password. I was wondering the best way to go about it simply and securely, and would love some example code if any exists.
To clarify, I would like to add a feature to a page on my website which prevents anyone visiting the site from going to that page unless they enter a password. I'm mostly looking for HTML, JS, or JQuery solutions, as this is only going to be for the users of the website.
The simplest way that I've come across is using an htpasswd file (which looks very similar to /etc/passwd if you are familiar with that), then setting up your webserver to point at it.
# create htpasswd file
htpasswd -c /path/htpasswd
# add user to htpasswd file (you'll be prompted for password)
htpasswd /path/htpasswd loginuser
Within your nginx.conf , set it up like this
server {
listen 80 yourserver;
listen [::]80 yourserver ipv6only=on;
root /var/www/yourserver;
index index.html;
location /public {
# ...
}
# everything under /private requires a login
location /private {
auth_basic "Restricted Content";
auth_basic_user_file /path/htpasswd;
}
}
There's a really good tutorial on this setup, that I shamelessly robbed for this answer here:
https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04
Then for anything over/above that, nginx's documentation is excellent as well (if that is the webserver you are using).
https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
One trap with this setup is that nginx only allows password hashes that are supported by your operating system's crypt module. So linux for example wouldn't necessarily have bcrypt, but most of the BSDs would. You can find what your OS's crypt module supports using man crypt .
|
If you're looking for something where you have a little more control, you can have a URL that you GET a website with form data, which POSTs the login information to a URL you can handle the login details yourself. This is python/flask - I'm not sure it is what you are looking for bsaed on your tags but it may still be helpful.
https://pythonspot.com/login-authentication-with-flask/
I hope this was helpful :) good luck!
Depending on what frameworks, applications etc. you are using to create your website, and If you want create an account system or just a protected area, there are many different ways.
1. .htaccess:
Assuming you are using a NCSA-compatible webserver such as apache and want to restrict access to a certain path, the simplest (yet by far not safest) way to do that would be to use a simple .htaccess-file.
simply put a file with that exact name into the folder you want to protect with following content:
AuthType Basic
AuthName "Enter Credentials Here"
AuthUserFile /full/path/to/.htpasswd
Require valid-user
and create a .htpasswd file in a safe place containing
username:password
or, if you care about people hacking your server getting the password:
username:hash
you can generate hashes using online-.htpasswd-generators.
Make sure to enter the path to your .htpasswd correctly into your .htaccess!
The .htaccess file will make the server ask for basic username/password authentication, show the message "Enter Credentials Here" to the user and require the users browser to send any valid credentials to your server. Valid credentials mean any username/password-pair in your .htpasswd file. Just know that the user's browser will always send the credentials to your server unencrypted, so make sure to enable https, if you care about the password not being stolen from your users. And tell them not to write it down etc. basic password safety.
2. Fancy Account System using SQL
This is more complicated an probably not what you want, so I will just give basic advice: Read about sql injection and make sure you fully understand it and how to avoid it. Read about password hashing and salting. Read about safe passwords (phrases) to advice your users. Read about html forms and how to parse them using your framework. Read about encryption. Then create a concept that fits your needs and implement it.
If you are using PHP then this is simple solution:
<?php
if(!isset($_POST["password"])){
header("location:pwdnotcorrect.php");
return;
}
$pwd=$_POST["password"];
if($pwd!="yourpassword"){
header("location:pwdnotcorrect.php");
return;
}?>
<!--Your HTML Code starts here--->
Send POST request with password to this page using form
If password not correct then this page redirect you to new page.
I am setting up a spreadsheet whose users do not necessarily have a Google account nor should be required to log in.
I would like to interact with users in two ways that are possible with the Browser class. One is displaying an alert in a pop-up window, in order to warn users not to edit a field. This is done with Browser.msgBox or ̀€ui.alert. The second thing is requesting an input in a window, which is done nicely with Browser.inputBox().
While my code works fine when I am logged in as owner, it is useless when edited by an unregistered user.
Can I make those function work for unregistered users and if so, how?
Otherwise, are there workarounds to achieve similar functionalities?
Here is a minimal example of what I did:
function onEdit(event) {
var ss = SpreadsheetApp.getActiveSheet();
var eventRange = event.range;
var eventRow = eventRange.getRow();
var eventCol = eventRange.getColumn();
if(eventCol == 1){
protectDateField(ss, eventRow, eventCol)
}
}
function protectDateField(ss, eventRow, eventCol){
var ui = SpreadsheetApp.getUi();
ui.alert("Do Not Edit This Field!");
ss.getRange(eventRow,eventCol).clearContent();
}
Short answer
What you want to do it's not possible on Google Sheets.
Explanation
To run a script bounded to a spreadsheet the user should be an editor for that spreadsheet.
Simple triggers can't access services that require authorization to run.
Some additional restrictions apply when triggers are triggered by anonymous users.
NOTES:
The required authorization scopes by each method are included on the documentation section for each method.
Anonymous users can't authorize scripts to be ran by installable triggers as the authorization process requires a usar account to log the respective authorization.
For further details see:
https://developers.google.com/apps-script/guides/sheets
https://developers.google.com/apps-script/guides/triggers
Workarounds
There is no way to achieve the desired functionality by solely using Google Sheets, but you could
create a web app by using Apps Script and embed on it a spreadsheet
create a web app by using another platform and embed on it spreadsheet
I am trying to use Twitter Pin-based authorization in my Google Apps Script to eventually send tweets on behalf of other uses.
I freely admit that I don't relay know what I'm doing but I have read a lot of info on the internet and feel I have tried everything.
My current Google Apps Script JavaScript code:
var method = 'post';
var url = 'https://api.twitter.com/oauth/request_token';
var consumerKey = '[my consumer key]';
var ticks = '1422745454';
var nonce = '6826266';
var options = {
'method': method,
'oauth_callback': 'oob',
'oauth_consumer_key': consumerKey,
'oauth_nonce': nonce,
'oauth_signature': 'cIFeptE5HjHp7xrp%2BZt9xFhHox4%3D',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': ticks,
'oauth_version': '1.0'
};
var response = UrlFetchApp.fetch(url, options);
For testing I set the ticks just before each test run to the value here
The nonce is a random number between 111111 and 9999999 which is regenerated before each test run.
The oauth signature I have been generating with some c# code lifted from the linq2twitter project
I suspect the problem is the signature. I have read the twitter documentation on creating a signature and I think the C# code is doing it correctly but I am not sure.
The problem is that whatever I try I always get this error:
"Request failed for https://api.twitter.com/oauth/request_token returned code 401. Truncated server response: Failed to validate oauth signature and token (use muteHttpExceptions option to examine full response)"
I have been trying to find an example of Twitter Pin-based authorization in a Google Apps Script but have so far not found anything.
My attempts to translate examples in C#, PHP, etc. have also failed.
Please help.
Apps Script provides an Oauth API that works with UrlFetchApp, they even use twitter in their examples. Work with those if at all possible, troubleshooting signature generation is a real hassle.
https://developers.google.com/apps-script/reference/url-fetch/o-auth-config
https://developers.google.com/apps-script/articles/twitter_tutorial
If you absolutely must do it from scratch, the best approach is to get requests working with an existing library (like the c# one you mention), then work on getting your apps script to generate the exact same request.
I get the sense that is what you are doing now, so it may just be a matter of base64 encoding your Signature in the outgoing request:
https://developers.google.com/apps-script/reference/utilities/utilities#base64Encode(String)
Ultimately, it's very difficult to do the whole Oauth process manually in Apps Script. When I tried something like this from scratch about a year ago I ultimately gave up and used a Python application deployed to Google App Engine instead. I submit requests from Apps Script to the App Engine application, and the App Engine application handles Oauth and relays my requests on to the external service, before returning requests to my Apps Script. This approach comes with complications of it's own.
I'm trying to figure out a way to display data collected from Google Analytics on my web site. I'm using NopCommerce, and I want to display this information/statistics in a view in the Admin Section.
There might be many ways to achieve this, and after searching the web I found some examples using JavaScript, but I couldn't find a good tutorial for this.
I have also looked into integrating Google Analytics with C#, and I found this example: http://biasecurities.com/2012/02/using-the-google-analytics-api-with-asp-net-mvc/#comment-1310
A demo project can be downloaded from GitHub here: https://github.com/jgeurts/Analytics-Example
However the demo project doesn't seem to work as the google URL (https://www.google.com/analytics/feeds/accounts/default) is no longer in use.
As I'm using a MVC application it would be preferable to make this happen by applying the Google Analytics logic within a Controller and displaying it in a view. Or something like that.
Google provides a query tool to experiment with here, so it shouldn't be to hard extracting data from Google Analytics and display the data on the website: https://ga-dev-tools.appspot.com/explorer/
Has anyone been able to successfully display Google Analytics data on their website?
In case some one else is having the same problem here's what I did and it pretty much answers the question.
1.
Here is the basic code for a API client that access data from Google Analytics via your Google Service Account. https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account
In order to make this application work you need to have several things ready before you start coding.
*Google Analytics Account - once registered a "tracker" code is generated for you to put on each webpage you want to track. You may not see any statistics right away and it can take up to 24h before any statistics are shown in the Google Analytics Dashboard.
An OAuth Authorisation (API-Key) with CLIENT_ID, CLIENT SECRET and EMAIL ADRESS (This is not your normal email but a service account email that is created for you when you make an OAuth Authorisation).
console.developers.google.com/
A serverkey, can also be created here: console.developers.google.com/.
You can also create a browser key, haven't bothered with that though and don't know what it does.
Finally you need a certificate key. Your application will only be able to access your Google Analytics account by using the key and credentials. The key is an encrypted p.12 file. You can find the key in https://code.google.com/apis/console/.
Here is a guide for the key: http://www.pimcore.org/wiki/display/PIMCORE/Setup+Google+Analytics+Reporting+with+OAuth2+Service+Accounts+(since+1.4.6)
2.
Now that you have all keys and credentials you need it is time to start looking at the code I linked in "1". Here is the basic for it again: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account
Create a console application and implement the code above.
Note: your not making a "Google Plus service" so you have to change those parts for "AnalyticsService". Go to manage nuget and install packages:
Google Apis Core Library
Google Apis Client Library
Google Apis Auth Client Library
Google Apis Analytics.v3 Library
Google GData Client (This provides properties used to query data, metrics, demensions etc)
Google GData Extensions Library
Analytics
Might forgot something but here are the namespaces I use:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Analytics.v3;
3
Finally, here's is some of my code. Note I'm creating a new Analytics as supposed to "new ServiceAccountCredentials" as in the code from Google. That's the main difference:
Retrieve data from Google Analytics API with .NET, multiple metrics?
With this I'm able to access and query data from Google Analytics account. The best part is that you don't have to log in to Google for this as the key and credentials gives you access to the account data directly.
I will migrate this code to MVC now I might make an update later on for how to implement this Analytics client in Mvc.
This document explains how to get Google Access tokens and use them to get Google Analytics data to be displayed in our websites.
Example: A live example is available in
https://newtonjoshua.com
Note: Use the same Gmail account for all the below steps.
STEP 1: Set Up Google Analytics
Follow the below steps to set up Google Analytics on your website
Sign in to your Analytics account.
Select the Admin tab.
Select an account from the drop-down menu in the ACCOUNT column.
Select a property from the drop-down menu in the PROPERTY column.
Under PROPERTY, click Tracking Info -> Tracking Code.
To collect data, you must copy and paste the Analytics tracking code
into the source code on every web page you wish to track.
Once you have the JavaScript tracking code snippet for your
property, copy the snippet exactly without editing it.
Paste your tracking code snippet (unaltered, in its entirety) before
the closing </head> tag on every web page on your site you wish to
track.
Once you have successfully installed Analytics tracking, it may take
up to 24 hours for data such as traffic referral information, user
characteristics, and browsing information to appear in your reports
Refer to:
https://support.google.com/analytics/answer/1008080?hl=en
https://analytics.google.com
STEP 2: Get Tokens
Google Project:
To create a Google Cloud Platform project, open the Google Developers Console (https://console.developers.google.com) and click Create Project.
Enable OAuth 2.0 API access:
Your application will need to access user data and contact other Google services on your behalf. Use OAuth 2.0 to grant your app API access.
To enable that, you need a client ID:
Open the Google API Console Credentials page (https://console.developers.google.com/apis/credentials).
From the project, drop-down and select your project.
Select Create credentials and choose OAuth client ID.
Under Application type, select Web application, enter a Name and
set the Restrictions by entering JavaScript origins, Redirect URIs to point the website where you are planning to display the data, and then click Create.
Make note of the OAuth 2.0 client_id and client_secret. You will need them to configure the UI.
Get Authorization code:
Enter in browser:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&client_id={{
client_id}}&redirect_uri={{redirect_uri }}
&approval_prompt=force&access_type=offline
You will get redirected to
{{redirect_uri }}?code=={{authorization_code}}#
Get Refresh Token:
Send a POST request, possibly via a REST console to
https://www.googleapis.com/oauth2/v3/token?code={{authorization_code}}
&client_id={{client_id}}&client_secret={{client_secret}}
&redirect_uri={{redirect_uri }}&grant_type=authorization_code
You will get a JSON response with
{"refresh_token": refresh_token}
You can use the refresh token to get access token to access to Google APIs.
Get the Access Token:
Send a POST request to,
https://www.googleapis.com/oauth2/v3/token?client_id={{client_id}}
&client_secret={{client_id}}
&grant_type=refresh_token&refresh_token={{refresh_token}}
You will get a JSON with access_token in the response.
{access_token: {{access_token}}}
Example:
var access_token = '';
function getAccessToken(){
$.post('https://www.googleapis.com/oauth2/v3/token', {
client_id: {{client_id}},
client_secret: {{client_secret}},
grant_type: 'refresh_token',
refresh_token: {{refresh_token}}
}, function (data, status) {
if (status === 'success') {
access_token = data.access_token;
// Do something eith the access_token
}
else {
console.error(status);
}
});
}
Check Token validity:
Send a POST request to,
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={{access_token}}
Example:
function checkValidity() {
$.post('https://www.googleapis.com/oauth2/v1/tokeninfo', {
access_token:{{access_token}}
}).done(function (data, status) {
if (status === 'success') {
console.debug(data.expires_in);
var check = false;
check = data.hasOwnProperty('expires_in');
if (check) {
// Token is valid
}
if (!check) {
getAccessToken();
}
}
else {
console.debug(status);
}
})
.fail(function (data) {
console.error(data);
getAccessToken();
});
}
Step 3: Fetch Data
Embed API:
The GA Embed API is a JavaScript library that allows you to easily create and embed your GA dashboard on your website in a matter of minutes.
Refer to https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started.
Query Explorer:
Visit Embed API Query Explorer and authorize
https://ga-dev-tools.appspot.com/query-explorer/
Select the view for which you want to fetch the data.
Select the required metrics and dimensions.
Example:
Get Country Data (I want to know the number of users accessing my website from each country).
To get that data, select the metrics as 'users' and the dimensions as 'country'.
Click on Run Query.
You will find the analytics data for the query displayed in a table.
Copy the API Query URI. And add access_token={{access_token}} to the URI.
Example:
https://www.googleapis.com/analytics/v3/data/ga?ids={{ids}}&start-date=2015-07-01&end-date=today&metrics=ga%3Ausers&dimensions=ga%3Acountry&access_token={{access_token}}
Send POST request to the URIs to get the data in your browser.
Example:
function gaGetCountry() {
$.get('https://www.googleapis.com/analytics/v3/data/ga?' +
'ids={{ids}}' +
'start-date=2015-07-01&' +
'end-date=today&' +
'metrics=ga%3Ausers&' +
'dimensions=ga%3Acountry&' +
'sort=ga%3Ausers&' +
'filters=ga%3Ausers%3E10&' +
'max-results=50' +
'&access_token=' + {{access_token}},
function (data, status) {
if (status === 'success') {
// Display the Data
drawRegionsMap(data.rows);
} else {
console.debug(status);
}
});
}
Step 4: Display Data
Now we have gathered the data. Finally we have to display them on our website.
"Display live data on your site" is the title of Google Charts. And that is what we are going to do.
Refer to https://developers.google.com/chart/.
The following example will draw a GeoChart in the div with id='countryChart'.
// Draw country chart
function drawRegionsMap(data) {
var head = data[0];
head[0] = 'Country';
head[1] = 'Users';
for (var i = 1; i < data.length; i++) {
var d = data[i];
d[1] = Number(d[1]);
}
var chartData = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Website is viewed from,',
domain: '{{Country Code eg: IN for India}}',
tooltip: {
textStyle: {
color: 'navy'
},
showColorCode: true
},
legend: {
textStyle: {
color: 'navy',
fontSize: 12
}
},
colorAxis: {
colors: ['#00FFFF', '#0000FF']
}
};
var chart = new google.visualization.GeoChart(document.getElementById('countryChart'));
chart.draw(chartData, options);
}
Refer to https://newtonjoshua.com to view the above example in action.
I'd recommend to use the new Google APIs Client Library for .NET (currently in beta). Information about the Analytics API can be found here. Note that the Client Library for .NET (google-api-dotnet-client) supersedes the .NET library for the Google Data API (google-gdata).
Unfortunately, there is no sample code available yet from Google (see this issue) but this question on SO should help.
If you don't want to login every time you access Analytics data, you can use OAuth 2.0 authorization with offline access. You have to grant initial access to your web application, though. This requires you to login once but you can use a refresh token later on.
To date, the easiest solution is to create a report of your Google Analytics data in Google Data Studio (free, native connector to GA), and share that report to embed in an <iframe>
See details on https://support.google.com/datastudio/answer/7450249?hl=en
You get
flexible vizualisation
security and control on the data being shared
0 code nor maintenance
result is being cached for better performance
I spent a couple of days trawling the Internet to get some sample ASP.NET code with no luck. I used Koffe14's method for authentication, and also Linda Lawton's excellent ASP.NET analytics example.
I've posted the code on my website. It's not MVC, but it might help other people who need to get data from Google analytics into an ASP.NET web page using the v3 Google API.
Check out embeddedanalytics.com (disclaimer - I work with them).
This is a simple yet powerful solution geared for people that don't want deal with learning the GA API and then having to link it to visualization (e.g. charts/graphs).
Basically define your charts and embed a snippet of code where you want the chart to show. We also support mechanisms so that it is easy to integrate into a custom built CMS or other web portal.
I coach a sports team and set up a website for it. I would like to add a button to an admin page which I can click to quickly send an email to everyone on the team. This email will say something like: "Today's schedule has changed, please visit the website for more info."
I am sure this could be achieved easier though a distribution list in outlook or something, but I want to use, and get a better understanding of, Google Apps Script.
I have a Google Spreadsheet with the email addresses and a simple script function which sends the email.
This works great when I click to run it inside the script editor, but is there a way to call this from an external website with a button and some JavaScript?
You need to create a Google UI object that you can embed in your site - you'll do this by creating a Script that you will deploy as a web app. (Refer to Google Apps Script - Web Apps.) That object will contain a button that will invoke your existing script function to send the email.
Publish your web app to execute as you. For your specific situation, you will also want to have access to the app limited to you. That will mean that the UI Blob you create will not function for the general public. This is very incomplete, but produces a blob with a single button that will trigger your script:
function doGet() {
var app = UiApp.createApplication();
var button = app.createButton('Send Schedule Change Email');
app.add(button);
var handler = app.createServerHandler('myClickHandler');
button.addClickHandler(handler);
return app;
}
function myClickHandler(e) {
var app = UiApp.getActiveApplication();
// Call your library function, e.g.
TeamSpreadsheet.sendScheduleChanged();
var label = app.createLabel('Message Sent')
.setId('statusLabel')
.setVisible(false);
label.setVisible(true);
app.close();
return app;
}
Your web app will need to have access to your existing script, which I assume is embedded in your spreadsheet. This is accomplished by first saving a version of your existing script (File - Manage Versions), then adding it as a library to your new web app script (Resources - Manage Libraries). Read more about libraries here. Since your web app will run as you, you can keep your spreadsheet private.
Caveats
The utility script in your library will need to open your spreadsheet in a way that will work from outside of the sheet; use SpreadsheetApp.openById(), rather than SpreadsheetApp.getActiveSpreadsheet(). Unfortunately, openById pukes when you use it to open the host spreadsheet, so you'll want something like this:
var ss = null;
try {
// This works for scripts running in the host spreadsheet
ss = SpreadsheetApp.getActiveSpreadsheet();
} catch(err) {
try {
// This works for web apps
ss = SpreadsheetApp.openById("SPREADSHEET ID");
} catch(err) {
Logger.log("Could not open source spreadsheet.");
// Well, then, not much sense carrying on, is there?
return;
}
}
SpreadsheetApp.setActiveSpreadsheet(ss);
...
In fact, watch for any reliance on calls to get info from "active" objects. You may need to do some gymnastics to get around them.
I've found debugging this type of arrangement to be painful, since the app-script debugger often reports "Server Errors" when you try to trace into a library routine.
I hope that helps gets you started!
As a complement to Mogsdad's answer (that was quite complete and interesting) I'd say that your case could be a bit simpler since you have already a working script.
Take your script and add a doGet() function like in Mogsdad example, define a handler on the button that will call your existing function you wrote to send mails, in this function replace the getActiveSpreadsheet() by SpreadsheetApp.OpenById("the ID of the SS") and the getActiveSheet() by OpenByName() and you're done with the modifications.
After that follow Mogsdad instructions : deploy the script as a webapp running as you and use the provided url to access it from a link on your site.
If you want not to take any risk, do all these changes on a copy of your original spreadsheet so you always keep a working model at hand.
If you want more accurate advice (or if you meet some difficulties) feel free to show your existing script to get some help with the modifications.
PS : please consider this as a simple comment, written in an answer for the comfort of formating
Just publish your script as web application and upon a button click, excecute:
window.open("https://script.google.com/macros/s/<id>/exec");
Don't know if this was possible a year ago.