-
-
Save RitwikGA/29578e48ce6cc92de6f590e923452127 to your computer and use it in GitHub Desktop.
| /* Facebook Page Feed Tracking in Google Analytics | |
| * Description: Track User Event Like, Comment & Share. | |
| * Auth:Ritwik B | |
| * Website:www.Digishuffle.com | |
| * | |
| * Updated on 13-10-2017 | |
| * - All Event Logger | |
| */ | |
| var CLIENT_ID = ''; // Insert App ID | |
| var CLIENT_SECRET = '';; // Insert App Secret | |
| var GA_PROPERTY_ID=''; // Insert Property ID | |
| var FB_PAGE_NAME='' // Insert Page Name | |
| var EVENTS = ['ec', 'ea' ] // [ Post URL , Post Action ] | |
| var NON_INTERACTION=false // Non-Interaction False | |
| var MEASUREMENT_PROTOCOL_HIT={ 'v':'1' , 'tid' : GA_PROPERTY_ID, 't': 'event','ni':NON_INTERACTION?'1':'0'} | |
| /** ALL EVENTS LOGGER **/ | |
| var SPREADSHEET_ID = "" //Enter Spreadsheet ID To Log Events | |
| var RT_SHEET_TRACKER = "FB_Events" //Sheet Name To Use | |
| /** | |
| * oAuth Script : https://github.com/googlesamples/apps-script-oauth2 | |
| */ | |
| function reset() { | |
| var service = getService(); | |
| service.reset(); | |
| } | |
| /** | |
| * 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/v2.7/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('manage_pages publish_pages') | |
| // Set the property store where authorized tokens should be persisted. | |
| .setPropertyStore(PropertiesService.getUserProperties()); | |
| } | |
| /** | |
| * Handles the OAuth callback. | |
| */ | |
| function authCallback(request) { | |
| var txt='' | |
| var Id='' | |
| var pageToken='' | |
| var service = getService(); | |
| var authorized = service.handleCallback(request); | |
| if (authorized&&service.hasAccess()) { | |
| var url = 'https://graph.facebook.com/v2.10/me/accounts?fields=name,access_token'; | |
| var response = UrlFetchApp.fetch(url, { | |
| headers: { | |
| 'Authorization': 'Bearer ' + service.getAccessToken() | |
| } | |
| }); | |
| var result = JSON.parse(response.getContentText()); | |
| for (i in result['data']){ | |
| if(FB_PAGE_NAME==result['data'][i].name) | |
| { txt=result['data'][i].name+" Page Token is (Double Click To Copy) : <br />"+result['data'][i].access_token; | |
| Id=result['data'][i].id | |
| pageToken=result['data'][i].access_token | |
| break | |
| } | |
| } | |
| var msg=pageSubscribe(Id,pageToken)?"Page SUBSCRIBED to App":"Page NOT SUBSCRIBED to App!!" | |
| return HtmlService.createHtmlOutput('OAuth Success!!! '+ msg +'<br /><br />'+txt); | |
| } else { | |
| return HtmlService.createHtmlOutput('Access Denied. Check your page name or access level'); | |
| } | |
| } | |
| // Subscribe Page to App | |
| function pageSubscribe(id,token) | |
| { | |
| var url = 'https://graph.facebook.com/v2.10/'+id+'/subscribed_apps'; | |
| var response = UrlFetchApp.fetch(url, { | |
| headers: { | |
| 'Authorization': 'Bearer ' + token | |
| }, method : 'POST' | |
| }); | |
| return JSON.parse(response.getContentText())['success'] | |
| } | |
| function getURL(id) | |
| { | |
| return "https://www.facebook.com/"+id | |
| } | |
| function doGet(e){ | |
| if(e.parameter['hub.challenge']&&e.parameter['hub.mode']=='subscribe') | |
| { | |
| return ContentService.createTextOutput(e.parameter['hub.challenge'])} | |
| else | |
| { | |
| if (getService().hasAccess()) { | |
| return HtmlService.createHtmlOutput("<b>Your Token is Valid. </b>"); | |
| } | |
| else | |
| { | |
| return HtmlService.createTemplate("<b><a href='<?=getService().getAuthorizationUrl()?>' target='_blank'>Click To Authorize</a></b>").evaluate() | |
| }}} | |
| // Handle The Facebook Post Requests & Send to Analytics Servers | |
| function getSheet(sht,name){ | |
| var sh2 =sht.getSheetByName(name); | |
| if(sh2) | |
| { | |
| return sht.getSheetByName(name)} | |
| else | |
| { var sh2=sht.insertSheet(name) | |
| return sh2 | |
| } | |
| } | |
| function isSheetLogOn(data){ | |
| var header = [] | |
| if (SPREADSHEET_ID != '' && RT_SHEET_TRACKER != '') | |
| { | |
| var sheet = SpreadsheetApp.openById("1HMQtUmf80ikdOAxHHJsvjhE8ezCNAtqIhOJYFBP68YA") | |
| var output_sheet = getSheet(sheet,RT_SHEET_TRACKER ) | |
| if(output_sheet.getRange(1,1).getValue()=="") | |
| { | |
| header.push(['Date/Time','Item','Post ID','Emoticon','Parent ID','Action','Name','ID']) | |
| output_sheet.getRange(1,1,1,Object.keys(data).length).setBackground('#6569e1') | |
| output_sheet.getRange(1,1,1,Object.keys(data).length).setFontColor('white') | |
| output_sheet.getRange(1,1,1,Object.keys(data).length).setFontSize('15') | |
| output_sheet.getRange(1,1,1,Object.keys(data).length).setValues(header) | |
| } | |
| return output_sheet | |
| } | |
| else {return false} | |
| } | |
| function parSer(data) | |
| { | |
| var ar = new Array(data.length) | |
| var ar1 = [] | |
| for (i in data) | |
| { | |
| if(i=="created_time") | |
| { | |
| var t = new Date(parseInt(data[i])*1000) | |
| t = t.toLocaleDateString() +" "+ t.toLocaleTimeString() | |
| ar[0] = t | |
| } | |
| if(i=="item") | |
| {ar[1] = data[i]} | |
| if(i=="post_id") | |
| {ar[2] = data[i]} | |
| if(i=="reaction_type") | |
| {ar[3] = data[i]} | |
| if(i=="parent_id") | |
| {ar[4] = data[i]} | |
| if(i=="verb") | |
| {ar[5] = data[i]} | |
| if(i=="sender_name") | |
| {ar[6] = data[i]} | |
| if(i=="sender_id") | |
| {ar[7] = data[i]} | |
| } | |
| ar1.push(ar) | |
| return ar1 | |
| } | |
| function doPost(e) | |
| { | |
| var actionData=JSON.parse(e.postData.contents) | |
| actionData=actionData.entry[0].changes[0].value | |
| var sheet = isSheetLogOn(actionData) | |
| if (sheet) | |
| { | |
| var parsed_data = parSer(actionData) | |
| sheet.getRange(sheet.getLastRow()+1,1,1,parsed_data[0].length).setValues(parsed_data) | |
| } | |
| //Track Actions on post, not on comments && Dont Track Actions By Page Owner | |
| if(actionData.post_id&&actionData.sender_name!==FB_PAGE_NAME) | |
| { | |
| switch(actionData.verb+actionData.item) | |
| { | |
| case 'addreaction': | |
| if(actionData.reaction_type) //No Comment Like | |
| { | |
| MEASUREMENT_PROTOCOL_HIT[EVENTS[0]]=getURL(actionData.post_id) | |
| MEASUREMENT_PROTOCOL_HIT[EVENTS[1]]=actionData.reaction_type.charAt(0).toUpperCase()+actionData.reaction_type.slice(1) //Capitalize first letter | |
| MEASUREMENT_PROTOCOL_HIT['cid']=actionData.sender_id.toString() | |
| sendHit(MEASUREMENT_PROTOCOL_HIT) | |
| } | |
| break; | |
| case 'addcomment': | |
| MEASUREMENT_PROTOCOL_HIT[EVENTS[0]]=getURL(actionData.post_id) | |
| MEASUREMENT_PROTOCOL_HIT[EVENTS[1]]=actionData.item.charAt(0).toUpperCase()+actionData.item.slice(1) | |
| MEASUREMENT_PROTOCOL_HIT['cid']=actionData.sender_id.toString() | |
| sendHit(MEASUREMENT_PROTOCOL_HIT) | |
| break; | |
| case 'addshare': | |
| MEASUREMENT_PROTOCOL_HIT[EVENTS[0]]=getURL(actionData.post_id) | |
| MEASUREMENT_PROTOCOL_HIT[EVENTS[1]]=actionData.item.charAt(0).toUpperCase()+actionData.item.slice(1) | |
| MEASUREMENT_PROTOCOL_HIT['cid']=actionData.sender_id.toString() | |
| sendHit(MEASUREMENT_PROTOCOL_HIT) | |
| break; | |
| } | |
| } | |
| if(e.parameter['hub.challenge']) | |
| return ContentService.createTextOutput(e.parameter['hub.challenge']) | |
| else return ContentService.createTextOutput("Done") | |
| } | |
| // Analytics Measurement Protocol Hits | |
| function sendHit(protocolHit) | |
| { | |
| var url = 'https://www.google-analytics.com/collect' | |
| var url = UrlFetchApp.fetch(url, {'method':'POST','payload':protocolHit}) | |
| } | |
Hi Matthew,
Facebook Login Plugin needs to be installed. There is a slight change in auth process in facebook, Recheck the step #4.#5,#6 & let me know
Here: http://www.digishuffle.com/blogs/track-facebook-like-comment-share-in-real-time-google-analytics/
Hi RitwikGA, i had done all the step with no error.
But i still cant see any data on GA when i like or comment on the the FB page i setup.
Hi Matthew,
Thank you for great script and blog post. I get everything done. But I can get data into google spreadsheet.
I think There are some bugs with code. Below are example.
When I run doget function, I get the error below.
" TypeError: Cannot read property "parameter" from undefined. (line 130, file "Code")Dismiss "
Because of lacking knowledge app script, so I couldn't fix it by myself. :(
I hope you will review and update your code when you have time.
Hi Ritwik:
I have done thorough evey step you have write in the blog post.
I still can't get the correct authorization from facebook.
It return below error:
Request failed for https://graph.facebook.com/... returned code 404. Truncated server response: {"error":{"message":"(#803) Some of the aliases you requested do not exist: subscribed_apps","type":"OAuthException","code":803,"fbtrace_id":"DH1A0... (use muteHttpExceptions option to examine full response). (line 95, file "Code")
Any idea what might the reason behind it?
Thanks