今日、私はGoogleアナリティクスからデータを取得するためにAPI API v4をリクエストしています。私はGoogleのスプレッドシートにデータを表示するために、Googleのアプリケーションのスクリプトを記述します。google analyticsのapiv4のご報告のリクエスト
function getService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('searchconsole')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
// this is Search Console read only scope for write access is:
// https://www.googleapis.com/auth/webmasters
.setScope('https://www.googleapis.com/auth/webmasters')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var searchConsoleService = getService();
var isAuthorized = searchConsoleService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
は最終的に私は私の貴様IDと私の見解でvariables.gsファイルを持っている:私はOAuth2.0.gsファイルを持っているもちろん
function get_ga(){
var now = new Date();
var doc = SpreadsheetApp.getActiveSpreadsheet();
var site = doc.getSheetByName("Dashboard").getRange(2,1).getValue();
var sheet = doc.getSheetByName("Google analytics");
var service = getService();
if (sheet==null){
sheet = doc.insertSheet("Google analytics");
}
start_date=getstart(now);
end_date=getend(now);
if (service.hasAccess()) {
var apiURL = 'https://analyticsreporting.googleapis.com/v4/reports:batchGet';
var headers = {"Authorization": "Bearer " + getService().getAccessToken()};
var request = {
"reportRequests":
[
{
"viewId": VIEW_ID,
"dateRanges": [{"startDate": start_date, "endDate": end_date}],
"metrics": [{"expression": "ga:users"}]
}
]
}
var options = {
"headers" : headers,
"contentType":'application/json',
"method" : "post",
"payload" : JSON.stringify(request),
"muteHttpExceptions": true
};
try {
var response = UrlFetchApp.fetch(apiURL, options);
}
catch (e) {
Logger.log(e);
}
Logger.log(response)
var result = JSON.parse(response.getContentText());
console.log(result);
if (result.error){
return null;
}
}
else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
return 0;
}
}
:ここ
は私の機能ですGoogleアナリティクスのIDです。データが必要なウェブサイトに対応しています。重要なことは、Googleアナリティクスのデータが表示されますが、私はウェブサイトの所有者ではありません。//GSC
var CLIENT_ID = '*******************************************';
var CLIENT_SECRET = '*****************';
//GA
var CLIENT_ID2 = '************************************';
var CLIENT_SECRET2 = '**************';
var VIEW_ID = '********';
Google検索コンソールとgoogle analytics APIを有効にします。 私のすべての機能はGoogle検索コンソールと完全に連携しています。
エラーがある:{「エラー」:{「ステータス」:「PERMISSION_DENIED」、「コード」:403、「メッセージ」:「要求が不十分認証スコープを持っていた」}} 奇妙私が気づいた最初であります私はGoogle Analytics(GoogleのOAuth2.0.gsファイルを参照)の認証のためにGoogle検索コンソールからクライアントIDとクライアントシークレットを使用していますが、動作するようです。それ以外の場合は401エラーが発生します。
初心者の方と同じように、Google APIコンソールでAPIを有効にしました。あなたの機能は完璧に動作します、ありがとう、あなたは実際に私の人生を救った。 – JeanSec
@JeanSecこれをチェックするには、チェックマーク – noogui