client_id на страницах AMP - PullRequest
       64

client_id на страницах AMP

0 голосов
/ 17 октября 2018

Я использовал simoahava и метод DanWilkerson для отслеживания AMP-страниц.Я знаю, что есть проблема с client_id на усилителе и на усилителе, как описано здесь: https://www.napkyn.com/2017/11/23/how-to-use-the-amp-client-id-api-for-consistent-user-tracking-in-google-analytics/

Я следовал инструкциям, но все еще не вижу, что я делаю неправильно.У меня 2 проблемы:

  1. Когда я перехожу из основного домена в домен, размещенный на усилителе, файл cookie из основного домена автоматически вставляется в домен, размещенный на усилителе, я не настраиваюсь для этого, поэтому я неt знать, ПОЧЕМУ cookie из основного домена доступен в домене, размещенном в amp.Размещенный домен amp находится не в Google, а на другом сервере (облачная платформа Google).Так ПОЧЕМУ файл cookie с главной страницы отображается на моем другом сайте проекта amp?
  2. client_id не обнаружен, а amp-xxxx client_id устанавливается вместе с GA.xxx из основного домена.

Основной домен: https://www.proteinfabrikken.no/

Страница AMP: https://amp -proteinfabrikken-dot-hydra-connect.appspot.com/amp/proteinfabrikken/product/bcaa-211-400g

Вот так выглядит мой HTML-код:

<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>

и конечная точка:

<amp-analytics config="https://amp-proteinfabrikken-dot-hydra-connect.appspot.com/amp/proteinfabrikken/gtm-analytics.config.json" type="googleanalytics" data-credentials="include"></amp-analytics>

Теперь на моем сервере, который указывает на /gtm-analytics.config.json в маршрутах:

// AMP TESTING
$app->get($prefix . '/gtm-analytics.config.json', function (Request $request, Response $response) {


    // Generate random Client ID
    function generate_ga_client_id() {
        return rand(100000000, 999999999) . '.' . time();
    }

    // Set cookie to expire in 2 years
    function getCookieExpirationDate() {
        return date('D, j F Y H:i:s', time() + 60 * 60 * 24 * 365 * 2);
    }

    // Callback for the GET request
    function retrieve_gtm_json($data) {
        /* Get the hostname of the request origin, and parse it for the
         * pure domain name. */




        $domainName = str_replace('www.', '', 'https://www.amp-proteinfabrikken-dot-hydra-connect.appspot.com/amp/proteinfabrikken/product/bcaa-211-400g');
        syslog(LOG_INFO, "DOMAIN_NAME:" . $domainName);

        // Get the number of parts in the domain name
        $domainLength = count(explode('.', $domainName));
        syslog(LOG_INFO, "DOMAIN_LENGTH:" . $domainLength);
        /* Check if the browser already has the _ga cookie.
            * If not, generate a new cookie. */

        syslog(LOG_INFO, "HVA ER INNE I _GA:". $_COOKIE['_ga']);
        if (isset($_COOKIE['_ga'])) {
            $cid = $_COOKIE['_ga'];
            syslog(LOG_INFO, "ISSET COOKIE: TRUE:");
            syslog(LOG_INFO, "ISSET COOKIE: TRUE. Cookie:".$_COOKIE['_ga']);
        } else {

            $cid = "GA1.{$domainLength}." . generate_ga_client_id();
            syslog(LOG_INFO, "ISSET COOKIE: FALSE:");
            syslog(LOG_INFO, "ISSET COOKIE: FALSE. Cookie:".$cid);
        }


        syslog(LOG_INFO, "COOKIE:" . $cid);
        /* Store the actual Client ID (last two numbers) of the
         * _ga cookie value in the $cidNumber variable */
        $cidNumber = preg_replace('/^GA.\.[^.]+\./', '', $cid);
        syslog(LOG_INFO, "Client_ID_number:" . $cidNumber);


        /* Fetch the actual GTM container, by passing the valid query parameters from
         * the original request. */
        $container = file_get_contents("https://www.googletagmanager.com/amp.json?id=GTM-MFWM3QP&gtm.url=https://amp-proteinfabrikken-dot-hydra-connect.appspot.com/amp/proteinfabrikken/product/bcaa-211-400g");


        // Replace the CLIENT_ID(AMP_ECID_GOOGLE) string with ${clientId}
        $container = str_replace('CLIENT_ID(AMP_ECID_GOOGLE)', '${clientId}', $container);

        // Add the clientId to the "vars" object in the container JSON.
        $container = json_decode($container);
        $container->vars->clientId = $cidNumber;


        //JSON Encode pga feil på lumen To_String()
        $contained = json_encode($container);
        syslog(LOG_INFO, "GTM_CONTAINER:" . $contained);


        $response = response($contained, 200)
            ->header('Content-Type', 'text/plain')
            // Add the required headers (Set-Cookie, most importantly) to the Request
            ->header('Set-Cookie', "_ga={$cid}; Path=/; Expires=" . getcookieExpirationDate() . " GMT; Domain=https://www.proteinfabrikken.no;")
            ->header('Access-Control-Allow-Origin', 'https://cdn.ampproject.org')
            ->header('Access-Control-Allow-Credentials', 'true')
            // Remember to check the protocol and change to http if that's where your domain is
            ->header('AMP-Access-Control-Allow-Source-Origin', "https://www.proteinfabrikken.no")
            ->header('Access-Control-Expose-Headers', 'AMP-Access-Control-Allow-Source-Origin');
        // Return the HTTP response.


        return $response;


    }


    return retrieve_gtm_json('https://amp-proteinfabrikken-dot-hydra-connect.appspot.com/amp/proteinfabrikken/product/bcaa-211-400g');


});

Я использую Люмен.Кто-нибудь может помочь с этой проблемой, может быть, встречались с этой проблемой раньше?Спасибо!

...