IndexController.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use yii\filters\AccessControl;
  5. use yii\web\Controller;
  6. use yii\web\Response;
  7. use yii\filters\VerbFilter;
  8. use app\models\LoginForm;
  9. use app\models\ContactForm;
  10. class IndexController extends Controller
  11. {
  12. /**
  13. * {@inheritdoc}
  14. */
  15. public function behaviors()
  16. {
  17. return [
  18. 'access' => [
  19. 'class' => AccessControl::className(),
  20. 'only' => ['logout'],
  21. 'rules' => [
  22. [
  23. 'actions' => ['logout'],
  24. 'allow' => true,
  25. 'roles' => ['@'],
  26. ],
  27. ],
  28. ],
  29. 'verbs' => [
  30. 'class' => VerbFilter::className(),
  31. 'actions' => [
  32. 'logout' => ['post'],
  33. ],
  34. ],
  35. ];
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function actions()
  41. {
  42. return [
  43. 'error' => [
  44. 'class' => 'yii\web\ErrorAction',
  45. ],
  46. 'captcha' => [
  47. 'class' => 'yii\captcha\CaptchaAction',
  48. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  49. ],
  50. ];
  51. }
  52. /**
  53. * Displays homepage.
  54. *
  55. * @return string
  56. */
  57. public function actionIndex()
  58. {
  59. $analytics=$this->initializeAnalytics();
  60. $response = $this->getReport($analytics);
  61. $this->printResults($response);
  62. exit;
  63. return $this->render('index');
  64. }
  65. function initializeAnalytics()
  66. {
  67. // Use the developers console and download your service account
  68. // credentials in JSON format. Place them in this directory or
  69. // change the key file location if necessary.
  70. $KEY_FILE_LOCATION = BASE_DIR . 'config/savvy-theory-278005-43552bf9fe94.json';
  71. // Create and configure a new client object.
  72. $client = new \Google_Client();
  73. $client->setApplicationName("Hello Analytics Reporting");
  74. $client->setAuthConfig($KEY_FILE_LOCATION);
  75. $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  76. $analytics = new \Google_Service_AnalyticsReporting($client);
  77. return $analytics;
  78. }
  79. /**
  80. * Queries the Analytics Reporting API V4.
  81. *
  82. * @param service An authorized Analytics Reporting API V4 service object.
  83. * @return The Analytics Reporting API V4 response.
  84. */
  85. function getReport($analytics) {
  86. // Replace with your view ID, for example XXXX.
  87. $VIEW_ID = "155703065";
  88. // Create the DateRange object.
  89. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  90. $dateRange->setStartDate("7daysAgo");
  91. $dateRange->setEndDate("today");
  92. $metrics=[];
  93. $dimensions=[];
  94. // Create the Metrics object.
  95. $sessions = new \Google_Service_AnalyticsReporting_Metric();
  96. $sessions->setExpression("ga:sessions");
  97. $sessions->setAlias("sessions");
  98. array_push($metrics,$sessions);
  99. // $users = new \Google_Service_AnalyticsReporting_Metric();
  100. // $users->setExpression("ga:users");
  101. // $users->setAlias("users");
  102. // array_push($metrics,$users);
  103. //跳出率
  104. $bounceRate = new \Google_Service_AnalyticsReporting_Metric();
  105. $bounceRate->setExpression("ga:bounceRate");
  106. $bounceRate->setAlias("bounceRate");
  107. array_push($metrics,$bounceRate);
  108. //
  109. $sessionDuration = new \Google_Service_AnalyticsReporting_Metric();
  110. $sessionDuration->setExpression("ga:sessionDuration");
  111. $sessionDuration->setAlias("sessionDuration");
  112. array_push($metrics,$sessionDuration);
  113. // $hits = new \Google_Service_AnalyticsReporting_Metric();
  114. // $hits->setExpression("ga:hits");
  115. // $hits->setAlias("hits");
  116. // array_push($metrics,$hits);
  117. //交易阶段
  118. // $shoppingStage = new \Google_Service_AnalyticsReporting_Dimension();
  119. // $shoppingStage->setName("ga:shoppingStage");
  120. // array_push($dimensions,$shoppingStage);
  121. $date = new \Google_Service_AnalyticsReporting_Dimension();
  122. $date->setName("ga:date");
  123. array_push($dimensions,$date);
  124. //交易次数
  125. $transactions = new \Google_Service_AnalyticsReporting_Metric();
  126. $transactions->setExpression("ga:transactions");
  127. $transactions->setAlias("transactions");
  128. array_push($metrics,$transactions);
  129. //电子商务转化率
  130. $transactionsPerSession = new \Google_Service_AnalyticsReporting_Metric();
  131. $transactionsPerSession->setExpression("ga:transactionsPerSession");
  132. $transactionsPerSession->setAlias("transactionsPerSession");
  133. array_push($metrics,$transactionsPerSession);
  134. $transactionRevenue = new \Google_Service_AnalyticsReporting_Metric();
  135. $transactionRevenue->setExpression("ga:transactionRevenue");
  136. $transactionRevenue->setAlias("transactionRevenue");
  137. array_push($metrics,$transactionRevenue);
  138. //
  139. $totalValue = new \Google_Service_AnalyticsReporting_Metric();
  140. $totalValue->setExpression("ga:totalValue");
  141. $totalValue->setAlias("totalValue");
  142. array_push($metrics,$totalValue);
  143. $itemQuantity = new \Google_Service_AnalyticsReporting_Metric();
  144. $itemQuantity->setExpression("ga:itemQuantity");
  145. $itemQuantity->setAlias("itemQuantity");
  146. array_push($metrics,$itemQuantity);
  147. $productAddsToCart = new \Google_Service_AnalyticsReporting_Metric();
  148. $productAddsToCart->setExpression("ga:productAddsToCart");
  149. $productAddsToCart->setAlias("productAddsToCart");
  150. array_push($metrics,$productAddsToCart);
  151. $productCheckouts = new \Google_Service_AnalyticsReporting_Metric();
  152. $productCheckouts->setExpression("ga:productCheckouts");
  153. $productCheckouts->setAlias("productCheckouts");
  154. array_push($metrics,$productCheckouts);
  155. // Create the ReportRequest object.
  156. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  157. $request->setViewId($VIEW_ID);
  158. $request->setDateRanges($dateRange);
  159. $request->setMetrics($metrics);
  160. $request->setDimensions($dimensions);
  161. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  162. $body->setReportRequests( array( $request) );
  163. return $analytics->reports->batchGet( $body );
  164. }
  165. /**
  166. * Parses and prints the Analytics Reporting API V4 response.
  167. *
  168. * @param An Analytics Reporting API V4 response.
  169. */
  170. function printResults($reports) {
  171. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  172. $report = $reports[ $reportIndex ];
  173. $header = $report->getColumnHeader();
  174. $dimensionHeaders = $header->getDimensions();
  175. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  176. $rows = $report->getData()->getRows();
  177. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  178. $row = $rows[ $rowIndex ];
  179. $dimensions = $row->getDimensions();
  180. $metrics = $row->getMetrics();
  181. if($dimensionHeaders&&$dimensions){
  182. for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  183. print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  184. echo"<br/>";
  185. }
  186. }
  187. if($metricHeaders&&$metrics){
  188. for ($j = 0; $j < count($metrics); $j++) {
  189. $values = $metrics[$j]->getValues();
  190. for ($k = 0; $k < count($values); $k++) {
  191. $entry = $metricHeaders[$k];
  192. print($entry->getName() . ": " . $values[$k] . "\n\r");
  193. echo"<br/>";
  194. }
  195. }
  196. }
  197. }
  198. }
  199. }
  200. /**
  201. * Login action.
  202. *
  203. * @return Response|string
  204. */
  205. public function actionLogin()
  206. {
  207. if (!Yii::$app->user->isGuest) {
  208. return $this->goHome();
  209. }
  210. $model = new LoginForm();
  211. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  212. return $this->goBack();
  213. }
  214. $model->password = '';
  215. return $this->render('login', [
  216. 'model' => $model,
  217. ]);
  218. }
  219. /**
  220. * Logout action.
  221. *
  222. * @return Response
  223. */
  224. public function actionLogout()
  225. {
  226. Yii::$app->user->logout();
  227. return $this->goHome();
  228. }
  229. /**
  230. * Displays contact page.
  231. *
  232. * @return Response|string
  233. */
  234. public function actionContact()
  235. {
  236. $model = new ContactForm();
  237. if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
  238. Yii::$app->session->setFlash('contactFormSubmitted');
  239. return $this->refresh();
  240. }
  241. return $this->render('contact', [
  242. 'model' => $model,
  243. ]);
  244. }
  245. /**
  246. * Displays about page.
  247. *
  248. * @return string
  249. */
  250. public function actionAbout()
  251. {
  252. return $this->render('about');
  253. }
  254. }