Reputation: 21
import React, { useEffect } from "react";
import { gapi } from "gapi-script";
import Login from "./components/login";
export default function App() {
useEffect(() => {
function start() {
gapi.client.init({
clientId: process.env.REACT_APP_CLIENT_ID,
discoveryDocs: [
"https://analyticsreporting.googleapis.com/$discovery/rest",
],
scope:
"https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/analytics",
});
}
gapi.load("client:auth2", start);
}, []);
const callApi = () => {
gapi.client.load("analyticsreporting", "v4", () => {
// Prepare the request
const accessToken = gapi.client.getToken().access_token;
const batchRequest = {
reportRequests: [
{
viewId: process.env.REACT_APP_VIEW_ID,
dateRanges: [
{
startDate: "7daysAgo",
endDate: "today",
},
],
metrics: [
{
expression: "ga:sessions",
},
],
dimensions: [
{
name: "ga:date",
},
],
},
],
};
// Make the request
gapi.client.analyticsreporting.reports
.batchGet({
resource: batchRequest,
headers: {
Authorization: `Bearer ${accessToken}`, // Add the access token to the header
},
})
.then((response: any) => {
const reports = response.result.reports;
console.log(reports);
})
.catch((error: any) => {
console.error("Error fetching analytics data:", error.result.error);
});
});
};
return (
<div>
<Login />
<button
onClick={() => {
console.log(gapi.auth.getToken().access_token);
}}
>
Log token
</button>
<button onClick={callApi}>Call Api</button>
</div>
);
}
I cant figure out why this does not work, i appreciate any help, i try to fetch some data from the Google Analytics Reporting Api, I'm new to google Apis but i need to make this app and figure it out.
The access token is valid and works, but i get the error "Request had insufficient authentification scopes".
Upvotes: 0
Views: 160