서버 측 API를 통해 Google 웹 로그 분석에 이벤트를 게시 할 수있는 방법이 있습니까? [닫은]


178

백엔드 시스템에서 이벤트를 게시하여 Google 웹 로그 분석을 사용하려고합니다. 서버 측에서 GA의 API로이를 수행 할 수있는 방법이 있습니까?


네, 같은 JS 측정 프로토콜 클라이언트를 사용하여 이 한
— 로이드

답변:


231

이제 서버 측에서 웹 로그 분석 데이터를 추적 할 수 있습니다. 범용 웹 로그 분석을 시작하면 이제 측정 프로토콜 을 사용 하여 GA 서버에 데이터를 게시 할 수 있습니다.

여기 코드 샘플


5
이 답변을 수락해야합니다. 우리는 아마도 웹 사이트 방문자 데이터로 상당히 정확한 수익 수치를 원할 때 OP와 비슷한 상황에 처해있을 것입니다. 그리고 브라우저 측 추적은 지불 완료의 마지막 단계에 충분하지 않습니다 (예 : 고객이 지불 제공 업체 사이트에서 돌아 오지 않음).
— Tadas Sasnauskas 12

고객이 결제 제공 업체 사이트에서 돌아 오지 않는 것과 동일한 문제가 있지만 고객 ID가 없습니다. 클라이언트 세션에 데이터를 첨부하는 방법은 무엇입니까?
— Korjavin Ivan

2
: @KorjavinIvan 여기 측정 프로토콜에 필요한 클라이언트 ID 또는 CID paramater 얻을 수있는 지침이다 developers.google.com/analytics/devguides/collection/...
— 호르헤 Pedret

1
이 ga.js 코드와 같은 심판을 찾아 광고 차단제의 효과를 해결하려면 좋은 방법처럼 보인다
— JoshuaDavid

동일한 측정 프로토콜, Google 웹 로그 분석 및 Google 태그 관리자 ??
— Kiquenet

21
using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Text;

    public class GoogleAnalyticsApi
    {
        public static void TrackEvent(string type, string category,
               string action, string label, string value)
        {

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = 
                "v=1&tid=UX-XXXXXXX-1&cid=1234&t=" + type +
                "&ec=" + category + 
                "&ea=" + action + 
                "&el=" + label + 
                "&ev=" + value;
            byte[] data = encoding.GetBytes(postData);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://www.google-analytics.com/collect");

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

        }
    }

이것은 범용 분석을 올바르게 사용합니까?
— Brady Moritz

@BradyMoritz 네 그렇습니다
— Koby Douek

또한 get 요청을 사용할 수있을 때 post를 사용해야하는 이유는 무엇입니까?
— 브래디 모리츠

이 C #입니까? 아마 지정해야합니까?
— Esqarrouth

7

PHP를 사용하는 경우 웹 로그 분석 측정 프로토콜 을 쉽게 호출하여 Google 웹 로그 분석 계정으로 페이지 뷰를 보낼 수 있습니다.

function sendAnalytics($sGaId, $sHostname, $sPath, $sTitle) {

    $aParams = array();

    //Protocol Version
    $aParams['v'] = '1';

    //Tracking ID / Web Property ID
    $aParams['tid'] = $sGaId;

    //Anonymize IP
    $aParams['aip'] = '1';

    //Data Source
    $aParams['ds'] = 'web';

    //Queue Time
    $aParams['qt'] = 0;

    //Client ID
    $aParams['cid'] = substr(md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']), 0, 8);

    //User ID
    //$aParams['uid'] = '';

    //Session Control
    //$aParams[''] = '';

    //IP Override
    $aParams['uip'] = $_SERVER['REMOTE_ADDR'];

    //User Agent Override
    $aParams['ua'] = urlencode($_SERVER['HTTP_USER_AGENT']);

    //Geographical Override
    //$aParams['geoid'] = '';

    //Document Referrer
    //$aParams['dr'] = '';

    //Campaign Name
    //$aParams['cn'] = '';

    //Campaign Source
    //$aParams['cs'] = '';

    //Campaign Medium
    //$aParams['cm'] = '';

    //Campaign Keyword
    //$aParams['ck'] = '';

    //Campaign Content
    //$aParams['cc'] = '';

    //Campaign ID
    //$aParams['ci'] = '';

    //Google AdWords ID
    //$aParams['gclid'] = '';

    //Google Display Ads ID
    //$aParams[''] = '';


    ////SystemInfo => see docs

    //Hit type
    $aParams['t'] = 'pageview';

    //Non-Interaction Hit
    //$aParams['ni'] = '';

    //Hostname
    $aParams['dh'] = $sHostname;

    //Document Path
    $aParams['dp'] = $sPath;

    //Document title
    $aParams['dt'] = urlencode($sTitle);


    $sGaUrl = 'http://www.google-analytics.com/collect?';


    foreach($aParams AS $sKey => $sValue) {
        $sGaUrl.= "$sKey=$sValue&";
    }

    $sGaUrl = substr($sGaUrl, 0, -1);

    file_get_contents($sGaUrl);
}


sendAnalytics('UA-XXXXXXXX-1', 'http://foo.com', '/bar', 'Foo Bar');

희망이 도움이됩니다!


1
http_build_query ()는 이것을 좀 더 깨끗하게 만들 수 있습니다 (그리고 적절한 탈출을 지원합니다)
— kainjow

2

사용 통계 모듈을 살펴보십시오 .

커맨드 라인

쉘 스크립트에서 통계 추적 :

# Track an event: category 'Backup', action 'start'
usage-stats event --tid UA-98765432-1 --ec Backup --ea start

# Perform the backup
cp files/** backup/

# Track an event: category 'Backup', action 'complete'
usage-stats event --tid UA-98765432-1 --ec Backup --ea complete

API

가장 사소한 예입니다.

const UsageStats = require('usage-stats')
const usageStats = new UsageStats('UA-98765432-1', { an: 'example' })

usageStats.screenView('screen name')
usageStats.event('category', 'action')
usageStats.send()
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.