function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sdusdu 

Access google analytics

Anyone can tell me what's the best/easiest way to access (read) google analytics data from Apex code (that runs in background)? 
pconpcon
You can do pretty much anything you need to do with apex callouts [1] in batch apex [2].  Assuming you know how to access the Google Analytics reporting apis [3] then it should be pretty straight foward.  However your question is pretty vague so unless you have a specific issue or additional questions, that's about the best I can do.

[1] https://developer.salesforce.com/page/Apex_Web_Services_and_Callouts
[2] https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm
[3] https://developers.google.com/analytics/devguides/reporting/
sdusdu
Thank you so much for your reply. I followed the instructions for using a service account, but kept getting 'invalid_grant' error. Do you have any suggestions what to check or do you have any work example I can take a look?

Oh, when I search on web for this error, some people said it could be caused by inaccurate system clock. But since I am running on salesforce platform, I have no control of that, and I would suppose the system clock on salesforce should be sync properly? So I should rule out this I suppose?

 
pconpcon
Invalid grant can be caused by several things.  I can be because you are sending the wrong id, the wrong secret, the wrong token you are using the wrong grant_type.  Is there any additional errors coming back?  Have you tried using something like cURL or a REST tool to test that you can get the data back without involving Salesforce?
sdusdu
Thanks, pcon. Actually it does seem to be related to the system clock. Because the exact same code sometimes work, but most times does not. When I manually adjust the timestamp by -25 seconds, the chance of working get highest, but it is still very low (like only works 2 out of ten tries).
pconpcon
Interesting.  How are you using the system time?
sdusdu
I am doing something like
Long currTime = System.currentTimeMillis() / 1000
then use currTime for iat value.