# TD JavaScript Consent Extension の使用

Treasure Data JavaScript Consent Extension (TD JS Consent Extension) は、クライアント側で consent 管理ソリューションを実装する API セットです。TD のお客様は、データ使用のカテゴリーと consent 収集のための異なる context を定義できます。

Consent Extension は、Web サイト訪問者が自分についてのデータの収集方法に関する consent 設定を制御およびカスタマイズできるようにします。訪問者は、完全にオプトアウトするか、データ使用の目的に同意しない場合は特定の context でのデータ収集を選択的にオプトアウトすることができます。UI で完全にカスタマイズ可能な consent 管理を構築できるアドオンもあります。

# 前提条件

* [TD JS SDK](https://github.com/treasure-data/td-js-sdk) に精通していること
* Treasure Data Platform にアクセスするための Write [API KEY](/products/my-settings/getting-your-api-keys)


Treasure Data では、本番環境で使用を開始する前に、Treasure Data JavaScript SDK version 3 を使用してサイトの新機能や機能の実装を検証することをお勧めします。cookie の管理方法が異なります。これらの記事のほとんどを参照する際は、ソリューションで推奨される event collector と Treasure Data JavaScript SDK version 3 の呼び出しを定義する必要があることに注意してください。例えば、//cdn.treasuredata.com/sdk/2.5/td.min.js を //cdn.treasuredata.com/sdk/3.0.0/td.min.js に変更します。

## Context と Consent について

Treasure Data JavaScript Consent Extension には、Web サイトの consent 情報を定義できる以下の概念があります:

* **Context**
* **Consent**


例えば、consent の `context_id` と `purpose` のパラメータを含めて、consent を一意にすることができます。この組み合わせにより、Treasure Data で消費者の consent をクエリしてフィルタリングできます。

### Context

Context は、ブランド、ドメイン、consent 収集のタイプなどの一般的な情報を定義します。これらの情報は、ユーザーが consent に同意または拒否した context を識別します。Treasure Data は、context に対して以下のデフォルトフィールドを提供します。context を充実させるために、いつでも追加のフィールドを追加できます。

| **Parameter** | **Description** |
|  --- | --- |
| `brand` | 会社のブランド名。 |
| `domain_name` | ブランドコンテンツと TD-JS SDK をホストしている Web サイトのドメイン名。 |
| `collection_type` | 異なるタイプの収集 context を含みます。例えば、consent 収集 context は、ショッピングカートページ、Web フォーム、または Web サイト全体に対して設定できます。 |
| `collection_point_id` | 別のシステムから渡すことができる各収集ポイントの識別子。例えば、収集 context がショッピングカートページの場合、この `collection_point_id` にショッピングカートトランザクション ID を使用できます。 |


`context_id`| 各 context に対して自動生成される ID。

例えば、context のコードスニペットは次のようになります:


```javascript
{
  brand: 'A brand',
  domain_name: 'abrand.com',
  collection_type: 'shopping_cart',
  collection_point_id: 'shopping_trnx_id',
  context_id: 'xxxxxxxxxx'
}
```

### Consent

Consent は、消費者によって与えられた consent のセマンティクスを定義します。Consent フィールドは次のように定義されます。

| **Parameter** | **Description** |
|  --- | --- |
| `purpose` | データ使用のカテゴリー。 |
| `status` | Consent のステータス。`given`、`refused`、または `notgiven` のいずれか。 |
| `datatype` | 個人データタイプ。 |
| `context_id` | consent が属する Context。 |
| `identifier` | ユーザー識別子。 |
| `expiry_date` | consent の有効期限。 |


例えば、consent のコードスニペットは次のようになります:


```javascript
{
  purpose: 'analytics',
  status: 'given',
  datatype: 'Purchase',
  context_id: 'xxxxxxxxxx',
  identifier: 'client id',
  expiry_date: 'YYYY-MM-DD'
}
```

## TD Consent Manager の設定

Consent Manager は、TD JS Consent Extension のメイン JS オブジェクトです。Consent Manager の設定は、TD JavaScript SDK の初期化と共にセットアップされます。database 名、API write key、およびお客様のリージョンに適した host を入力します。

TD Consent Manager を次のように設定します:

1. JS SDK を使用している新しい [js file](https://github.com/treasure-data/td-js-sdk) を開くか作成します。例えば、td_initializations.js です。
ファイルは次のようになります:



```javascript
var td = new Treasure({
   database: 'database',
   writeKey: '1/xxxxxxxxxx',
   host: 'in.treasuredata.com',
   ...
```

1. 前述のパラメータに従って TD JS Consent Manager の設定を開始します。
例は次のようになります:



```javascript
var td = new Treasure({
  database: 'database',
  writeKey: '1/xxxxxxxxxx',
  host: 'in.treasuredata.com',
  consentManager: {
    storageKey: 'storage key',
    successConsentCallback: function () {},
    failureConsentCallback: function () {},
    expiredConsentsCallback: function () {},
    consentTable: 'consent_table_name',
    contextTable: 'context_table_name',
    issuer: 'name of the consent management platform',
    dateFormat: 'YYYY-MM-DD'
  }
})
```

## TD Consent Manager Parameters

以下のパラメータを使用して TD Consent Manager を設定できます。

| **Parameter** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `storageKey` | String | Optional | local storage の名前。デフォルト: `td_consent_preferences` |
| `consentTable` | String | Optional | consent テーブルの名前。デフォルト: `td_cm_consent` |
| `contextTable` | String | Optional | context テーブルの名前。デフォルト: `td_cm_context` |
| `issuer` | String | Optional | consent 管理プラットフォームの名前。デフォルト: `treasuredata` |
| `dateFormat` | String | Optional | 日付フォーマット文字列。デフォルト: `YYYY-MM-DD`。Treasure Data は日付フォーマットを処理するために [dayjs](https://github.com/iamkun/dayjs) を使用しているため、日付フォーマット文字列はこのドキュメント [string-format](https://day.js.org/docs/en/parse/string-format) に従う必要があります。 |
| `successConsentCallback` | Function | Optional | consent の保存が成功した場合の callback |
| `failureConsentCallback` | Function | Optional | consent の保存が失敗した場合の callback |
| `expiredConsentsCallback` | Function | Optional | consent が期限切れの場合の callback |


ページが読み込まれるたびに、TD JS Consent Manager は consent の有効期限をチェックし、期限切れの consent がある場合は `expiredConsentCallback` がトリガーされます。また、期限切れの consent のステータスを `expired` に更新します。

## デフォルト Context の作成

consent に context を追加すると、TD platform にデータを送信する際に context が含まれます。独自の context ID を指定できます。指定しない場合は、新しい context ID が戻り値として生成されます。

| **Parameter** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `context` | Object | Yes | Context 情報 |
| `brand` | String | Yes | ブランド名 |
| `domain_name` | String | Yes | ドメイン名 |
| `collection_type` | String | Yes | Consent 収集タイプ |
| `collection_point_id` | String | Yes | Consent 収集ポイント ID |
| `context_id` | String | Optional | Context ID |


例えば、コードスニペットは次のようになります:


```javascript
sdk.addContext({
  brand: 'A Brand',
  domain_name: 'abrand.com',
  collection_type: 'shopping_cart',
  collection_point_id: 'shopping_trnx_id'
  context_id: 'uuid'
})
```

## デフォルト Consent Preferences の作成

context ID を持たない consent は、デフォルトの context に追加されます。

| **Parameter** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `purpose` | String | Yes | データ使用の目的を記述します。consent を作成する際、consent オブジェクトの名前として `purpose` を使用します。 |
| `description` | String | Optional | Consent の説明 |
| `datatype` | String | Yes | データタイプ |
| `status` | String | Yes | Consent のステータス。次のいずれかになります: `given`、`refused`、`notgiven`。デフォルト: `notgiven` |
| `expiry_date` | (String | Number | Date) |
| `context_id` | String | Yes | Context ID |


例えば、コードスニペットは次のようになります:


```javascript
sdk.addConsents({
  'marketing': { // <--- purpose
description: 'description of consent',
datatype: 'Attibutes',
status: Given | Refused,
expiry_date: 'YYYY-MM-DD',
context_id: 'context_id'
  },
  'storing': { // <--- purpose
description: 'description',
datatype: 'datatype',
status: Given | Refused,
expiry_date: 'YYYY-MM-DD',
context_id: 'context_id'
  },
  'recommendations': { // <--- purpose
description: 'description',
datatype: 'datatype',
status: Given | Refused,
expiry_date: 'YYYY-MM-DD',
context_id: 'context_id'
  }
)
```

## Callback Functions の設定

SDK は、consent が期限切れになった場合、consent が更新された場合、consent が Treasure Data に正常に送信された場合、または consent が失敗した場合など、さまざまな callback 関数を提供します。

これらの callback がトリガーされたときの動作を決定するために、追加のコードを追加できます。

例えば、コードスニペットは次のようになります:


```javascript
function successCallback (preferences) {
  if (preferences['analytics'].status === 'given') {
td.setSignedMode()
td.unblockEvents()
  } else if (preferences['analytics'].status === 'refused') {
td.setAnonymousMode()
td.blockEvents()
  }
```

## Web サイト訪問者から Consent を求める

Web サイトに表示される cookie banner を作成してデプロイし、Web サイト訪問者から consent を求めることができます。cookie banner には通常、訪問者にデータが収集されていること、および consent に従って特定の目的に使用されることを知らせる短い声明が含まれています。さらに、サイト訪問者が consent 設定を直接制御できる Consent Manager UI へのリンクを追加できます。

cookie banner と Consent Manager UI の例については、[Treasure Data GitHub repo](https://github.com/treasure-data/td-js-consent) を参照してください。

## TD Consent Manager への Consent Preferences の更新

デフォルトの consent preferences を作成するのと同様に、ユーザーが特定のデータ使用の consent を承認または拒否した場合に、consent ステータスを更新できます。そのためには、デフォルトとして設定したときと同じ名前を consent に使用し、以下のパラメータで `updateConsent (contextId, consentObject)` を呼び出します:

**Consent preferences を更新するための Parameters**

| **Parameters** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `contextId` | String | Yes | Context ID |
| `consentObject` | Object | Yes | 更新したい context の値 |


例えば、コードスニペットは次のようになります:


```javascript
sdk.updateConsent('xxxxxx-context-id', {
  'recommendations': {
status: 'refused'
  }
})
```

consent を更新すると、`saveConsents` を呼び出した後、更新された consent のみが `successConsentCallback` に送信されます。

## TD Consent Manager への Context の更新

既存の context を更新して、context を説明するための詳細情報を追加することもできます。

**Context を更新するための Parameters**:

| **Parameters** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `contextId` | String | Yes | Context ID |
| `values` | Object | Yes | 更新したい context の値 |



```javascript
sdk.updateContext('xxxxxx-context-id', {
  brand: 'Other brand',
  domain_name: 'otherdomain.com'
})
```

## Consent と Context の Treasure Data への保存

以下の呼び出しを使用して、consent と context を local storage と Treasure Data に保存できます:


```javascript
saveConsents(success, error);
saveContexts(success, error);
```

**Consent を保存するための Parameters**:

| **Parameters** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `success` | Function | Optional | consent の保存が成功した場合の Callback |
| `error` | Function | Optional | consent の保存が成功した場合の Callback |


例えば、コードスニペットは次のようになります:


```javascript
function success () {
  // yay()
}

function error (err) {
  /**
  * err: { success: false, message: 'Timeout' }
  */
}
sdk.saveContexts(success, error)
```

**Contexts を保存するための Parameters:**

| **Parameters** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `success` | Function | Optional | context の保存が成功した場合の Callback |
| `error` | Function | Optional | context の保存が成功した場合の Callback |


例えば、コードスニペットは次のようになります:


```javascript
function success () {
  // yay()
}

function error (err) {
  /**
  * err: { success: false, message: 'Timeout' }
  */
}
sdk.saveContexts(success, error)
```

## その他の Functions

これらは、TD Consent Manager からローカルに consent 情報を取得するために呼び出すことができるその他のユーティリティ関数です。

| **Function** | **Description** |
|  --- | --- |


#### `getConsents()`

| consent のリストを返します

#### `getContexts()`

| context のリストを返します

#### `getConsentExpiryDate(contextId, consentPurpose)`

特定の consent の有効期限を取得します
`getExpiredConsents()`

期限切れの consent を返します

getConsentExpiryDate の Parameters:

| **Parameters** | **Type** | **Required** | **Description** |
|  --- | --- | --- | --- |
| `contextId` | String | Yes | Context ID |
| `consentPurpose` | String | Yes | consent の purpose |


例えば、`getConsentExpiryDate` のコードスニペットは次のようになります:


```javascript
sdk.getConsentExpiryDate('context_id', 'analytics')
```