# 구글 애널리틱스

{% hint style="info" %}
샵바이예시 코드들은 스크립트 동작을 보장하지 않습니다.
{% endhint %}

{% hint style="info" %}
본 문서에서는 구글 태그매니저 적용 방법에 대해서 기입하지 않습니다.
{% endhint %}

## 관련 문서 <a href="#undefined" id="undefined"></a>

* **구글 애널리틱스 개발자 문서**: [https://developers.google.com/analytics/devguides/collection/ga4](https://developers.google.com/analytics/devguides/collection/ga4?hl=ko)
* **샵바이 변수 조회 가이드**: <https://admin-remote.shopby.co.kr/popup/variable-guide>
* **구글 애널리틱스 추천 이벤트**: <https://support.google.com/analytics/answer/9267735>

## 구글 애널리틱스 스크립트 예시 <a href="#undefined-1" id="undefined-1"></a>

### 상단 공통 <a href="#undefined-2" id="undefined-2"></a>

{% hint style="info" %}
상단 공통 스크립트는 샵바이 관리자페이지에서 아이디 값을 입력할 경우 자동으로 삽입 됩니다.

따라서, 샵바이 어드민에 아이디를 입력하여 저장한 경우에는 상단 공통 스크립트는 생략 하시면 됩니다.
{% endhint %}

<figure><img src="/files/4DFOh1CQYbO8x8z1KeLD" alt=""><figcaption></figcaption></figure>

```javascript
<!-- 예시 코드 -->
<script
  async
  src="https://www.googletagmanager.com/gtag/js?id={{GA4 ID}}"
></script>
<script>
  globalThis.dataLayer = globalThis.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag("js", new Date());

  gtag("config", "{{GA4 ID}}"); // GA4, Stream ID로 변경해주세요
</script>
```

### 상품 상세 페이지

```javascript
<!-- 예시 코드 -->
<script>
  try {
    if (sb.product) {
      const {
        baseInfo: { productNo, productName },
        price: { salePrice, immediateDiscountAmt },
      } = sb.product;

      const gaViewItem = {
        item_id: String(productNo),
        item_name: productName,
        price: salePrice - immediateDiscountAmt,
        quantity: 1,
      };

      gtag('event', 'view_item', {
        currency: 'KRW',
        value: gaViewItem.price,
        items: [gaViewItem],
      });
    }
  } catch (error) {
    console.error("An error occurred:", error);
  }
</script>
```

### 회원가입 완료 페이지 <a href="#undefined-4" id="undefined-4"></a>

```javascript
<!-- 예시 코드 -->
<script>
  try {
    gtag("event", "sign_up", {
      currency: "KRW",
      value: 1,
    });
  } catch (error) {
    console.error("An error occurred:", error);
  }
</script>
```

### 장바구니 페이지

```javascript
<!-- 예시 코드 -->
<script>
  try {
    if (sb.cart?.deliveryGroups?.length > 0) {
      function getGAViewCartInfo() {
        const gaOrderProducts = sb.cart.deliveryGroups.flatMap(({ orderProducts }) =>
          orderProducts.map((product) => {
            const { productNo, productName, buyAmt, orderProductOptions } = product;
            const quantity = orderProductOptions.reduce((sum, { orderCnt }) => {
              sum += orderCnt;

              return sum;
            }, 0);

            return {
              item_id: productNo,
              item_name: productName,
              currency: 'KRW',
              price: buyAmt,
              quantity,
            };
          }),
        );

        const gaOrderPrice = gaOrderProducts.reduce((sum, cur) => {
          sum += cur.price;

          return sum;
        }, 0);

        return { gaOrderProducts, gaOrderPrice };
      }


      const { gaOrderPrice, gaOrderProducts } = getGAViewCartInfo();
      if(gaOrderProducts.length > 0){
      gtag('event', 'view_cart', {
        currency: 'KRW',
        value: gaOrderPrice,
        items: gaOrderProducts,
      });
      }
    }
  } catch (error) {
    console.error("An error occurred:", error);
  }
</script>
```

### 주문 완료 페이지

```javascript
<!-- 예시 코드 -->
<script>
  try {
    if (sb.order) {
      const {
        orderNo,
        payInfo: { payAmt },
        orderOptionsGroupByPartner,
      } = sb.order;

      const gaOrderItems = orderOptionsGroupByPartner.flatMap(({ orderOptionsGroupByDelivery }) =>
        orderOptionsGroupByDelivery.flatMap(({ orderOptions }) =>
          orderOptions.map((options) => {
            const {
              productNo: item_id,
              productName: item_name,
              price: { immediateDiscountAmt: discount, buyPrice: price },
              orderCnt: quantity,
            } = options;

            return {
              item_id:String(item_id),
              item_name,
              currency: 'KRW',
              discount,
              price,
              quantity,
            };
          }),
        ),
      );

      gtag('event', 'purchase', {
        transaction_id: orderNo,
        value: payAmt,
        currency: 'KRW',
        items: gaOrderItems,
      });
    }
  } catch (error) {
    console.error("An error occurred:", error);
  }
</script>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://marketing-help.nhn-commerce.com/conversion-tracking-setup/shopby-ads-script/google-analytics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
