-
Notifications
You must be signed in to change notification settings - Fork 22
/
Code.gs
314 lines (264 loc) · 10.1 KB
/
Code.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
* ###########################################################################
* # Name: Hubspot Automation #
* # Description: This script let's you connect to Hubspot CRM and retrieve #
* # its data to populate a Google Spreadsheet. #
* # Date: March 11th, 2018 #
* # Author: Alexis Bedoret #
* # Detail of the turorial: https://goo.gl/64hQZb #
* ###########################################################################
*/
/**
* ###########################################################################
* # ----------------------------------------------------------------------- #
* # ------------------------------- CONFIG -------------------------------- #
* # ----------------------------------------------------------------------- #
* ###########################################################################
*/
/**
* Fill in the following variables
*/
var CLIENT_ID = '';
var CLIENT_SECRET = '';
var SCOPE = 'contacts';
var AUTH_URL = "https://app.hubspot.com/oauth/authorize";
var TOKEN_URL = "https://api.hubapi.com/oauth/v1/token";
var API_URL = "https://api.hubapi.com";
/**
* Create the following sheets in your spreadsheet
* "Stages"
* "Deals"
*/
var sheetNameStages = "Stages";
var sheetNameDeals = "Deals";
var sheetNameLogSources = "Log: Sources";
var sheetNameLogStages = "Log: Stages";
/**
* ###########################################################################
* # ----------------------------------------------------------------------- #
* # --------------------------- AUTHENTICATION ---------------------------- #
* # ----------------------------------------------------------------------- #
* ###########################################################################
*/
/**
* Authorizes and makes a request to get the deals from Hubspot.
*/
function getOAuth2Access() {
var service = getService();
if (service.hasAccess()) {
// ... do whatever ...
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
getService().reset();
}
/**
* Configures the service.
*/
function getService() {
return OAuth2.createService('hubspot')
// Set the endpoint URLs.
.setTokenUrl(TOKEN_URL)
.setAuthorizationBaseUrl(AUTH_URL)
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(SCOPE);
}
/**
* Handles the OAuth2 callback.
*/
function authCallback(request) {
var service = getService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied.');
}
}
/**
* Logs the redict URI to register.
*/
function logRedirectUri() {
Logger.log(getService().getRedirectUri());
}
/**
* ###########################################################################
* # ----------------------------------------------------------------------- #
* # ------------------------------- GET DATA ------------------------------ #
* # ----------------------------------------------------------------------- #
* ###########################################################################
*/
/**
* Get the different stages in your Hubspot pipeline
* API & Documentation URL: https://developers.hubspot.com/docs/methods/deal-pipelines/get-deal-pipeline
*/
function getStages() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer ' + service.getAccessToken()}};
// API request
var pipeline_id = "default"; // Enter your pipeline id here.
var url = API_URL + "/crm-pipelines/v1/pipelines/deals";
var response = UrlFetchApp.fetch(url, headers);
var result = JSON.parse(response.getContentText());
var stages = Array();
// Looping through the different pipelines you might have in Hubspot
result.results.forEach(function(item) {
if (item.pipelineId == pipeline_id) {
var result_stages = item.stages;
// Let's sort the stages by displayOrder
result_stages.sort(function(a,b) {
return a.displayOrder-b.displayOrder;
});
// Let's put all the used stages (id & label) in an array
result_stages.forEach(function(stage) {
stages.push([stage.stageId,stage.label]);
});
}
});
return stages;
}
/**
* Get the deals from your Hubspot pipeline
* API & Documentation URL: https://developers.hubspot.com/docs/methods/deals/get-all-deals
*/
function getDeals() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer ' + service.getAccessToken()}};
// Prepare pagination
// Hubspot lets you take max 250 deals per request.
// We need to make multiple request until we get all the deals.
var keep_going = true;
var offset = 0;
var deals = Array();
while(keep_going)
{
// We'll take three properties from the deals: the source, the stage & the amount of the deal
var url = API_URL + "/deals/v1/deal/paged?properties=dealstage&properties=source&properties=amount&limit=250&offset="+offset;
var response = UrlFetchApp.fetch(url, headers);
var result = JSON.parse(response.getContentText());
// Are there any more results, should we stop the pagination ?
keep_going = result.hasMore;
offset = result.offset;
// For each deal, we take the stageId, source & amount
result.deals.forEach(function(deal) {
var stageId = (deal.properties.hasOwnProperty("dealstage")) ? deal.properties.dealstage.value : "unknown";
var source = (deal.properties.hasOwnProperty("source")) ? deal.properties.source.value : "unknown";
var amount = (deal.properties.hasOwnProperty("amount")) ? deal.properties.amount.value : 0;
deals.push([stageId,source,amount]);
});
}
return deals;
}
/**
* ###########################################################################
* # ----------------------------------------------------------------------- #
* # -------------------------- WRITE TO SPREADSHEET ----------------------- #
* # ----------------------------------------------------------------------- #
* ###########################################################################
*/
/**
* Print the different stages in your pipeline to the spreadsheet
*/
function writeStages(stages) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetNameStages);
// Let's put some headers and add the stages to our table
var matrix = Array(["StageID","StageName"]);
matrix = matrix.concat(stages);
// Writing the table to the spreadsheet
var range = sheet.getRange(1,1,matrix.length,matrix[0].length);
range.setValues(matrix);
}
/**
* Print the different deals that are in your pipeline to the spreadsheet
*/
function writeDeals(deals) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetNameDeals);
// Let's put some headers and add the deals to our table
var matrix = Array(["StageID","Source", "Amount"]);
matrix = matrix.concat(deals);
// Writing the table to the spreadsheet
var range = sheet.getRange(1,1,matrix.length,matrix[0].length);
range.setValues(matrix);
}
/**
* ###########################################################################
* # ----------------------------------------------------------------------- #
* # -------------------------------- ROUTINE ------------------------------ #
* # ----------------------------------------------------------------------- #
* ###########################################################################
*/
/**
* This function will update the spreadsheet. This function should be called
* every hour or so with the Project Triggers.
*/
function refresh() {
var service = getService();
if (service.hasAccess()) {
var stages = getStages();
writeStages(stages);
var deals = getDeals();
writeDeals(deals);
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
/**
* This function will log the amount of leads per stage over time
* and print it into the sheet "Log: Stages"
* It should be called once a day with a Project Trigger
*/
function logStages() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Stages: Count");
var getRange = sheet.getRange("B2:B12");
var row = getRange.getValues();
row.unshift(new Date);
var matrix = [row];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Log: Stages");
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
// Writing at the end of the spreadsheet
var setRange = sheet.getRange(lastRow+1,1,1,row.length);
setRange.setValues(matrix);
}
/**
* This function will log the amount of leads per source over time
* and print it into the sheet "Log: Sources"
* It should be called once a day with a Project Trigger
*/
function logSources() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sources: Count & Conversion Rates");
var getRange = sheet.getRange("M3:M13");
var row = getRange.getValues();
row.unshift(new Date);
var matrix = [row];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Log: Sources");
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
// Writing at the end of the spreadsheet
var setRange = sheet.getRange(lastRow+1,1,1,row.length);
setRange.setValues(matrix);
}