google-analytics-api
입증
수색…
통사론
- GET https://accounts.google.com/o/oauth2/auth?client_id= {clientid} & redirect_uri = urn : ietf : wg : oauth : 2.0 : oob & scope = {범위} 및 response_type = 코드
- POST https://accounts.google.com/o/oauth2/token code = {위 코드에서 코드} & client_id = {ClientId} & client_secret = {ClientSecret} & redirect_uri = urn : ietf : wg : oauth : 2.0 : oob & grant_type = authorization_code
- POST https://accounts.google.com/o/oauth2/token client_id = {ClientId} & client_secret = {ClientSecret} & refresh_token = {위 전화에서} & grant_type = refresh_token
매개 변수
매개 변수 | 기술 |
---|---|
고객 ID | Google 개발자 콘솔에서 프로젝트 또는 애플리케이션을 식별합니다. |
비밀 | Google 개발자 콘솔에서 프로젝트 또는 애플리케이션을 식별합니다. |
redirect_uri | 인증을 반환해야하는 Google 개발자 위치에서. 기본 응용 프로그램의 경우 urn:ietf:wg:oauth:2.0:oob 을 사용하여 localhost를 나타낼 수 있습니다. |
비고
Google API에 액세스하려면 자신을 개발자로 식별하고 프로젝트를 식별해야합니다. 우리는 Google Developers 콘솔 에서 새 프로젝트를 작성하여이 작업을 수행합니다.
프로젝트를 만들 때 Google 애널리틱스 API에 액세스하려면 액세스하려는 API를 사용하도록 설정해야합니다.
- 보고 API : Google 웹 로그 분석보고 API v4에 액세스합니다.
- Analytics API : 다른 모든 기능에 액세스 할 수 있습니다.
이제 데이터 액세스 방법을 결정해야합니다.
Google 데이터에는 두 가지 유형의 데이터 공개 및 비공개 데이터가 있습니다.
- 공용 데이터는 사용자가 소유하지 않습니다. 메타 데이터 API는 해당 데이터에 액세스하기 위해 로그인 할 필요가없는 공용 API입니다.
- 보고 API에는 사용자가 Google 애널리틱스 데이터를 포함하고있어 사용자가 액세스 권한을 부여하지 않은 한 비공개로 표시됩니다.
공개 데이터에만 액세스하는 경우 공용 API 키를 작성하면 문제의 API에 액세스 할 수 있습니다. 개인 사용자 데이터에 액세스하려는 경우 Oauth2 자격 증명 또는 서비스 계정 자격 증명을 만들어야합니다.
권한 Oauth2
비공개 사용자 데이터에 액세스하려면 액세스 할 수있는 데이터 소유자의 허가가 있어야합니다. Oauth2 는 사용자가 해당 액세스 권한을 요청하도록 허용합니다.
이전에 Oauth2 이전에 보셨을 것입니다.
애플리케이션 'Google 웹 로그 분석 Windows'에서 'Google 웹 로그 분석 데이터'사용자를 볼 수있는 액세스 권한을 요청하고 있습니다.
- Google 웹 로그 분석 창은 Google 개발자 콘솔에서 생성 된 프로젝트의 이름입니다.
- Google 애널리틱스 데이터는 Google이 요청한 권한의 범위입니다.
범위 Google Analytics API를 수행 할 사용자에게 사용할 수있는 두 가지 범위가 있음을 알릴 필요가 있습니다.
필요한 범위 만 요청하는 것이 가장 좋습니다. 사용자 데이터 만 읽는다면 읽기 전용 범위 만 요청하면됩니다.
권한 부여 서비스 계정
서비스 계정 은 사전 승인을받은 점에서 다릅니다. 개발자가 서비스 계정 이메일을 가져 와서 Google 애널리틱스 계정의 사용자로 추가 할 수있는 서비스 계정 자격증 명을 만들면 계정 수준 에서 서비스 계정에 데이터 액세스 권한이 부여됩니다. 인증 창이 뜨고 액세스 권한을 요청하지 않아도됩니다. 서비스 계정은 Google 웹 로그 분석 계정의 사용자 인 동안 데이터에 액세스 할 수 있습니다.
결론
Google 애널리틱스 API에서 공개하는 대부분의 데이터에 액세스하려면 인증이 필요합니다.
2015 년 5 월부터 클라이언트 로그인 / 로그인과 비밀번호를 사용하여 Google API에 액세스 할 수 없습니다. 개방 인증을 사용해야합니다.
**
Oauth2 C #
예는 Google API Dotnet 클라이언트 라이브러리를 사용합니다.
PM> 설치 - 패키지 Google.Apis.AnalyticsReporting.v4
/// <summary>
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static AnalyticsReportingService AuthenticateOauth(string clientSecretJson, string userName)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new Exception("userName is required.");
if (string.IsNullOrEmpty(clientSecretJson))
throw new Exception("clientSecretJson is required.");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need.
string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // View your Google Analytics Data
UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = string.Format("{0} Authentication", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name),
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message);
throw new Exception("CreateOauth2DriveFailed", ex);
}
}
서비스 계정 인증 Vb.net
샘플 설치 패키지 Google.Apis.AnalyticsReporting.v4 사용
Public Shared Function getServiceInitializer() As BaseClientService
Dim serviceAccountCredentialFilePath = "Path to Json service account key file" REM from Google Developers console
Dim myKeyEMail = "XXX@developer.gserviceaccount.com" REM from Google Developers console
Dim scope = Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly
Try
Dim credential
Using stream As New FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read)
credential = GoogleCredential.FromStream(stream).CreateScoped(scope)
End Using
Dim Initializer As New BaseClientService.Initializer()
Initializer.HttpClientInitializer = credential
Initializer.ApplicationName = "SRJCGMail"
Dim service As New AnalyticsReportingService(Initializer)
Return service
Catch ex As Exception
Console.WriteLine(ex.Message)
Return Nothing
End Try
End Function