Google Analytics API V4 does not work with GA4 account

文章推薦指數: 80 %
投票人數:10人

You are using the Google Analytics Reporting api that will only work with universal analytics accounts. If you are trying to access GA4 then you ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore GoogleAnalyticsAPIV4doesnotworkwithGA4account AskQuestion Asked 4monthsago Modified 4monthsago Viewed 636times 0 IsitpossibletogetdatafromnewGoogleAnalytics(GA4)accountsthroughAPIV4?Italwaysreturnsthefollowingerrormessage: {"error":{"code":403,"message":"Userdoesnothavesufficientpermissionsforthisprofile.","errors":[{"message":"Userdoesnothavesufficientpermissionsforthisprofile.","domain":"global","reason":"forbidden"}],"status":"PERMISSION_DENIED"}} IcandoitperfectlyonUAaccounts. IsthereanyAPI(webserverrequest-OAuth)specifictothisnewaccounttype? propertyid Hereisthecodeused(PHP): require_once__DIR__.'/vendor/autoload.php'; session_start(); $client=newGoogle_Client(); $client->setAuthConfig(__DIR__.'/FILE.json'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); $client->setAccessToken($_SESSION['access_token']); $analytics=newGoogle_Service_AnalyticsReporting($client); $response=getReport($analytics); printResults($response); functiongetReport($analytics){ $dateRange=newGoogle_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("7daysAgo"); $dateRange->setEndDate("today"); $sessions=newGoogle_Service_AnalyticsReporting_Metric(); $sessions->setExpression("name"); $sessions->setAlias("sessions"); $request=newGoogle_Service_AnalyticsReporting_ReportRequest(); $request->setViewId('307566943'); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions)); $body=newGoogle_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests(array($request)); return$analytics->reports->batchGet($body); } google-apigoogle-oauthgoogle-analytics-api Share Follow editedMar21at12:20 FBRC askedMar18at21:47 FBRCFBRC 7355bronzebadges 3 Couldyouedityourquestionandincludeminimalreproducibleexample – DaImTo Mar19at12:08 @DaImToUpdated,theerrorpersists:/ – FBRC Mar21at12:21 YouareusingtheGoogleAnalyticsReportingapithatwillonlyworkwithuniversalanalyticsaccounts.IfyouaretryingtoaccessGA4thenyouneedtousetheAnalyticsDataAPI.Pleasecheckmyanswer. – DaImTo Mar21at12:26 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 1 Userdoesnothavesufficientpermissionsforthisprofile Meansthattheuseryouhaveauthenticatedyourapplicationwith.DoesnothavepermissiontoaccesstheGoogleanalyticsviewyouaretryingtoextractdatafrom. TheissuecanalsobecausedifyouaretryingtousetheGoogleanalyticsreportingapiwithaGoogleanalyticsGA4account.AsGA4propertyidarenotthesameasUAviewids.Thesystemgetsconfusedandassumesyoujustdontaccess. Thesolutionistoauthenticatetheappwithauserthathasaccesstothatvieworgranttheuseraccess.Andtocheckthatyouareusingthecorrectapiforthetypeofgoogleanalyticsyouaretryingtoaccess. UAvsGA4 AlsorememberthattoextractdatefromaGA4accountyouneedtousetheGoogleanalyticsdataapi.IfyouhaveextracteddatafromUAaccountsyouhavebeenusingtheGoogleanalyticsreportingapi.ThesearetwocompletelydiffrentAPIswithdiffrentmethods. Googleanalyticsdataapiquickstart require'vendor/autoload.php'; useGoogle\Analytics\Data\V1beta\BetaAnalyticsDataClient; useGoogle\Analytics\Data\V1beta\DateRange; useGoogle\Analytics\Data\V1beta\Dimension; useGoogle\Analytics\Data\V1beta\Metric; /** *TODO(developer):ReplacethisvariablewithyourGoogleAnalytics4 *propertyIDbeforerunningthesample. */ $property_id='YOUR-GA4-PROPERTY-ID'; //Usingadefaultconstructorinstructstheclienttousethecredentials //specifiedinGOOGLE_APPLICATION_CREDENTIALSenvironmentvariable. $client=newBetaAnalyticsDataClient(); //MakeanAPIcall. $response=$client->runReport([ 'property'=>'properties/'.$property_id, 'dateRanges'=>[ newDateRange([ 'start_date'=>'2020-03-31', 'end_date'=>'today', ]), ], 'dimensions'=>[newDimension( [ 'name'=>'city', ] ), ], 'metrics'=>[newMetric( [ 'name'=>'activeUsers', ] ) ] ]); //PrintresultsofanAPIcall. print'Reportresult:'.PHP_EOL; foreach($response->getRows()as$row){ print$row->getDimensionValues()[0]->getValue() .''.$row->getMetricValues()[0]->getValue().PHP_EOL; } Share Follow editedMar21at12:30 answeredMar19at12:05 DaImToDaImTo 91.1k2626goldbadges156156silverbadges393393bronzebadges 2 Thanks.Thecodesentconnectsviaserviceaccount,viaoauthisitpossible? – FBRC Mar25at11:16 Serviceaccountsareoauth2.butifyoumeanrequestingconsentoftheuseryeahitsusingthegooglecloudclientlibrary.Youjustneedtoswapouttheauthorizationmethodtothatofthestandardoauth2method. – DaImTo Mar25at11:21 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedgoogle-apigoogle-oauthgoogle-analytics-apioraskyourownquestion. TheOverflowBlog DesignpatternsforasynchronousAPIcommunication GameBoyemulators,PowerPointdevelopers,andtheenduringappealofPokémon... FeaturedonMeta AnnouncingtheStacksEditorBetarelease! Trending:Anewanswersortingoption The[options]tagisbeingburninated Related 32 "Notsufficientpermissions"googleanalyticsAPIserviceaccount 45 GoogleAnalyticsAPI:"Userdoesnothavesufficientpermissionsforthisaccount." 0 GoogleAnalyticsReportingAPIV4with"Requesthadinvalidauthenticationcredentials" 0 GoogleAnalyticsAPI:autologinuserandfetchdata,showingerror"TheOAuthclientwasinvalid." 1 AnalyticsGoogleAPIError403:“UserdoesnothaveanyGoogleAnalyticsAccount” 0 AnalyticsAPI:Ican'tusetwodifferentAPIcredentialsonmyPC 1 ReadGA4(GoogleAnalytics4)sessionsviaAPI 1 CustomGoogleAnalyticsAPIscriptisworking,butrunningextremelyslow HotNetworkQuestions Isthereanycriminalimplicationoffalsifyingdocumentsdemandedbyaprivateparty? bashlooptoreplacemiddleofstringafteracertaincharacter SumofConvergentSeriesforProblemLikeSchrödinger’sCat Whatdateis74029onanIBMMainframe? WhathappensifIaccidentallygroundtheoutputofanLDOregulator? Identifyinganovelaboutfloatingislands,dragons,airshipsandamysteriousmachine TechniquesforCompensatingInductorSRF HowdoesatailplaneprovidedownforceifithasthesameAoAasthemainwing? Laymen'sdescriptionof"modals"toclients Whatisthistoolusedfor? Canahumancolonybeself-sustainingwithoutsunlightusingmushrooms? Countthecells DataImbalance:whatwouldbeanidealnumber(ratio)ofnewlyaddedclass'sdata? Geonodes,useimagetexture Howshouldwedoboxplotswithsmallsamples? JavaScriptfrontendforOdinProjectbooklibrarydatabase Howdoesoneshowthiscomplexexpressionequalsanaturalnumber? Whyisradioactivehalf-lifeconstant? WasthereaRussiansafehavencityforpoliticiansandscientists? DidSauronsuspectthattheRingwouldbedestroyed? Tannakian-typereconstructionofetalefundamentalgroup Whatdoes'that'referto? Whyhadclimatechangenotbeenprovenbeyonddoubtforsolong? setuploops;neverentersloop-restarting? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?