forked from RitwikGA/FacebookReportingTool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode.gs
3054 lines (2693 loc) · 100 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Facebook Reporting & Cost Data Upload in Google Analytics
* Description: Exports Facebook Ads Data in Google Sheets & Uploads it To Google Analytics.
* @Ritwikga www.Digishuffle.com
*
* Updated: 21-05-2019
* - Breakdown Feature
* - Data Import Alerts
* - UI Improvements & Bug Fixes
*
* Recent Updates @https://github.com/RitwikGA/FacebookReportingTool/
*/
///// Facebook Details ///////
var CLIENT_ID = ''; // Insert App ID
var CLIENT_SECRET = ''; // Insert App Secret
var FB_AD_ACCOUNT_ID = ''; //Ad Account Id
// More fields at https://developers.facebook.com/docs/marketing-api/insights/parameters
var FB_FIELDS = 'campaign_name,clicks,spend,impressions,date_start';
// More brekadowns at https://developers.facebook.com/docs/marketing-api/insights/breakdowns
var FB_BREAKDOWN = '';
var FB_LEVEL = 'campaign'; // ad,adset,campaign,account
var pos = [1,1] //Spreadsheet Cell Position
// More DATE_RANGE at https://developers.facebook.com/docs/marketing-api/insights/parameters (date_preset paramteter)
var DATE_RANGE='last_7d'; //today, yesterday, this_month, last_month, this_quarter, etc
// To use below date range, make sure DATE_RANGE='' //
var start_date='2019-01-01'; // custom date range
var end_date='2019-01-30';
var splitByDate = false;
var limit = 100; //Facebook Graph API Limit per request
// Facebook Ad URL UTMs values (Only for GA Upload Format) //
var isGaUpload = false // set to True, to export GA upload compatible data
var SOURCE = "facebook" // source, if not specified in Facebook Tracking URL Params utm_source
var MEDIUM = "cpc" // medium, if not specified in Facebook Tracking URL Params utm_medium
// Google Analytics Data (Only for GA Upload Format) //
var ACCOUNT_ID = ""; //Account ID
var PROPERTY_ID = ""; //Property ID
var DATASET_ID = ""; //Data set upload ID
// CurrenyMultiplier (Only for GA Upload Format) //
var currenyMultiplier = 1; //Will Multipy 'Spend' Field. (Currency converter only for GA upload)
//// Emailers (Only for GA Upload Format)////////////
var isEmail = false // Will Send Email To Provide Status Of Upload (During Automation)
var subject = '' // Enter Subject Line For Email Else It Fallback To "Facebook Data Upload To GA(ACCOUNTID)"
/**
*
* Input Variable Values Ends
*
*/
////// ACCOUNTDATA Literal ////////////////////
var ACCOUNTDATA = {
adAccountUIFields : ['account_currency','account_id','account_name','ad_name','adset_name','campaign_name','clicks','impressions','cpc',
'cpm','date_start','date_stop','reach','spend','unique_clicks'],
/// The Columns To Be Populated in the Fields Box in the UI.
adAccountLevels : ['ad','adset','campaign','account'], /// The Columns To Be Populated in the Fields Box in the UI.
adAccountBreakdowns : ['age','country','gender','impression_device','product_id','region','dma','frequency_value','hourly_stats_aggregated_by_advertiser_time_zone',
'hourly_stats_aggregated_by_audience_time_zone','publisher_platform','platform_position','device_platform'],
getUIFields : function(y) {return y.map(function(i){return {id:i,text:i.split('_').map(function(j){return j.charAt(0).toUpperCase()+j.slice(1)}).join(' ')}})},
getUIHeaders : function(k){return k.map(function(i){return i.split('_').map(function(j){return j.charAt(0).toUpperCase()+j.slice(1)}).join(' ')})},
facebookData : {facebookAccountId:FB_AD_ACCOUNT_ID,
facebookLevel:FB_LEVEL,
facebookFields:FB_FIELDS,
facebookBreakdowns:FB_BREAKDOWN},
dateData : {
preDefinedRage: DATE_RANGE,
startDate : start_date,
endDate: end_date,
splitByDate:splitByDate
},
additionalData: {
isGaUpload:isGaUpload,
source:SOURCE,
medium:MEDIUM,
pos:pos,
limit:limit
}
}
function showBar() {
var html=HtmlService.createTemplateFromFile('digiSideBar').evaluate().setTitle("Facebook Reporting Tool").setWidth(300)
SpreadsheetApp.getUi().showSidebar(html)
}
function facebookData()
{ makeRequest(ACCOUNTDATA) }
function uploadDataToGa()
{ uploadData(ACCOUNT_ID, PROPERTY_ID, DATASET_ID) }
function onOpen() {
SpreadsheetApp.getUi().createMenu('Reports').addSubMenu(SpreadsheetApp.getUi()
.createMenu('Facebook').addItem("Open Sidebar", 'showBar').addSeparator().addItem("Authorize", 'fbAuth').addItem("Log Out", 'reset').addItem("Export Data", 'facebookData').addItem("Upload Data To GA", 'uploadDataToGa'))
.addSeparator().addItem("oAuth Redirect URI", 'getValidOauthRedirectUrl').addToUi();
}
function fbAuth(){
var UI=HtmlService.createTemplate("<b><a href='<?=getService().getAuthorizationUrl()?>' target='_blank'>Click To Authorize</a></b><br /><? if(getService().hasAccess())"+
"{ ?> <?!= <p><span style='color:green'>Authorized Successfully</span></p> } else {?> <?!= <p><span style='color:red'>Not Authorized</span></p> }").evaluate()
SpreadsheetApp.getUi().showModalDialog(UI, "Facebook Authorization")
}
function jsonToQuery(param)
{
var str = "";
for (var key in param) {
if (str != "") {
str += "&";
}
str += key + "=" + param[key];
}
return str
}
function getValidOauthRedirectUrl(){
var validOauthUrl = Utilities.formatString('https://developers.facebook.com/apps/%s/fb-login/settings/', CLIENT_ID)
var htmlOutput = HtmlService
.createHtmlOutput('<style>span{font-size: 14px;font-weight: bold;text-decoration: underline;font-style: italic;cursor: pointer;}</style>'+
'<script>function selectURL(){document.getElementById("oauthURL").select();document.execCommand("copy")}</script>'+
'<p>Copy & Paste The Below URL In <a href="'+validOauthUrl+'"><i>Valid OAuth Redirect URIs</i></a></p>'+
'<br /><span onclick="selectURL()">Copy to Clipboard</span><textarea type="text" id="oauthURL" style="width:100%;">'+Utilities.formatString("https://script.google.com/macros/d/%s/usercallback", ScriptApp.getScriptId())+
'</textarea>')
.setWidth(450)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Valid OAuth Redirect URIs')
}
function makeRequest(ACCOUNTDATAOBJECT) {
if(!ACCOUNTDATAOBJECT['callFrom']) {ACCOUNTDATAOBJECT = ACCOUNTDATA}
var fbRequest = getService();
var requestEndpoint = "https://graph.facebook.com/v3.3/act_"+ACCOUNTDATAOBJECT['facebookData']['facebookAccountId']+"/insights?"
var param = {'limit':ACCOUNTDATAOBJECT['additionalData']['limit'],'level': ACCOUNTDATAOBJECT['facebookData']['facebookLevel']}
if(ACCOUNTDATAOBJECT['additionalData']['isGaUpload']) {
param['fields'] = 'ad_id,'+ACCOUNTDATAOBJECT['facebookData']['facebookFields']
param['time_increment'] = '1'
} else {
param['fields'] = ACCOUNTDATAOBJECT['facebookData']['facebookFields']
}
if(param['fields'] == ''){SpreadsheetApp.getUi().alert("Enter The Fields");return}
if(ACCOUNTDATAOBJECT['facebookData']['facebookBreakdowns'] != ''){param['breakdowns'] = ACCOUNTDATAOBJECT['facebookData']['facebookBreakdowns'] }
if(ACCOUNTDATAOBJECT['dateData']['splitByDate']){param['time_increment'] = '1'}
if(ACCOUNTDATAOBJECT['dateData']['preDefinedRage']!="")
{ param['date_preset'] = ACCOUNTDATAOBJECT['dateData']['preDefinedRage'] ;}
else if(ACCOUNTDATAOBJECT['dateData']['startDate']!=""&&ACCOUNTDATAOBJECT['dateData']['endDate']!="")
{ param['time_range[since]']=ACCOUNTDATAOBJECT['dateData']['startDate'];param['time_range[until]']=ACCOUNTDATAOBJECT['dateData']['endDate'];}
else { SpreadsheetApp.getUi().alert("Enter Correct Date Range!!");return}
var response = UrlFetchApp.fetch(requestEndpoint + jsonToQuery(param),
{headers: {'Authorization': 'Bearer ' + fbRequest.getAccessToken()},muteHttpExceptions : true})
var parseData = JSON.parse(response)
if(parseData.hasOwnProperty('error'))
{
if(parseData.error.hasOwnProperty('error_user_title'))
{SpreadsheetApp.getUi().alert(parseData.error.error_user_title)}
else{SpreadsheetApp.getUi().alert(parseData.error.message)}
return
}
//if(parseData.data.length == 0)
//{SpreadsheetApp.getUi().alert('No Facebook Data For The Applied Date Range'); return;}
if(ACCOUNTDATAOBJECT['additionalData']['isGaUpload'] && parseData.data.length > 0){
var utms_endpoint = "https://graph.facebook.com/v3.3/act_"+ACCOUNTDATAOBJECT['facebookData']['facebookAccountId']+"/ads?fields=adcreatives%7Burl_tags%7D&limit="+5000
var utms_ads = UrlFetchApp.fetch(utms_endpoint,
{headers: {'Authorization': 'Bearer ' + fbRequest.getAccessToken()},muteHttpExceptions : true})
var parsed_utms = JSON.parse(utms_ads)
if(parsed_utms.hasOwnProperty('error'))
{
if(parsed_utms.error.hasOwnProperty('error_user_title'))
{SpreadsheetApp.getUi().alert(parsed_utms.error.error_user_title)}
else{SpreadsheetApp.getUi().alert(parsed_utms.error.message)}
return
}
var parsed_utms_data = nextTokenData(parsed_utms)
}
try{
parseData = nextTokenData(parseData)
var fieldArray = param['fields'].split(",")
if(param['breakdowns']){fieldArray = fieldArray.concat(param['breakdowns'].split(","))}
var headers = ACCOUNTDATA.getUIHeaders(fieldArray)
var sheet= SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var pos = ACCOUNTDATAOBJECT['additionalData']['pos']
if(typeof(ACCOUNTDATAOBJECT['additionalData']['pos']) == 'string'){
pos = ACCOUNTDATAOBJECT['additionalData']['pos'].split(",")
}
if(sheet.getLastRow() > 0 && sheet.getLastColumn() > 0)
{sheet.getRange(pos[0],pos[1],sheet.getLastRow(),sheet.getLastColumn()).clear()}
var finalParsedOutput = []
if(ACCOUNTDATAOBJECT['additionalData']['isGaUpload']){
if(parseData.data.length > 0 ){finalParsedOutput=parser(parseData,parsed_utms_data,ACCOUNTDATAOBJECT['additionalData']['source'],ACCOUNTDATAOBJECT['additionalData']['medium'])}
else {finalParsedOutput.push([])}
}
else{
finalParsedOutput = parserNonGA(parseData, fieldArray);
finalParsedOutput.unshift(headers);
var cell = sheet.getRange(pos[0],pos[1],1,finalParsedOutput[0].length)
cell.setFontWeight("bold")
cell.setBorder(false, false, true, false, false, false,"black",SpreadsheetApp.BorderStyle.DOUBLE)
}
if(finalParsedOutput[0].length > 0) {sheet.getRange(pos[0], pos[1], finalParsedOutput.length, finalParsedOutput[0].length).setValues(finalParsedOutput)}
var statusDescription = "DATE: "+ACCOUNTDATAOBJECT['dateData']['startDate']+" TO "+ACCOUNTDATAOBJECT['dateData']['endDate']+"<br /> ACCOUNT_ID: "+ACCOUNTDATAOBJECT['facebookData']['facebookAccountId']+"<br /> ROWS: "+finalParsedOutput.length;
return {status:'success', description:statusDescription}
} catch (e) {Logger.log(e) }
};
function nextTokenData(parseData)
{
if(parseData.data.length == 0) {return parseData}
var fbRequest = getService();
if(parseData.paging.next != undefined)
{
var parsedata_pg = parseData;
while (true)
{
var response = UrlFetchApp.fetch(parsedata_pg.paging.next,
{headers: {'Authorization': 'Bearer ' + fbRequest.getAccessToken()},muteHttpExceptions : true})
parsedata_pg = JSON.parse(response)
parseData.data = parseData.data.concat(parsedata_pg.data)
if(parsedata_pg.paging.next == undefined)
{ break;}
}}
return parseData
}
function AdIds(id, parsed_utms_data)
{
var data = parsed_utms_data
for (i in data.data)
{
if (data.data[i].id == id)
{
if (data.data[i].adcreatives.data[0].url_tags != undefined)
{
var tags = data.data[i].adcreatives.data[0].url_tags
var ids_obj = {}
ids_obj['id']=data.data[i].id
if (/utm_source=([^&]+)/i.exec(tags) != null)
{ids_obj['source'] = /utm_source=([^&]+)/i.exec(tags)[1]}
if (/utm_medium=([^&]+)/i.exec(tags) != null)
{ids_obj['medium'] = /utm_medium=([^&]+)/i.exec(tags)[1]}
if (/utm_campaign=([^&]+)/i.exec(tags) != null)
{ids_obj['campaign'] = /utm_campaign=([^&]+)/i.exec(tags)[1]}
if (/utm_content=([^&]+)/i.exec(tags) != null)
{ids_obj['content'] = /utm_content=([^&]+)/i.exec(tags)[1]}
} else { return false }
return ids_obj
} } }
function parserNonGA(parseData, fieldsArray){
var data=parseData.data;
var rw=[];
for (var i = 0; i < data.length; i++)
{
rw[i]= Array.apply(null, new Array(fieldsArray.length)).map(Number.prototype.valueOf,0);
for (key in data[i]) {rw[i][fieldsArray.indexOf(key)] = data[i][key].replace(/\,|\'|\"/g,'')}
}
return rw
}
function parser(parseData,parsed_utms_data,SOURCE,MEDIUM)
{
var Data=parseData;
var rw=[];
for (var i = 0; i < Data.data.length; i++)
{
rw[i]=[]
var p = {}
for (key in Data.data[i])
{
if (key == 'ad_id') { p = AdIds(Data.data[i][key],parsed_utms_data); continue;}
if (p==undefined) { Logger.log("Ad ID Error"); break; }
if (key == 'campaign_name')
{ if (p.campaign != undefined)
{rw[i].push(p.campaign);continue;}
else { rw[i].push(Data.data[i][key].replace(/\,|\'|\"/g,'')); continue; }
}
if (key == 'ad_name')
{
if (p.content != undefined)
{
rw[i].push(p.content); continue;
} else { rw[i].push(Data.data[i][key].replace(/\,|\'|\"/g,'')); continue; }
}
if(key == 'spend') { rw[i].push(Data.data[i][key]*currenyMultiplier); continue; }
if(key=='date_stop') {continue;}
if(key=='date_start') {rw[i].push(Data.data[i][key].toString().split('-').join(''));continue;}
rw[i].push(Data.data[i][key].replace(/\,|\'|\"/g,''))
}
if (p.source !=undefined)
{ rw[i].push( p.source ) }
else{ rw[i].push(SOURCE)}
if (p.medium !=undefined)
{rw[i].push( p.medium ) }
else{rw[i].push(MEDIUM)}
}
return rw
}
/**
* oAuth Script : https://github.com/googlesamples/apps-script-oauth2
*/
/**
* Configures the service.
*/
function getService() {
return OAuth2.createService('Facebook')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://www.facebook.com/dialog/oauth')
.setTokenUrl('https://graph.facebook.com/v3.3/oauth/access_token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to complete
// the OAuth flow.
.setCallbackFunction('authCallback')
//Set Scope
.setScope('ads_read')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties());
}
function authCallback(request) {
var isAuthorized = getService().handleCallback(request);
if (isAuthorized) {
successUI(true)
showBar()
return HtmlService.createHtmlOutput('Success! You can close this tab.<script>window.top.close()</script>');
} else {
successUI(false)
showBar()
return HtmlService.createHtmlOutput('Denied. You can close this tab.<script>window.top.close()</script>');
}
}
function reset() {
var service = getService();
service.reset();
showBar()
SpreadsheetApp.getUi().alert("Log Out Success!!")
}
function successUI(isAuth){
if(isAuth){
var UI=HtmlService.createHtmlOutput("<b><span style='color:green'>Authorization Successful</span></b>")
SpreadsheetApp.getUi().showModalDialog(UI, "Authorization Status") } else
{var UI=HtmlService.createHtmlOutput("<b><span style='color:red'>Authorization Fail</span></b>")
SpreadsheetApp.getUi().showModalDialog(UI, "Authorization Status")}
}
function adAccounts(){
var fbRequest = getService();
var addaccounts_endpoint = "https://graph.facebook.com/v3.3/me?fields=adaccounts.limit(100)%7Bname,account_id%7D"
var adAccountInfo = UrlFetchApp.fetch(addaccounts_endpoint,
{headers: {'Authorization': 'Bearer ' + fbRequest.getAccessToken()},muteHttpExceptions : true})
var parsedadAccountInfo = JSON.parse(adAccountInfo)
if(parsedadAccountInfo.hasOwnProperty('error') || !parsedadAccountInfo.adaccounts)
{SpreadsheetApp.getUi().alert('ERROR: '+parsedadAccountInfo['error']['message']);return false}
else {
var adAccountFB = nextTokenData(parsedadAccountInfo.adaccounts,200)
var parsed_adurls = parsedadAccountInfo;
parsed_adurls['adaccounts'] = adAccountFB
}
return { 'facebookAccountData':parsed_adurls.adaccounts.data }
}
////
//
//Cost Data Upload Script - http://www.ryanpraski.com/google-analytics-cost-data-import-google-sheets-automated/
//
////
function uploadData(ACCOUNT_ID, PROPERTY_ID, DATASET_ID) {
var accountId = ACCOUNT_ID
var webPropertyId = PROPERTY_ID
var customDataSourceId = DATASET_ID
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var maxRows = ss.getLastRow();
var maxColumns = ss.getLastColumn();
var data = [];
for (var i = 1; i <= maxRows;i++) {
data.push(ss.getRange([i], 1,1, maxColumns).getValues());
}
var newData = data.join("\n");
var blobData = Utilities.newBlob(newData, "application/octet-stream", "GA import data");
uploadStatus(accountId, webPropertyId, customDataSourceId, blobData)
}
function uploadStatus(accountId, webPropertyId, customDataSourceId, blobData){
try {
var upload = Analytics.Management.Uploads.uploadData(accountId, webPropertyId, customDataSourceId, blobData);
SpreadsheetApp.getUi().alert("Data Has Been Sent To Google Analytics.!! Checking Errors...");
var uploadId = JSON.parse(upload)
var count = 0
while(count < 5)
{var status =Analytics.Management.Uploads.get(accountId, webPropertyId , customDataSourceId, uploadId.id )
status = JSON.parse(status)
if(status['status'] == 'PENDING')
{count++;Utilities.sleep(1000)}
else if(status['status'] == 'COMPLETED'){
SpreadsheetApp.getUi().alert("SUCCESS.!! No Errors Found. Data Has Been Successfully Uploaded");
sendEmail(isEmail,subject,"SUCCESS")
break;
} else if(status['status'] == 'FAILED')
{
var error = ""
for(var j=0;j<status.errors.length;j++)
{error += (j+1)+".) "+status.errors[j]+" \n" }
SpreadsheetApp.getUi().alert("FAILED.!! Here are some errors. \n"+error );
sendEmail(isEmail,subject,error)
break;
}}}
catch(err) {
return
}
}
function sendEmail(isEmail,subject,status){
if(!isEmail){return;}
if(MailApp.getRemainingDailyQuota() == 0) {return;}
var subject = ''
var subject = subject == '' ? 'Facebook Data Upload To GA ('+ACCOUNT_ID+')' : subject
var message = '';
if(status == "SUCCESS" ){
message = "<h3>Data Has Been Successfully Uploaded in Google Analytics.</h3><br /><p>- AccountID: "+ACCOUNT_ID+"<br />"+
"<p>- Property ID: "+PROPERTY_ID}
else{ message = "<h3>Data Import Has Been Failed. Here are some errors</h3><br /><p> Errors: "+status+"<br />"
}
MailApp.sendEmail({
'to':Session.getActiveUser().getEmail(),
'subject':subject,
'htmlBody':message
})
}
//////////////////////////////////////////////
(function (host, expose) {
var module = { exports: {} };
var exports = module.exports;
/****** code begin *********/
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file Contains the methods exposed by the library, and performs
* any required setup.
*/
/**
* The supported formats for the returned OAuth2 token.
* @enum {string}
*/
var TOKEN_FORMAT = {
/** JSON format, for example <code>{"access_token": "..."}</code> **/
JSON: 'application/json',
/** Form URL-encoded, for example <code>access_token=...</code> **/
FORM_URL_ENCODED: 'application/x-www-form-urlencoded'
};
/**
* The supported locations for passing the state parameter.
* @enum {string}
*/
var STATE_PARAMETER_LOCATION = {
/**
* Pass the state parameter in the authorization URL.
* @default
*/
AUTHORIZATION_URL: 'authorization-url',
/**
* Pass the state token in the redirect URL, as a workaround for APIs that
* don't support the state parameter.
*/
REDIRECT_URL: 'redirect-url'
};
/**
* Creates a new OAuth2 service with the name specified. It's usually best to
* create and configure your service once at the start of your script, and then
* reference them during the different phases of the authorization flow.
* @param {string} serviceName The name of the service.
* @return {Service_} The service object.
*/
function createService(serviceName) {
return new Service_(serviceName);
}
/**
* Returns the redirect URI that will be used for a given script. Often this URI
* needs to be entered into a configuration screen of your OAuth provider.
* @param {string} scriptId The script ID of your script, which can be found in
* the Script Editor UI under "File > Project properties".
* @return {string} The redirect URI.
*/
function getRedirectUri(scriptId) {
return Utilities.formatString(
'https://script.google.com/macros/d/%s/usercallback', scriptId);
}
if (typeof module === 'object') {
module.exports = {
createService: createService,
getRedirectUri: getRedirectUri,
TOKEN_FORMAT: TOKEN_FORMAT,
STATE_PARAMETER_LOCATION: STATE_PARAMETER_LOCATION
};
}
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file Contains the Service_ class.
*/
// Disable JSHint warnings for the use of eval(), since it's required to prevent
// scope issues in Apps Script.
// jshint evil:true
/**
* Creates a new OAuth2 service.
* @param {string} serviceName The name of the service.
* @constructor
*/
var Service_ = function(serviceName) {
validate_({
'Service name': serviceName
});
this.serviceName_ = serviceName;
this.params_ = {};
this.tokenFormat_ = TOKEN_FORMAT.JSON;
this.tokenHeaders_ = null;
this.scriptId_ = eval('Script' + 'App').getScriptId();
this.expirationMinutes_ = 60;
};
/**
* The number of seconds before a token actually expires to consider it expired
* and refresh it.
* @type {number}
* @private
*/
Service_.EXPIRATION_BUFFER_SECONDS_ = 60;
/**
* The number of milliseconds that a token should remain in the cache.
* @type {number}
* @private
*/
Service_.LOCK_EXPIRATION_MILLISECONDS_ = 30 * 1000;
/**
* Sets the service's authorization base URL (required). For Google services
* this URL should be
* https://accounts.google.com/o/oauth2/auth.
* @param {string} authorizationBaseUrl The authorization endpoint base URL.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setAuthorizationBaseUrl = function(authorizationBaseUrl) {
this.authorizationBaseUrl_ = authorizationBaseUrl;
return this;
};
/**
* Sets the service's token URL (required). For Google services this URL should
* be https://accounts.google.com/o/oauth2/token.
* @param {string} tokenUrl The token endpoint URL.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenUrl = function(tokenUrl) {
this.tokenUrl_ = tokenUrl;
return this;
};
/**
* Sets the service's refresh URL. Some OAuth providers require a different URL
* to be used when generating access tokens from a refresh token.
* @param {string} refreshUrl The refresh endpoint URL.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setRefreshUrl = function(refreshUrl) {
this.refreshUrl_ = refreshUrl;
return this;
};
/**
* Sets the format of the returned token. Default: OAuth2.TOKEN_FORMAT.JSON.
* @param {OAuth2.TOKEN_FORMAT} tokenFormat The format of the returned token.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenFormat = function(tokenFormat) {
this.tokenFormat_ = tokenFormat;
return this;
};
/**
* Sets the additional HTTP headers that should be sent when retrieving or
* refreshing the access token.
* @param {Object.<string,string>} tokenHeaders A map of header names to values.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenHeaders = function(tokenHeaders) {
this.tokenHeaders_ = tokenHeaders;
return this;
};
/**
* @callback tokenHandler
* @param tokenPayload {Object} A hash of parameters to be sent to the token
* URL.
* @param tokenPayload.code {string} The authorization code.
* @param tokenPayload.client_id {string} The client ID.
* @param tokenPayload.client_secret {string} The client secret.
* @param tokenPayload.redirect_uri {string} The redirect URI.
* @param tokenPayload.grant_type {string} The type of grant requested.
* @returns {Object} A modified hash of parameters to be sent to the token URL.
*/
/**
* Sets an additional function to invoke on the payload of the access token
* request.
* @param {tokenHandler} tokenHandler tokenHandler A function to invoke on the
* payload of the request for an access token.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setTokenPayloadHandler = function(tokenHandler) {
this.tokenPayloadHandler_ = tokenHandler;
return this;
};
/**
* Sets the name of the authorization callback function (required). This is the
* function that will be called when the user completes the authorization flow
* on the service provider's website. The callback accepts a request parameter,
* which should be passed to this service's <code>handleCallback()</code> method
* to complete the process.
* @param {string} callbackFunctionName The name of the callback function.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setCallbackFunction = function(callbackFunctionName) {
this.callbackFunctionName_ = callbackFunctionName;
return this;
};
/**
* Sets the client ID to use for the OAuth flow (required). You can create
* client IDs in the "Credentials" section of a Google Developers Console
* project. Although you can use any project with this library, it may be
* convinient to use the project that was created for your script. These
* projects are not visible if you visit the console directly, but you can
* access it by click on the menu item "Resources > Advanced Google services" in
* the Script Editor, and then click on the link "Google Developers Console" in
* the resulting dialog.
* @param {string} clientId The client ID to use for the OAuth flow.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setClientId = function(clientId) {
this.clientId_ = clientId;
return this;
};
/**
* Sets the client secret to use for the OAuth flow (required). See the
* documentation for <code>setClientId()</code> for more information on how to
* create client IDs and secrets.
* @param {string} clientSecret The client secret to use for the OAuth flow.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setClientSecret = function(clientSecret) {
this.clientSecret_ = clientSecret;
return this;
};
/**
* Sets the property store to use when persisting credentials (required). In
* most cases this should be user properties, but document or script properties
* may be appropriate if you want to share access across users.
* @param {PropertiesService.Properties} propertyStore The property store to use
* when persisting credentials.
* @return {Service_} This service, for chaining.
* @see https://developers.google.com/apps-script/reference/properties/
*/
Service_.prototype.setPropertyStore = function(propertyStore) {
this.propertyStore_ = propertyStore;
return this;
};
/**
* Sets the cache to use when persisting credentials (optional). Using a cache
* will reduce the need to read from the property store and may increase
* performance. In most cases this should be a private cache, but a public cache
* may be appropriate if you want to share access across users.
* @param {CacheService.Cache} cache The cache to use when persisting
* credentials.
* @return {Service_} This service, for chaining.
* @see https://developers.google.com/apps-script/reference/cache/
*/
Service_.prototype.setCache = function(cache) {
this.cache_ = cache;
return this;
};
/**
* Sets the lock to use when checking and refreshing credentials (optional).
* Using a lock will ensure that only one execution will be able to access the
* stored credentials at a time. This can prevent race conditions that arise
* when two executions attempt to refresh an expired token.
* @param {LockService.Lock} lock The lock to use when accessing credentials.
* @return {Service_} This service, for chaining.
* @see https://developers.google.com/apps-script/reference/lock/
*/
Service_.prototype.setLock = function(lock) {
this.lock_ = lock;
return this;
};
/**
* Sets the scope or scopes to request during the authorization flow (optional).
* If the scope value is an array it will be joined using the separator before
* being sent to the server, which is is a space character by default.
* @param {string|Array.<string>} scope The scope or scopes to request.
* @param {string} [optSeparator] The optional separator to use when joining
* multiple scopes. Default: space.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setScope = function(scope, optSeparator) {
var separator = optSeparator || ' ';
this.params_.scope = Array.isArray(scope) ? scope.join(separator) : scope;
return this;
};
/**
* Sets an additional parameter to use when constructing the authorization URL
* (optional). See the documentation for your service provider for information
* on what parameter values they support.
* @param {string} name The parameter name.
* @param {string} value The parameter value.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setParam = function(name, value) {
this.params_[name] = value;
return this;
};
/**
* Sets the private key to use for Service Account authorization.
* @param {string} privateKey The private key.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setPrivateKey = function(privateKey) {
this.privateKey_ = privateKey;
return this;
};
/**
* Sets the issuer (iss) value to use for Service Account authorization.
* If not set the client ID will be used instead.
* @param {string} issuer This issuer value
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setIssuer = function(issuer) {
this.issuer_ = issuer;
return this;
};
/**
* Sets the subject (sub) value to use for Service Account authorization.
* @param {string} subject This subject value
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setSubject = function(subject) {
this.subject_ = subject;
return this;
};
/**
* Sets number of minutes that a token obtained through Service Account
* authorization should be valid. Default: 60 minutes.
* @param {string} expirationMinutes The expiration duration in minutes.
* @return {Service_} This service, for chaining.
*/
Service_.prototype.setExpirationMinutes = function(expirationMinutes) {
this.expirationMinutes_ = expirationMinutes;
return this;
};
/**
* Gets the authorization URL. The first step in getting an OAuth2 token is to
* have the user visit this URL and approve the authorization request. The
* user will then be redirected back to your application using callback function
* name specified, so that the flow may continue.
* @return {string} The authorization URL.
*/
Service_.prototype.getAuthorizationUrl = function() {
validate_({
'Client ID': this.clientId_,
'Script ID': this.scriptId_,
'Callback function name': this.callbackFunctionName_,
'Authorization base URL': this.authorizationBaseUrl_
});
var redirectUri = getRedirectUri(this.scriptId_);
var state = eval('Script' + 'App').newStateToken()
.withMethod(this.callbackFunctionName_)
.withArgument('serviceName', this.serviceName_)
.withTimeout(3600)
.createToken();
var params = {
client_id: this.clientId_,
response_type: 'code',
redirect_uri: redirectUri,
state: state
};
params = extend_(params, this.params_);
return buildUrl_(this.authorizationBaseUrl_, params);
};
/**
* Completes the OAuth2 flow using the request data passed in to the callback
* function.
* @param {Object} callbackRequest The request data recieved from the callback
* function.
* @return {boolean} True if authorization was granted, false if it was denied.
*/
Service_.prototype.handleCallback = function(callbackRequest) {
var code = callbackRequest.parameter.code;
var error = callbackRequest.parameter.error;
if (error) {
if (error == 'access_denied') {
return false;
} else {
throw new Error('Error authorizing token: ' + error);
}
}
validate_({
'Client ID': this.clientId_,
'Client Secret': this.clientSecret_,
'Script ID': this.scriptId_,
'Token URL': this.tokenUrl_
});
var redirectUri = getRedirectUri(this.scriptId_);
var headers = {
'Accept': this.tokenFormat_
};
if (this.tokenHeaders_) {
headers = extend_(headers, this.tokenHeaders_);
}
var tokenPayload = {
code: code,
client_id: this.clientId_,
client_secret: this.clientSecret_,
redirect_uri: redirectUri,
grant_type: 'authorization_code'
};
if (this.tokenPayloadHandler_) {
tokenPayload = this.tokenPayloadHandler_(tokenPayload);
}
var response = UrlFetchApp.fetch(this.tokenUrl_, {
method: 'post',
headers: headers,
payload: tokenPayload,
muteHttpExceptions: true
});
var token = this.getTokenFromResponse_(response);
this.saveToken_(token);
return true;
};
/**
* Determines if the service has access (has been authorized and hasn't
* expired). If offline access was granted and the previous token has expired
* this method attempts to generate a new token.
* @return {boolean} true if the user has access to the service, false
* otherwise.
*/
Service_.prototype.hasAccess = function() {
return this.lockable_(function() {
var token = this.getToken();
if (!token || this.isExpired_(token)) {
if (token && token.refresh_token) {
try {
this.refresh();
} catch (e) {
this.lastError_ = e;
return false;
}
} else if (this.privateKey_) {
try {
this.exchangeJwt_();
} catch (e) {
this.lastError_ = e;
return false;
}