Jenderal92

Untitled

Aug 15th, 2022
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. class HomeController extends Controller
  6. {
  7. public function getAnalyticsSummary(Request $request){
  8. $from_date = date("Y-m-d", strtotime($request->get('from_date',"7 days ago")));
  9. $to_date = date("Y-m-d",strtotime($request->get('to_date',$request->get('from_date','today')))) ;
  10. $gAData = $this->gASummary($from_date,$to_date) ;
  11. return $gAData;
  12. }
  13. //to get the summary of google analytics.
  14. private function gASummary($date_from,$date_to) {
  15. $service_account_email = 'your service account email';
  16. // Create and configure a new client object.
  17. $client = new \Google_Client();
  18. $client->setApplicationName("{application name}");
  19. $analytics = new \Google_Service_Analytics($client);
  20. $cred = new \Google_Auth_AssertionCredentials(
  21. $service_account_email,
  22. array(\Google_Service_Analytics::ANALYTICS_READONLY),
  23. "{your private_key}"
  24. );
  25. $client->setAssertionCredentials($cred);
  26. if($client->getAuth()->isAccessTokenExpired()) {
  27. $client->getAuth()->refreshTokenWithAssertion($cred);
  28. }
  29. $optParams = [
  30. 'dimensions' => 'ga:date',
  31. 'sort'=>'-ga:date'
  32. ] ;
  33. $results = $analytics->data_ga->get(
  34. 'ga:{View ID}',
  35. $date_from,
  36. $date_to,
  37. 'ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:hits,ga:avgSessionDuration',
  38. $optParams
  39. );
  40.  
  41. $rows = $results->getRows();
  42. $rows_re_align = [] ;
  43. foreach($rows as $key=>$row) {
  44. foreach($row as $k=>$d) {
  45. $rows_re_align[$k][$key] = $d ;
  46. }
  47. }
  48. $optParams = array(
  49. 'dimensions' => 'rt:medium'
  50. );
  51. try {
  52. $results1 = $analytics->data_realtime->get(
  53. 'ga:{View ID}',
  54. 'rt:activeUsers',
  55. $optParams);
  56. // Success.
  57. } catch (apiServiceException $e) {
  58. // Handle API service exceptions.
  59. $error = $e->getMessage();
  60. }
  61. $active_users = $results1->totalsForAllResults ;
  62. return [
  63. 'data'=> $rows_re_align ,
  64. 'summary'=>$results->getTotalsForAllResults(),
  65. 'active_users'=>$active_users['rt:activeUsers']
  66. ] ;
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment