Trying to use Google Sheets to connect to the Enphase solar API. Can't get the code to work?

330 views Asked by At

Background: I have barely any knowledge of coding but I want to be able to use my solar output data from the Enphase system to trigger a hot water service to run. How I'm trying to do this is by moving the solar data into Google Sheets and when the solar generation is high enough, a button is pressed.

I've copied and changed this code from another question but I can't get it working. I am getting this error: Exception: Request failed for https://api.enphaseenergy.com returned code 401. Truncated server response: {"reason":"401","message":["Not authorized to access requested resource.","User not found."]} (use muteHttpExceptions option to examine full response). (line 10, file "Enphase To Sheets").

I have no idea where to go from here. Any ideas what I've done wrong? Thanks

Code:

function getReport() 
{
var url = 'https://api.enphaseenergy.com/api/v2/systemskey=<apikey>&user_id=<userid>'

var token = UrlFetchApp.fetch(url,{method:'POST',muteHttpExceptions: true});
var token_data = JSON.parse(token.getContentText());
var access_token = token_data.access_token

var url2 = 'https://api.enphaseenergy.com/api/v2/systems/1692404/stats&key<apikey>&user_id=<userid>'
var report = UrlFetchApp.fetch(url2,{method:'GET',headers:{Authorization: 'Bearer ' + '<apikey>'}});
Logger.log(report)

SpreadsheetApp.getActiveSheet().getSheetByName('Solar').getRange('A1').setValue(report); 
}
2

There are 2 answers

1
MattKing On

It looks to me like you're supposed to request an API key from them and they'll issue you one that you can put in the parts of your url with the < > symbols.

That is, you'll need a real api "key" and a real userid that you get from enphase.

0
Jamie On

I managed to get this working. All I've changed is a few stupid little mistakes with question marks instead of '&'. Hope this helps someone else if you need it. Once I had my data in the google sheet, I use =transpose(split(A1)) and then another split function to get the correct formatting to be able to use with IFTTT.

function getReport() 
{
  var url = 'https://api.enphaseenergy.com/api/v2/systems?key=<apikey_goes_here>&user_id=<userid_goes_here>'

  var token = UrlFetchApp.fetch(url,{method:'POST',muteHttpExceptions: true});
  var token_data = JSON.parse(token.getContentText());
  var access_token = token_data.access_token

  var url2 = 'https://api.enphaseenergy.com/api/v2/systems/1692404/summary?key=<apikey_goes_here>&user_id=<userid_goes_here>'
  var report = UrlFetchApp.fetch(url2,{method:'GET',headers:{Authorization: 'Bearer ' + '<userid_goes_here>'}});
  Logger.log(report)



  var sheet = SpreadsheetApp.getActive().getSheetByName('Solar');
  sheet.getRange('A1').setValue(report)

}