Hi everyone,
I’m facing a persistent issue while trying to fetch my Dhan ledger data into Google Sheets using GAS (Google Apps Script).
I keep encountering errors despite following the API documentation and trying various solutions.
I’ve confirmed that I have ledger entries within the specified date range in my Dhan account.
Below is the code I’m using, and below the code is the Execution log screenshot.
Thanks in advance for your help!
function fetchDhanLedger() {
const accessToken = 'My_Access_Token'; // Replace with your actual Access Token
const ledgerApiUrl = 'https://api.dhan.co/v2/ledger';
const fromDate = '2024-10-01'; // Replace with your desired start date
const toDate = '2024-10-08'; // Replace with your desired end date
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Statement');
sheet.clearContents();
const apiUrlWithParams = `${ledgerApiUrl}?from_date=${fromDate}&to_date=${toDate}`;
const options = {
'method': 'get',
'headers': {
'Accept': 'application/json',
'access-token': accessToken
},
'muteHttpExceptions': true
};
try {
const ledgerResponse = UrlFetchApp.fetch(apiUrlWithParams, options);
Logger.log("Ledger Response: " + ledgerResponse.getContentText());
const ledgerData = JSON.parse(ledgerResponse.getContentText());
// Check if ledgerData is an array
if (!Array.isArray(ledgerData)) {
Logger.log("Error: Ledger data is not an array. Response: " + JSON.stringify(ledgerData));
return; // Exit the function if it's not an array
}
let row = 1;
for (const entry of ledgerData) {
sheet.getRange(row, 1).setValue(entry.dhanClientId);
sheet.getRange(row, 2).setValue(entry.narration);
sheet.getRange(row, 3).setValue(entry.voucherdate);
sheet.getRange(row, 4).setValue(entry.exchange);
sheet.getRange(row, 5).setValue(entry.voucherdesc);
sheet.getRange(row, 6).setValue(entry.vouchernumber);
sheet.getRange(row, 7).setValue(entry.debit);
sheet.getRange(row, 8).setValue(entry.credit);
sheet.getRange(row, 9).setValue(entry.runbal);
row++;
}
} catch (error) {
Logger.log("Error parsing JSON response: " + error);
}
}