IndexController.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. //交易次数
  122. $transactions = new \Google_Service_AnalyticsReporting_Metric();
  123. $transactions->setExpression("ga:transactions");
  124. $transactions->setAlias("transactions");
  125. array_push($metrics,$transactions);
  126. //电子商务转化率
  127. $transactionsPerSession = new \Google_Service_AnalyticsReporting_Metric();
  128. $transactionsPerSession->setExpression("ga:transactionsPerSession");
  129. $transactionsPerSession->setAlias("transactionsPerSession");
  130. array_push($metrics,$transactionsPerSession);
  131. $transactionRevenue = new \Google_Service_AnalyticsReporting_Metric();
  132. $transactionRevenue->setExpression("ga:transactionRevenue");
  133. $transactionRevenue->setAlias("transactionRevenue");
  134. array_push($metrics,$transactionRevenue);
  135. //
  136. $totalValue = new \Google_Service_AnalyticsReporting_Metric();
  137. $totalValue->setExpression("ga:totalValue");
  138. $totalValue->setAlias("totalValue");
  139. array_push($metrics,$totalValue);
  140. $itemQuantity = new \Google_Service_AnalyticsReporting_Metric();
  141. $itemQuantity->setExpression("ga:itemQuantity");
  142. $itemQuantity->setAlias("itemQuantity");
  143. array_push($metrics,$itemQuantity);
  144. $productAddsToCart = new \Google_Service_AnalyticsReporting_Metric();
  145. $productAddsToCart->setExpression("ga:productAddsToCart");
  146. $productAddsToCart->setAlias("productAddsToCart");
  147. array_push($metrics,$productAddsToCart);
  148. $productCheckouts = new \Google_Service_AnalyticsReporting_Metric();
  149. $productCheckouts->setExpression("ga:productCheckouts");
  150. $productCheckouts->setAlias("productCheckouts");
  151. array_push($metrics,$productCheckouts);
  152. // Create the ReportRequest object.
  153. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  154. $request->setViewId($VIEW_ID);
  155. $request->setDateRanges($dateRange);
  156. $request->setMetrics($metrics);
  157. $request->setDimensions($dimensions);
  158. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  159. $body->setReportRequests( array( $request) );
  160. return $analytics->reports->batchGet( $body );
  161. }
  162. /**
  163. * Parses and prints the Analytics Reporting API V4 response.
  164. *
  165. * @param An Analytics Reporting API V4 response.
  166. */
  167. function printResults($reports) {
  168. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  169. $report = $reports[ $reportIndex ];
  170. $header = $report->getColumnHeader();
  171. $dimensionHeaders = $header->getDimensions();
  172. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  173. $rows = $report->getData()->getRows();
  174. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  175. $row = $rows[ $rowIndex ];
  176. $dimensions = $row->getDimensions();
  177. $metrics = $row->getMetrics();
  178. if($dimensionHeaders&&$dimensions){
  179. for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  180. print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  181. echo"<br/>";
  182. }
  183. }
  184. if($metricHeaders&&$metrics){
  185. for ($j = 0; $j < count($metrics); $j++) {
  186. $values = $metrics[$j]->getValues();
  187. for ($k = 0; $k < count($values); $k++) {
  188. $entry = $metricHeaders[$k];
  189. print($entry->getName() . ": " . $values[$k] . "\n\r");
  190. echo"<br/>";
  191. }
  192. }
  193. }
  194. }
  195. }
  196. }
  197. /**
  198. * Login action.
  199. *
  200. * @return Response|string
  201. */
  202. public function actionLogin()
  203. {
  204. if (!Yii::$app->user->isGuest) {
  205. return $this->goHome();
  206. }
  207. $model = new LoginForm();
  208. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  209. return $this->goBack();
  210. }
  211. $model->password = '';
  212. return $this->render('login', [
  213. 'model' => $model,
  214. ]);
  215. }
  216. /**
  217. * Logout action.
  218. *
  219. * @return Response
  220. */
  221. public function actionLogout()
  222. {
  223. Yii::$app->user->logout();
  224. return $this->goHome();
  225. }
  226. /**
  227. * Displays contact page.
  228. *
  229. * @return Response|string
  230. */
  231. public function actionContact()
  232. {
  233. $model = new ContactForm();
  234. if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
  235. Yii::$app->session->setFlash('contactFormSubmitted');
  236. return $this->refresh();
  237. }
  238. return $this->render('contact', [
  239. 'model' => $model,
  240. ]);
  241. }
  242. /**
  243. * Displays about page.
  244. *
  245. * @return string
  246. */
  247. public function actionAbout()
  248. {
  249. return $this->render('about');
  250. }
  251. }