Created
May 12, 2023 13:04
-
-
Save Kugelschieber/9f07432e7ea24ba193a3bf97cbb3bd63 to your computer and use it in GitHub Desktop.
Pirsch Analytics Google Sheets API Integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PIRSCH_CLIENT_ID = ScriptProperties.getProperty('client_id'); | |
const PIRSCH_CLIENT_SECRET = ScriptProperties.getProperty('client_secret'); | |
function onOpen() { | |
var ui = SpreadsheetApp.getUi(); | |
ui.createMenu("Pirsch Analytics") | |
.addItem('Get Visitors', 'pasteVisitorsToSheet') | |
.addToUi(); | |
} | |
function pasteVisitorsToSheet() { | |
const accessToken = getAccessToken(); | |
const domain = getDomain(accessToken); | |
const visitors = getVisitors(accessToken, domain[0].id); | |
const data = []; | |
visitors.forEach(day => { | |
data.push([day.day, day.visitors, day.views, day.sessions, day.bounces, day.bounce_rate]); | |
}); | |
const ss = SpreadsheetApp.getActive(); | |
const sheet = ss.getSheetByName("Tabellenblatt1"); | |
sheet.getRange(2, 1, data.length, 6).setValues(data); | |
sheet.getRange(2, 3, data.length, 3).setNumberFormat("#,##0"); | |
} | |
function getAccessToken() { | |
const endpoint = "https://api.pirsch.io/api/v1/token"; | |
const params = { | |
method: "POST", | |
payload: JSON.stringify({ | |
client_id: PIRSCH_CLIENT_ID, | |
client_secret: PIRSCH_CLIENT_SECRET | |
}) | |
}; | |
const response = UrlFetchApp.fetch(endpoint, params); | |
const data = JSON.parse(response.getContentText()); | |
return data.access_token; | |
} | |
function getDomain(accessToken) { | |
const endpoint = "https://api.pirsch.io/api/v1/domain"; | |
const params = { | |
method: "GET", | |
headers: { | |
"Authorization": `Bearer ${accessToken}` | |
} | |
}; | |
const response = UrlFetchApp.fetch(endpoint, params); | |
const data = JSON.parse(response.getContentText()); | |
return data; | |
} | |
function getVisitors(accessToken, domainID) { | |
const endpoint = `https://api.pirsch.io/api/v1/statistics/visitor?id=${domainID}&from=2023-01-01&to=2023-05-12`; | |
const params = { | |
method: "GET", | |
headers: { | |
"Authorization": "Bearer " + accessToken | |
} | |
}; | |
const response = UrlFetchApp.fetch(endpoint, params); | |
const data = JSON.parse(response.getContentText()); | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment