GA.php 37 KB

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