Google Analytics API:“用户对此个人资料没有足够的权限

时间:2018-02-28 20:53:49

标签: google-api

我收到此错误消息:

{error: {…}}
error:
    code:
        403
errors:
    [{…}]
    message: "User does not have sufficient permissions for this profile."

Here is a screen-shot of my dashboard,(the two white lines on the bottom should contain text

我这是作为求职面试的一个案例,在他们取消对我们的数据的访问后,我再也无法使用“案例”,即使是我自己的谷歌分析数据(我是所有者)?

我创建了一个新项目并更新了我的clientID。它部分工作,图表正常加载并在我更改日期时更新,但我的其他2个请求获取403消息并且不显示任何内容。

<script>
    (function(w, d, s, g, js, fs) {
        g = w.gapi || (w.gapi = {});
        g.analytics = {
            q: [],
            ready: function(f) {
                this.q.push(f);
            }
        };
        js = d.createElement(s);
        fs = d.getElementsByTagName(s)[0];
        js.src = 'https://apis.google.com/js/platform.js';
        fs.parentNode.insertBefore(js, fs);
        js.onload = function() {
            g.load('analytics');
        };
    }(window, document, 'script'));
</script>
<!-- Include the ViewSelector2 component script. -->
<script src="view-selector2.js"></script>
<!-- Include the DateRangeSelector component script. -->
<script src="date-range-selector.js"></script>
<div id="top">
    <h1 id="view-name"></h1>
    <div id="embed-api-auth-container"></div>
    <div id="view-selector-container"></div>
    <hr>
    <br>
    <div class="container">
        <div class="row">
            <div class="col">
                <div id="date-range-selector-1-container"></div>
            </div>
        </div>
    </div>
</div>
<div id="mainContent">
    <div id="containerStyle">
        <div class="container">
            <div class="row">
                <div class="col">
                    <div id="date-range-selector-1-container"></div>
                    <div id="data-chart-1-container"></div>
                </div>
            </div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col colLeft">
                    <div id="sessionsPrDayCal"></div>
                    <div id="sessionsPrDayArray"></div>
                    <div id="sessionsPrDayArrayTo"></div>
                </div>
                <div class="col colRight">
                    <div id="test"></div>
                    <div id="data"></div>
                    <div id="dataTo"></div>
                    <div id="main-chart-container"></div>
                    <div id="breakdown-chart-container"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    gapi.analytics.ready(function() {
        /**
         * Authorizinge the user
         */
        /*Global values */
        var dayToBe = 14;

        gapi.analytics.auth.authorize({
            container: 'embed-api-auth-container',
            clientid: 'MYIDWASHERE'
        });

        var viewSelector = new gapi.analytics.ext.ViewSelector2({
            container: 'view-selector-container'
        }).execute();

        /**
         * Store a set of common DataChart config options since they're shared by
         * both of the charts we're about to make.
         */
        var commonConfig = {
            query: {
                metrics: 'ga:sessions',
                dimensions: 'ga:date'
            },
            chart: {
                type: 'LINE',
                options: {
                    width: '100%'
                }
            }
        };

        /**
         * Query params representing the first chart's date range.
         */
        var dateRange1 = {
            'start-date': '14daysAgo',
            'end-date': 'today'
        };

        /**
         * Create a new DateRangeSelector instance to be rendered inside of an
         * element with the id "date-range-selector-1-container", set its date range
         * and then render it to the page.
         */


        var dateRangeSelector1 = new gapi.analytics.ext.DateRangeSelector({
                container: 'date-range-selector-1-container'
            })
            .set(dateRange1)
            .execute();

        /**
         * Create a new DataChart instance with the given query parameters
         * and Google chart options. It will be rendered inside an element
         * with the id "data-chart-1-container".
         */
        //Denne endrer datoen hvis brukeren har endret tidsperiode
        var dataChart1 = new gapi.analytics.googleCharts.DataChart(commonConfig)
            .set({
                query: dateRange1
            })
            .set({
                chart: {
                    container: 'data-chart-1-container'
                }
            });

        /**
         * Register a handler to run whenever the user changes the view.
         * The handler will update both dataCharts as well as updating the title
         * of the dashboard.
         */
        //Checks the total amount of results of direct
        var report = new gapi.analytics.report.Data({
            query: {
                ids: 'ga:76988010',
                metrics: 'ga:sessions',
                dimensions: 'ga:source'
            }
        }).set({
            query: dateRange1
        });

        report.execute();
          report.on('error', function(response) {
            console.log("Dette er feilmeldingen jeg får");

              console.log(response);


          });
        report.on('success', function(response) {


          console.log(response);
            var headerNames = [];
            var data = [];
            var dataTo = [];

            for (var i = 0, header; header = response.columnHeaders[i]; i++) {
                data.push(response.rows[0][1]);
                dataTo.push(response.totalsForAllResults[header.name]);

            }
            var sorted = document.getElementById("data").innerHTML = "Direkte trafikk " + parseInt(data[0]);
            var totalSessions = document.getElementById("dataTo").innerHTML = "Av total trafikk " + parseInt(dataTo[1]);
            var output = document.getElementById("test");
            var result = parseInt(data[0]) / parseInt(dataTo[1]) * 100;
            // console.log("Result " + result);
            output.innerHTML = "<h3> Andel besøk fra 'Direct/(none)' <br>" + result.toFixed(2) + " %</h3>";
        });

        var sessionsPrDay = new gapi.analytics.report.Data({
            query: {
                ids: 'ga:76988010',
                metrics: 'ga:sessions',

            }
        }).set({
            query: dateRange1
        });

        sessionsPrDay.execute();
        sessionsPrDay.on('success', function(response) {

            var sessionsPrDayArray = [];
            var sessionsPrDayArrayTo = [];
            //Checks the total amount of results
            for (var i = 0, header; header = response.columnHeaders[i]; i++) {
                //sessionsPrDayArray.push(response.rows[0][1]);
                sessionsPrDayArray.push(response.totalsForAllResults[header.name]);
                //console.log(response);
                //console.log(sessionsPrDayArray);
            }
            var output = document.getElementById("sessionsPrDayCal");
            var result = parseInt(sessionsPrDayArray[0]) / dayToBe;
            // console.log("Result " + result);
            output.innerHTML = "<h3> Gjennomsnitt antall besøk per dag <br>" + result.toFixed(0) + " </h3>";
        });

        viewSelector.on('viewChange', function(data) {
            dataChart1.set({
                query: {
                    ids: data.ids
                }
            }).execute();
            var title = document.getElementById('view-name');
            title.textContent = data.property.name;

        });

        /**
         * Register a handler to run whenever the user changes the date range from
         * the first datepicker. The handler will update the first dataChart
         * instance as well as change the dashboard subtitle to reflect the range.
         */

        dateRangeSelector1.on('change', function(data) {
            dataChart1.set({
                query: data
            }).execute();
            console.log("!");
            report.set({
                query: data
            }).execute();
            sessionsPrDay.set({
                query: data
            }).execute();
            var dataResponseStart = data['start-date'];
            var dataResponseEnd = data['end-date'];

            var resStart = dataResponseStart.split("-");
            var dagStart = resStart[2];
            var maanedStart = resStart[1] - 1;
            var aarStart = resStart[0];

            var resSlutt = dataResponseEnd.split("-");
            var dagSlutt = resSlutt[2];
            var maanedSlutt = resSlutt[1] - 1;
            var aarSlutt = resSlutt[0];

            var endDate = new Date(aarSlutt, maanedSlutt, dagSlutt);
            var startDate = new Date(aarStart, maanedStart, dagStart);
            var differenceInTime = Math.abs(startDate.getTime() - endDate.getTime());
            var differenceInDays = Math.ceil(differenceInTime / (1000 * 3600 * 24));
            return dayToBe = differenceInDays;

            // Update the "from" dates text.
            var datefield = document.getElementById('from-dates');
            datefield.textContent = data['start-date'] + '&mdash;' + data['end-date'];
        });

    });
</script>

1 个答案:

答案 0 :(得分:0)

遵循this指南:

  1. 导航至analytics.google.com,然后转到管理→属性设置→并记下默认网址设置。

  2. 在新标签中,导航至https://analytics.google.com,然后转到管理→所有产品→Search Console→并单击调整链接并记下所连接站点的URL。

  3. 如果这些网站URL不匹配,如果一个拥有www,另一个没有,或者一个拥有https://而另一个拥有http://,则这将导致前面提到的错误。该API返回了403响应。

  4. 您需要通过执行以下一项操作来纠正不匹配问题: 以下:

    • 更改默认URL的分析设置,以匹配连接的Search Console帐户(如果适用)
    • 如果未连接Search Console配置文件,请按照以下说明进行连接(并确保网址匹配:如何使用Google Analytics(分析)在Google Search Console中验证您的网站。
    • 如果您喜欢分析中的URL,但是连接了错误的Search Console配置文件URL,并且它们不完全匹配,则需要断开不匹配的URL,然后连接正确的URL。