Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var appId = "Your ID";
var secret = "Your Secret";
function alertAuth() {
var service = getService();
var authorizationUrl = service.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">認証</a>. ' +
'認証が完了したら再度操作を行ってください。');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
SpreadsheetApp.getUi().showModalDialog(page, "認証が必要です");
Logger.log("認証が切れています");
}
function getService() {
return OAuth2.createService('freee')
.setAuthorizationBaseUrl('https://secure.freee.co.jp/oauth/authorize')
.setTokenUrl('https://api.freee.co.jp/oauth/token')
.setClientId(appId)
.setClientSecret(secret)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
}
function authCallback(request) {
var service = getService();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('認証に成功しました。タブを閉じてください。');
} else {
return HtmlService.createHtmlOutput('認証に失敗しました。タブを閉じてください。');
}
}
function fetchFreee(url) {
var freeeApp = getService();
var token = freeeApp.getAccessToken();
var options =
{
"method" : "get",
"headers" : {"Authorization" : "Bearer "+ token}
};
var json = UrlFetchApp.fetch(url,options).getContentText();
var jsonData = JSON.parse(json);
return jsonData
}
function getCompanyId() {
var jsonData = fetchFreee("https://api.freee.co.jp/api/1/companies")
var companyId = jsonData['companies']['0']['id'];
return companyId
}
function getSalesData() {
var companyId = getCompanyId();
var dealsData = fetchFreee("https://api.freee.co.jp/api/1/deals?company_id=" + companyId);
var dataCnt = dealsData["deals"].length;
var arr = [];
for(var i=0; i<dataCnt; i++){
var issue_data = dealsData["deals"][i]["issue_date"]
var type = dealsData["deals"][i]["type"]
var amount = dealsData["deals"][i]["amount"]
var description = dealsData["deals"][i]["details"][0]["description"]
arr.push([issue_data, type, amount, description])
}
return arr
}
//detaというシートに取得したデータを書き出す。
function setDataToSheet(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('data');
var arr = getSalesData()
var lastRow = arr.length;
var column = arr[0].length;
Logger.log(arr)
sheet.getRange(2,1,lastRow,column).setValues(arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.