GA.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. <?php
  2. namespace app\lib;
  3. class GA{
  4. const SUPERNOVA_KEY_PATH= BASE_DIR . 'config/supernova.json';
  5. const ALIPEARL_KEY_PATH= BASE_DIR . 'config/alipearl.json';
  6. const WIGGINS_KEY_PATH= BASE_DIR . 'config/wiggins.json';
  7. const YOLISSA_KEY_PATH= BASE_DIR . 'config/yolissa.json';
  8. const ASTERIA_KEY_PATH= BASE_DIR . 'config/asteria.json';
  9. const WESTKISS_KEY_PATH= BASE_DIR . 'config/westkiss.json';
  10. private static $insances=[];
  11. private static function initializeAnalytics($dp){
  12. $KEY_FILE_LOCATION = self::getPath($dp);
  13. if(!$KEY_FILE_LOCATION){
  14. throw new \Exception("store 配置不存在");
  15. }
  16. $client = new \Google_Client();
  17. $client->setApplicationName("Hello Analytics Reporting");
  18. $client->setAuthConfig($KEY_FILE_LOCATION);
  19. $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  20. $analytics = new \Google_Service_AnalyticsReporting($client);
  21. return $analytics;
  22. }
  23. public static function getInstance($dp){
  24. if(isset(self::$insances[$dp])){
  25. return self::$insances[$dp];
  26. }else{
  27. self::$insances[$dp]=self::initializeAnalytics($dp);
  28. return self::$insances[$dp];
  29. }
  30. }
  31. private function getViewId($dp){
  32. $VIEW_ID="";
  33. switch($dp){
  34. case "1"://supernovahair
  35. $VIEW_ID="155703065";
  36. break;
  37. case "2"://asteriahair
  38. $VIEW_ID="162723112";
  39. break;
  40. case "3"://alipearlhair
  41. $VIEW_ID="148377136";
  42. break;
  43. case "4"://alipearlhair
  44. $VIEW_ID="152302477";
  45. break;
  46. case "5"://yolissahair
  47. $VIEW_ID="157127813";
  48. break;
  49. case "6"://wiggins
  50. $VIEW_ID="154631720";
  51. break;
  52. }
  53. return $VIEW_ID;
  54. }
  55. public static function getPath($dp){
  56. $path="";
  57. switch($dp){
  58. case "1"://supernovahair
  59. $path=self::SUPERNOVA_KEY_PATH;
  60. break;
  61. case "2"://asteriahair
  62. $path=self::ASTERIA_KEY_PATH;
  63. break;
  64. case "3"://alipearlhair
  65. $path=self::ALIPEARL_KEY_PATH;
  66. break;
  67. case "4"://westkiss
  68. $path=self::WESTKISS_KEY_PATH;
  69. break;
  70. case "5"://yolissahair
  71. $path=self::YOLISSA_KEY_PATH;
  72. break;
  73. case "6"://alipearlhair
  74. $path=self::WIGGINS_KEY_PATH;
  75. break;
  76. }
  77. return $path;
  78. }
  79. /*进一步封装
  80. *$config=[
  81. 'dp'=>'',
  82. 'metricArr'=[],
  83. 'dimensionArr'=[],
  84. 'dateRange'=[start_at,end_at]
  85. 'SegmentDimensionFilters'=>[[name,operate,expression]]
  86. 'oderBy'=>[name,order]
  87. ]
  88. *
  89. *
  90. *
  91. */
  92. public function getData($config){
  93. if(!$dp||!$dateRange||empty($config['metricArr'])){
  94. return false;
  95. }
  96. $metricArr=$config['metricArr'];
  97. $dimensionArr=$config['dimensionArr'];
  98. $analytics=self::getInstance($dp);
  99. $VIEW_ID = $this->getViewId($dp);//
  100. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  101. $request->setViewId($VIEW_ID);
  102. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  103. $dateRange->setStartDate($config['start_at']);
  104. $dateRange->setEndDate($config['end_at']);
  105. $request->setDateRanges($dateRange);
  106. $metrics=[];
  107. $dimensions=[];
  108. foreach($metricArr as $k=>$v){
  109. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  110. $Metric->setExpression($v);
  111. $Metric->setAlias($k);
  112. array_push($metrics,$Metric);
  113. }
  114. foreach($dimensionArr as $k=>$v){
  115. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  116. $Dimension->setName($v);
  117. array_push($dimensions,$Dimension);
  118. }
  119. $request->setMetrics($metrics);
  120. $request->setDimensions($dimensions);
  121. $segment=[];
  122. if(isset($config['SegmentDimensionFilters'])&&!empty($config['SegmentDimensionFilters'])){
  123. foreach($config['SegmentDimensionFilters'] as $filter){
  124. $segment[]=$this->setSegmentDimensionFilter($filter);
  125. }
  126. }
  127. if(isset($config['SegmentMetricFilters'])&&!empty($config['SegmentMetricFilters'])){
  128. foreach($config['SegmentMetricFilters'] as $filter){
  129. $segment[]=$this->setSegmentMetricFilters($filter);
  130. }
  131. }
  132. if(!empty($segment)){
  133. $request->setSegments(array($segment));
  134. }
  135. if(isset($config['orderBy'])&&!empty($config['orderBy'])){
  136. $orderBy=new \Google_Service_AnalyticsReporting_OrderBy();
  137. $orderBy->setFieldName($config['orderBy']['name']);
  138. $orderBy->setSortOrder($config['orderBy']['order']);
  139. $request->setOrderBys($orderBy);
  140. }
  141. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  142. $body->setReportRequests( array( $request) );
  143. $reports= $analytics->reports->batchGet( $body );
  144. $result=$this->getResults($reports);
  145. return $result;
  146. }
  147. private function setSegmentDimensionFilter($param){
  148. $dimensionFilter = new \Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  149. $dimensionFilter->setDimensionName($param['name']);
  150. $dimensionFilter->setOperator($param['operate']);
  151. $dimensionFilter->setExpressions($param['expression']);
  152. // Create Segment Filter Clause.
  153. $segmentFilterClause = new \Google_Service_AnalyticsReporting_SegmentFilterClause();
  154. $segmentFilterClause->setDimensionFilter($dimensionFilter);
  155. // Create the Or Filters for Segment.
  156. $orFiltersForSegment = new \Google_Service_AnalyticsReporting_OrFiltersForSegment();
  157. $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));
  158. // Create the Simple Segment.
  159. $simpleSegment = new \Google_Service_AnalyticsReporting_SimpleSegment();
  160. $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));
  161. // Create the Segment Filters.
  162. $segmentFilter = new \Google_Service_AnalyticsReporting_SegmentFilter();
  163. $segmentFilter->setSimpleSegment($simpleSegment);
  164. $segmentFilter->setNot(True);
  165. // Create the Segment Definition.
  166. $segmentDefinition = new \Google_Service_AnalyticsReporting_SegmentDefinition();
  167. $segmentDefinition->setSegmentFilters(array($segmentFilter));
  168. $dynamicSegment = new \Google_Service_AnalyticsReporting_DynamicSegment();
  169. $dynamicSegment->setSessionSegment($segmentDefinition);
  170. $dynamicSegment->setName($param['name']);
  171. $segment = new \Google_Service_AnalyticsReporting_Segment();
  172. $segment->setDynamicSegment($dynamicSegment);
  173. return $segment;
  174. }
  175. public function contentpages($dp,$start_at,$end_at){
  176. $analytics=self::getInstance($dp);
  177. $metricArr=[
  178. 'pageviews'=>"ga:pageviews",
  179. 'uniquePageviews'=>"ga:uniquePageviews",
  180. 'avgTimeOnPage'=>"ga:avgTimeOnPage",
  181. 'entrances'=>"ga:entrances",
  182. 'bounceRate'=>"ga:bounceRate",
  183. 'exitRate'=>"ga:exitRate",
  184. 'pageValue'=>"ga:pageValue",
  185. ];
  186. $dimensionArr=[
  187. 'pagePath'=>'ga:pagePath',
  188. 'date'=>"ga:date",
  189. ];
  190. $VIEW_ID = $this->getViewId($dp);//
  191. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  192. $dateRange->setStartDate($start_at);
  193. $dateRange->setEndDate($end_at);
  194. $metrics=[];
  195. $dimensions=[];
  196. foreach($metricArr as $k=>$v){
  197. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  198. $Metric->setExpression($v);
  199. $Metric->setAlias($k);
  200. array_push($metrics,$Metric);
  201. }
  202. foreach($dimensionArr as $k=>$v){
  203. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  204. $Dimension->setName($v);
  205. array_push($dimensions,$Dimension);
  206. }
  207. $pageviewsFilter = new \Google_Service_AnalyticsReporting_MetricFilter();
  208. $pageviewsFilter->setMetricName("ga:pageviews");
  209. $pageviewsFilter->setOperator("GREATER_THAN");
  210. $pageviewsFilter->setComparisonValue("1");
  211. $MetricFilterClause=new \Google_Service_AnalyticsReporting_MetricFilterClause();
  212. $MetricFilterClause->setFilters(array($pageviewsFilter));
  213. $segmentDimensions = new \Google_Service_AnalyticsReporting_Dimension();
  214. $segmentDimensions->setName("ga:segment");
  215. array_push($dimensions,$segmentDimensions);
  216. // Create Dimension Filter.
  217. $dimensionFilter = new \Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  218. $dimensionFilter->setDimensionName("ga:pagePath");
  219. $dimensionFilter->setOperator("REGEXP");
  220. $dimensionFilter->setExpressions(array("(fbclid|catalogsearch)"));
  221. // Create Segment Filter Clause.
  222. $segmentFilterClause = new \Google_Service_AnalyticsReporting_SegmentFilterClause();
  223. $segmentFilterClause->setDimensionFilter($dimensionFilter);
  224. // Create the Or Filters for Segment.
  225. $orFiltersForSegment = new \Google_Service_AnalyticsReporting_OrFiltersForSegment();
  226. $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));
  227. // Create the Simple Segment.
  228. $simpleSegment = new \Google_Service_AnalyticsReporting_SimpleSegment();
  229. $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));
  230. // Create the Segment Filters.
  231. $segmentFilter = new \Google_Service_AnalyticsReporting_SegmentFilter();
  232. $segmentFilter->setSimpleSegment($simpleSegment);
  233. $segmentFilter->setNot(True);
  234. // Create the Segment Definition.
  235. $segmentDefinition = new \Google_Service_AnalyticsReporting_SegmentDefinition();
  236. $segmentDefinition->setSegmentFilters(array($segmentFilter));
  237. $dynamicSegment = new \Google_Service_AnalyticsReporting_DynamicSegment();
  238. $dynamicSegment->setSessionSegment($segmentDefinition);
  239. $dynamicSegment->setName('pagePath');
  240. $segment = new \Google_Service_AnalyticsReporting_Segment();
  241. $segment->setDynamicSegment($dynamicSegment);
  242. $orderBy=new \Google_Service_AnalyticsReporting_OrderBy();
  243. $orderBy->setFieldName('ga:pageviews');
  244. $orderBy->setSortOrder("DESCENDING");
  245. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  246. $request->setViewId($VIEW_ID);
  247. $request->setDateRanges($dateRange);
  248. $request->setMetrics($metrics);
  249. $request->setDimensions($dimensions);
  250. $request->setSegments(array($segment));
  251. $request->setOrderBys($orderBy);
  252. $request->setPageSize(5000);
  253. $request->setMetricFilterClauses($MetricFilterClause);
  254. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  255. $body->setReportRequests( array( $request) );
  256. $reports= $analytics->reports->batchGet( $body );
  257. $result=$this->getResults($reports);
  258. return $result;
  259. }
  260. public function trafficsource($dp,$start_at,$end_at){
  261. $analytics=self::getInstance($dp);
  262. $metricArr=[
  263. 'users'=>"ga:users",
  264. 'newUsers'=>"ga:newUsers",
  265. 'sessions'=>"ga:sessions",
  266. 'bounceRate'=>"ga:bounceRate",
  267. 'pageviewsPerSession'=>"ga:pageviewsPerSession",
  268. 'avgSessionDuration'=>"ga:avgSessionDuration",
  269. 'transactionsPerVisit'=>"ga:transactionsPerVisit",
  270. 'transactions'=>"ga:transactions",
  271. 'transactionRevenue'=>"ga:transactionRevenue",
  272. ];
  273. $dimensionArr=[
  274. 'pagePath'=>'ga:source',
  275. 'date'=>"ga:date",
  276. 'channelGrouping'=>"ga:channelGrouping",
  277. 'landingPagePath'=>"ga:landingPagePath",
  278. 'keyword'=>"ga:keyword",
  279. 'socialNetwork'=>"ga:socialNetwork",
  280. ];
  281. $VIEW_ID = $this->getViewId($dp);//
  282. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  283. $dateRange->setStartDate($start_at);
  284. $dateRange->setEndDate($end_at);
  285. $metrics=[];
  286. $dimensions=[];
  287. foreach($metricArr as $k=>$v){
  288. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  289. $Metric->setExpression($v);
  290. $Metric->setAlias($k);
  291. array_push($metrics,$Metric);
  292. }
  293. foreach($dimensionArr as $k=>$v){
  294. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  295. $Dimension->setName($v);
  296. array_push($dimensions,$Dimension);
  297. }
  298. $segmentDimensions = new \Google_Service_AnalyticsReporting_Dimension();
  299. $segmentDimensions->setName("ga:segment");
  300. array_push($dimensions,$segmentDimensions);
  301. // Create Dimension Filter.
  302. $dimensionFilter = new \Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  303. $dimensionFilter->setDimensionName("ga:source");
  304. $dimensionFilter->setOperator("REGEXP");
  305. $dimensionFilter->setExpressions(array("(fbclid|catalogsearch)"));
  306. // Create Segment Filter Clause.
  307. $segmentFilterClause = new \Google_Service_AnalyticsReporting_SegmentFilterClause();
  308. $segmentFilterClause->setDimensionFilter($dimensionFilter);
  309. // Create the Or Filters for Segment.
  310. $orFiltersForSegment = new \Google_Service_AnalyticsReporting_OrFiltersForSegment();
  311. $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));
  312. // Create the Simple Segment.
  313. $simpleSegment = new \Google_Service_AnalyticsReporting_SimpleSegment();
  314. $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));
  315. // Create the Segment Filters.
  316. $segmentFilter = new \Google_Service_AnalyticsReporting_SegmentFilter();
  317. $segmentFilter->setSimpleSegment($simpleSegment);
  318. $segmentFilter->setNot(True);
  319. // Create the Segment Definition.
  320. $segmentDefinition = new \Google_Service_AnalyticsReporting_SegmentDefinition();
  321. $segmentDefinition->setSegmentFilters(array($segmentFilter));
  322. $dynamicSegment = new \Google_Service_AnalyticsReporting_DynamicSegment();
  323. $dynamicSegment->setSessionSegment($segmentDefinition);
  324. $dynamicSegment->setName('trafficsources filter');
  325. $segment = new \Google_Service_AnalyticsReporting_Segment();
  326. $segment->setDynamicSegment($dynamicSegment);
  327. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  328. $request->setViewId($VIEW_ID);
  329. $request->setDateRanges($dateRange);
  330. $request->setMetrics($metrics);
  331. $request->setDimensions($dimensions);
  332. $request->setSegments(array($segment));
  333. $request->setPageSize(5000);
  334. // $request->setOrderBys($orderBy);
  335. // $request->setMetricFilterClauses($MetricFilterClause);
  336. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  337. $body->setReportRequests( array( $request) );
  338. $reports= $analytics->reports->batchGet( $body );
  339. $result=$this->getResults($reports);
  340. return $result;
  341. }
  342. public function visitors_geo($dp,$start_at,$end_at){
  343. $analytics=self::getInstance($dp);
  344. $dimensionArr=[
  345. 'country'=>'ga:country',
  346. 'region'=>"ga:region",
  347. ];
  348. $metricArr=[
  349. 'transactions'=>"ga:transactions",
  350. 'transactionRevenue'=>"ga:transactionRevenue",
  351. ];
  352. $VIEW_ID = $this->getViewId($dp);//
  353. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  354. $dateRange->setStartDate($start_at);
  355. $dateRange->setEndDate($end_at);
  356. $metrics=[];
  357. $dimensions=[];
  358. foreach($metricArr as $k=>$v){
  359. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  360. $Metric->setExpression($v);
  361. $Metric->setAlias($k);
  362. array_push($metrics,$Metric);
  363. }
  364. foreach($dimensionArr as $k=>$v){
  365. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  366. $Dimension->setName($v);
  367. array_push($dimensions,$Dimension);
  368. }
  369. $orderBy=new \Google_Service_AnalyticsReporting_OrderBy();
  370. $orderBy->setFieldName('ga:transactions');
  371. $orderBy->setSortOrder("DESCENDING");
  372. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  373. $request->setViewId($VIEW_ID);
  374. $request->setDateRanges($dateRange);
  375. $request->setMetrics($metrics);
  376. $request->setDimensions($dimensions);
  377. $request->setOrderBys($orderBy);
  378. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  379. $body->setReportRequests( array( $request) );
  380. $reports= $analytics->reports->batchGet( $body );
  381. $result=$this->getResults($reports);
  382. return $result;
  383. }
  384. public function product($dp,$start_at,$end_at){
  385. $analytics=self::getInstance($dp);
  386. $dimensionArr=[
  387. 'productName'=>'ga:productName',
  388. ];
  389. $metricArr=[
  390. 'itemRevenue'=>"ga:itemRevenue",
  391. 'uniquePurchases'=>"ga:uniquePurchases",
  392. 'itemQuantity'=>"ga:itemQuantity",
  393. ];
  394. $VIEW_ID = $this->getViewId($dp);//
  395. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  396. $dateRange->setStartDate($start_at);
  397. $dateRange->setEndDate($end_at);
  398. $metrics=[];
  399. $dimensions=[];
  400. foreach($metricArr as $k=>$v){
  401. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  402. $Metric->setExpression($v);
  403. $Metric->setAlias($k);
  404. array_push($metrics,$Metric);
  405. }
  406. foreach($dimensionArr as $k=>$v){
  407. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  408. $Dimension->setName($v);
  409. array_push($dimensions,$Dimension);
  410. }
  411. $orderBy=new \Google_Service_AnalyticsReporting_OrderBy();
  412. $orderBy->setFieldName('ga:itemQuantity');
  413. $orderBy->setSortOrder("DESCENDING");
  414. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  415. $request->setViewId($VIEW_ID);
  416. $request->setDateRanges($dateRange);
  417. $request->setMetrics($metrics);
  418. $request->setDimensions($dimensions);
  419. $request->setOrderBys($orderBy);
  420. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  421. $body->setReportRequests( array( $request) );
  422. $reports= $analytics->reports->batchGet( $body );
  423. $result=$this->getResults($reports);
  424. return $result;
  425. }
  426. public function visitors_type($dp,$start_at,$end_at){
  427. $analytics=self::getInstance($dp);
  428. $dimensionArr=[
  429. 'userType'=>'ga:userType',
  430. 'date'=>'ga:date',
  431. ];
  432. $metricArr=[
  433. 'users'=>"ga:users",
  434. 'newUsers'=>"ga:newUsers",
  435. ];
  436. $VIEW_ID = $this->getViewId($dp);//
  437. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  438. $dateRange->setStartDate($start_at);
  439. $dateRange->setEndDate($end_at);
  440. $metrics=[];
  441. $dimensions=[];
  442. foreach($metricArr as $k=>$v){
  443. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  444. $Metric->setExpression($v);
  445. $Metric->setAlias($k);
  446. array_push($metrics,$Metric);
  447. }
  448. foreach($dimensionArr as $k=>$v){
  449. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  450. $Dimension->setName($v);
  451. array_push($dimensions,$Dimension);
  452. }
  453. // $orderBy=new \Google_Service_AnalyticsReporting_OrderBy();
  454. // $orderBy->setFieldName('ga:itemQuantity');
  455. // $orderBy->setSortOrder("DESCENDING");
  456. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  457. $request->setViewId($VIEW_ID);
  458. $request->setDateRanges($dateRange);
  459. $request->setMetrics($metrics);
  460. $request->setDimensions($dimensions);
  461. // $request->setOrderBys($orderBy);
  462. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  463. $body->setReportRequests( array( $request) );
  464. $reports= $analytics->reports->batchGet( $body );
  465. $result=$this->getResults($reports);
  466. return $result;
  467. }
  468. public function productInfo($productName,$dp,$start_at,$end_at){
  469. $analytics=self::getInstance($dp);
  470. $dimensionArr=[
  471. 'productName'=>'ga:productName',
  472. ];
  473. $metricArr=[
  474. 'itemRevenue'=>"ga:itemRevenue",
  475. 'revenuePerItem'=>"ga:revenuePerItem",
  476. 'productRefundAmount'=>"ga:productRefundAmount",
  477. 'quantityAddedToCart'=>"ga:quantityAddedToCart",
  478. // 'quantityRemovedFromCart'=>"ga:quantityRemovedFromCart",
  479. 'itemQuantity'=>"ga:itemQuantity",
  480. 'productListViews'=>"ga:productListViews",
  481. 'productDetailViews'=>"ga:productDetailViews",
  482. 'productAddsToCart'=>"ga:productAddsToCart",
  483. // 'productRemovesFromCart'=>"ga:productRemovesFromCart",
  484. 'productCheckouts'=>"ga:productCheckouts",
  485. 'uniquePurchases'=>"ga:uniquePurchases",
  486. ];
  487. $VIEW_ID = $this->getViewId($dp);//
  488. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  489. $dateRange->setStartDate($start_at);
  490. $dateRange->setEndDate($end_at);
  491. $metrics=[];
  492. $dimensions=[];
  493. foreach($metricArr as $k=>$v){
  494. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  495. $Metric->setExpression($v);
  496. $Metric->setAlias($k);
  497. array_push($metrics,$Metric);
  498. }
  499. foreach($dimensionArr as $k=>$v){
  500. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  501. $Dimension->setName($v);
  502. array_push($dimensions,$Dimension);
  503. }
  504. $skuFilter = new \Google_Service_AnalyticsReporting_DimensionFilter();
  505. $skuFilter->setDimensionName("ga:productName");
  506. $skuFilter->setOperator("EXACT");
  507. $skuFilter->setExpressions([$productName]);
  508. $MetricFilterClause=new \Google_Service_AnalyticsReporting_MetricFilterClause();
  509. $MetricFilterClause->setFilters(array($skuFilter));
  510. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  511. $request->setViewId($VIEW_ID);
  512. $request->setDateRanges($dateRange);
  513. $request->setMetrics($metrics);
  514. $request->setDimensions($dimensions);
  515. $request->setDimensionFilterClauses($MetricFilterClause);
  516. // $request->setOrderBys($orderBy);
  517. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  518. $body->setReportRequests( array( $request) );
  519. $reports= $analytics->reports->batchGet( $body );
  520. $result=$this->getResults($reports);
  521. return $result;
  522. }
  523. public function goals($dp,$metricArr,$start_at,$end_at){
  524. $analytics=self::getInstance($dp);
  525. $dimensionArr=[
  526. // 'date'=>'ga:date',
  527. // 'sessionCount'=>'ga:sessionCount',
  528. ];
  529. $VIEW_ID = $this->getViewId($dp);//
  530. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  531. $dateRange->setStartDate($start_at);
  532. $dateRange->setEndDate($end_at);
  533. $metrics=[];
  534. $dimensions=[];
  535. foreach($metricArr as $k=>$v){
  536. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  537. $Metric->setExpression($v);
  538. $Metric->setAlias($k);
  539. array_push($metrics,$Metric);
  540. }
  541. foreach($dimensionArr as $k=>$v){
  542. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  543. $Dimension->setName($v);
  544. array_push($dimensions,$Dimension);
  545. }
  546. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  547. $request->setViewId($VIEW_ID);
  548. $request->setDateRanges($dateRange);
  549. $request->setMetrics($metrics);
  550. $request->setDimensions($dimensions);
  551. // $request->setOrderBys($orderBy);
  552. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  553. $body->setReportRequests( array( $request) );
  554. $reports= $analytics->reports->batchGet( $body );
  555. $result=$this->getResults($reports);
  556. return $result;
  557. }
  558. public function regionProduct($region,$dp,$start_at,$end_at){
  559. $analytics=self::getInstance($dp);
  560. $dimensionArr=[
  561. 'region'=>'ga:region',
  562. ];
  563. $metricArr=[
  564. 'itemRevenue'=>"ga:itemRevenue",
  565. 'revenuePerItem'=>"ga:revenuePerItem",
  566. 'productRefundAmount'=>"ga:productRefundAmount",
  567. 'quantityAddedToCart'=>"ga:quantityAddedToCart",
  568. // 'quantityRemovedFromCart'=>"ga:quantityRemovedFromCart",
  569. 'itemQuantity'=>"ga:itemQuantity",
  570. 'productListViews'=>"ga:productListViews",
  571. 'productDetailViews'=>"ga:productDetailViews",
  572. 'productAddsToCart'=>"ga:productAddsToCart",
  573. // 'productRemovesFromCart'=>"ga:productRemovesFromCart",
  574. 'productCheckouts'=>"ga:productCheckouts",
  575. // 'uniquePurchases'=>"ga:uniquePurchases",
  576. 'transactions'=>"ga:transactions",
  577. ];
  578. $VIEW_ID = $this->getViewId($dp);//
  579. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  580. $dateRange->setStartDate($start_at);
  581. $dateRange->setEndDate($end_at);
  582. $metrics=[];
  583. $dimensions=[];
  584. foreach($metricArr as $k=>$v){
  585. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  586. $Metric->setExpression($v);
  587. $Metric->setAlias($k);
  588. array_push($metrics,$Metric);
  589. }
  590. foreach($dimensionArr as $k=>$v){
  591. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  592. $Dimension->setName($v);
  593. array_push($dimensions,$Dimension);
  594. }
  595. $regionFilter = new \Google_Service_AnalyticsReporting_DimensionFilter();
  596. $regionFilter->setDimensionName("ga:region");
  597. $regionFilter->setOperator("EXACT");
  598. $regionFilter->setExpressions([$region]);
  599. $MetricFilterClause=new \Google_Service_AnalyticsReporting_MetricFilterClause();
  600. $MetricFilterClause->setFilters(array($regionFilter));
  601. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  602. $request->setViewId($VIEW_ID);
  603. $request->setDateRanges($dateRange);
  604. $request->setMetrics($metrics);
  605. $request->setDimensions($dimensions);
  606. $request->setDimensionFilterClauses($MetricFilterClause);
  607. // $request->setOrderBys($orderBy);
  608. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  609. $body->setReportRequests( array( $request) );
  610. $reports= $analytics->reports->batchGet( $body );
  611. $result=$this->getResults($reports);
  612. return $result;
  613. }
  614. public function storeData($dp,$start_at,$end_at){
  615. $analytics=self::getInstance($dp);
  616. $dimensionArr=[
  617. // 'campaign'=>'ga:campaign'
  618. ];
  619. $metricArr=[
  620. '销量'=>"ga:itemQuantity",
  621. '订单量'=>"ga:transactions",
  622. '订单金额'=>"ga:transactionRevenue",
  623. '广告点击次数'=>"ga:adClicks",//点击次数
  624. '广告花费'=>"ga:adCost",//成本
  625. 'CTR'=>"ga:CTR",//点击率
  626. 'ROAS'=>"ga:ROAS",//回报率
  627. ];
  628. $VIEW_ID = $this->getViewId($dp);//
  629. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  630. $dateRange->setStartDate($start_at);
  631. $dateRange->setEndDate($end_at);
  632. $metrics=[];
  633. $dimensions=[];
  634. foreach($metricArr as $k=>$v){
  635. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  636. $Metric->setExpression($v);
  637. $Metric->setAlias($k);
  638. array_push($metrics,$Metric);
  639. }
  640. foreach($dimensionArr as $k=>$v){
  641. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  642. $Dimension->setName($v);
  643. array_push($dimensions,$Dimension);
  644. }
  645. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  646. $request->setViewId($VIEW_ID);
  647. $request->setDateRanges($dateRange);
  648. $request->setMetrics($metrics);
  649. $request->setDimensions($dimensions);
  650. // $request->setOrderBys($orderBy);
  651. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  652. $body->setReportRequests( array( $request) );
  653. $reports= $analytics->reports->batchGet( $body );
  654. $result=$this->getResults($reports);
  655. return $result[0]??[];
  656. }
  657. public function storeSellData($dp,$start_at,$end_at,$type="day"){
  658. $analytics=self::getInstance($dp);
  659. switch($type){
  660. case "day":
  661. $dimensionArr=[
  662. 'date'=>'ga:date',
  663. ];
  664. break;
  665. case "hour":
  666. $dimensionArr=[
  667. 'date'=>'ga:date',
  668. 'hour'=>'ga:hour'
  669. ];
  670. break;
  671. case "week":
  672. $dimensionArr=[
  673. 'year'=>'ga:isoYear',
  674. 'week'=>'ga:isoWeek',
  675. ];
  676. break;
  677. case "month":
  678. $dimensionArr=[
  679. 'year'=>'ga:year',
  680. 'month'=>'ga:month',
  681. ];
  682. break;
  683. }
  684. $metricArr=[
  685. 'itemQuantity'=>"ga:itemQuantity",
  686. ];
  687. $VIEW_ID = $this->getViewId($dp);//
  688. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  689. $dateRange->setStartDate($start_at);
  690. $dateRange->setEndDate($end_at);
  691. $metrics=[];
  692. $dimensions=[];
  693. foreach($metricArr as $k=>$v){
  694. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  695. $Metric->setExpression($v);
  696. $Metric->setAlias($k);
  697. array_push($metrics,$Metric);
  698. }
  699. foreach($dimensionArr as $k=>$v){
  700. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  701. $Dimension->setName($v);
  702. array_push($dimensions,$Dimension);
  703. }
  704. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  705. $request->setViewId($VIEW_ID);
  706. $request->setDateRanges($dateRange);
  707. $request->setMetrics($metrics);
  708. $request->setDimensions($dimensions);
  709. // $request->setOrderBys($orderBy);
  710. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  711. $body->setReportRequests( array( $request) );
  712. $reports= $analytics->reports->batchGet( $body );
  713. $result=$this->getResults($reports);
  714. return $result;
  715. }
  716. public function trafficsource_overview($dp,$start_at,$end_at){
  717. $analytics=self::getInstance($dp);
  718. $dimensionArr=[
  719. 'channelGrouping'=>'ga:channelGrouping',
  720. ];
  721. $metricArr=[
  722. 'users'=>"ga:users",
  723. 'newUsers'=>"ga:newUsers",
  724. 'sessions'=>"ga:sessions",
  725. 'bounceRate'=>"ga:bounceRate",
  726. 'transactionsPerSession'=>"ga:transactionsPerSession",
  727. 'transactionRevenue'=>"ga:transactionRevenue",
  728. 'transactions'=>"ga:transactions",
  729. ];
  730. $VIEW_ID = $this->getViewId($dp);//
  731. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  732. $dateRange->setStartDate($start_at);
  733. $dateRange->setEndDate($end_at);
  734. $metrics=[];
  735. $dimensions=[];
  736. foreach($metricArr as $k=>$v){
  737. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  738. $Metric->setExpression($v);
  739. $Metric->setAlias($k);
  740. array_push($metrics,$Metric);
  741. }
  742. foreach($dimensionArr as $k=>$v){
  743. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  744. $Dimension->setName($v);
  745. array_push($dimensions,$Dimension);
  746. }
  747. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  748. $request->setViewId($VIEW_ID);
  749. $request->setDateRanges($dateRange);
  750. $request->setMetrics($metrics);
  751. $request->setDimensions($dimensions);
  752. // $request->setOrderBys($orderBy);
  753. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  754. $body->setReportRequests( array( $request) );
  755. $reports= $analytics->reports->batchGet( $body );
  756. $result=$this->getResults($reports);
  757. return $result;
  758. }
  759. public function googleAds(){
  760. $analytics=self::getInstance($dp);
  761. $dimensionArr=[
  762. 'adwordsCampaignID'=>'ga:adwordsCampaignID',
  763. ];
  764. $metricArr=[
  765. 'adClicks'=>"ga:adClicks",
  766. 'adCost'=>"ga:adCost",
  767. 'CPC'=>"ga:CPC",
  768. 'users'=>"ga:users",
  769. 'sessions'=>"ga:sessions",
  770. 'bounceRate'=>"ga:bounceRate",
  771. 'transactionsPerSession'=>"ga:transactionsPerSession",
  772. 'transactionRevenue'=>"ga:transactionRevenue",
  773. 'transactions'=>"ga:transactions",
  774. ];
  775. $VIEW_ID = $this->getViewId($dp);//
  776. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  777. $dateRange->setStartDate($start_at);
  778. $dateRange->setEndDate($end_at);
  779. $metrics=[];
  780. $dimensions=[];
  781. foreach($metricArr as $k=>$v){
  782. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  783. $Metric->setExpression($v);
  784. $Metric->setAlias($k);
  785. array_push($metrics,$Metric);
  786. }
  787. foreach($dimensionArr as $k=>$v){
  788. $Dimension = new \Google_Service_AnalyticsReporting_Dimension();
  789. $Dimension->setName($v);
  790. array_push($dimensions,$Dimension);
  791. }
  792. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  793. $request->setViewId($VIEW_ID);
  794. $request->setDateRanges($dateRange);
  795. $request->setMetrics($metrics);
  796. $request->setDimensions($dimensions);
  797. // $request->setOrderBys($orderBy);
  798. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  799. $body->setReportRequests( array( $request) );
  800. $reports= $analytics->reports->batchGet( $body );
  801. $result=$this->getResults($reports);
  802. return $result;
  803. }
  804. function getResults($reports) {
  805. $data=[];
  806. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  807. $item=[];
  808. $report = $reports[ $reportIndex ];
  809. $header = $report->getColumnHeader();
  810. $dimensionHeaders = $header->getDimensions();
  811. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  812. $rows = $report->getData()->getRows();
  813. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  814. $row = $rows[ $rowIndex ];
  815. $dimensions = $row->getDimensions();
  816. $metrics = $row->getMetrics();
  817. if($dimensionHeaders&&$dimensions){
  818. for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  819. $header = $dimensionHeaders[$i];
  820. $header=str_replace('ga:','',$header);
  821. $item[$header]=$dimensions[$i];
  822. // print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  823. // echo"<br/>";
  824. }
  825. // $date=$dimensions[0];
  826. // $date=date('Y-m-d',strtotime($date));
  827. }
  828. if($metricHeaders&&$metrics){
  829. for ($j = 0; $j < count($metrics); $j++) {
  830. $values = $metrics[$j]->getValues();
  831. for ($k = 0; $k < count($values); $k++) {
  832. $entry = $metricHeaders[$k];
  833. $item[$entry->getName()]=$values[$k];
  834. // print($entry->getName() . ": " . $values[$k] . "\n\r");
  835. // echo"<br/>";
  836. }
  837. }
  838. }
  839. $data[]=$item;
  840. }
  841. }
  842. return $data;
  843. }
  844. }