> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kleep.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 모바일 SDK - Android

**Repository:** [https://github.com/KlipFit/kleep-android](https://github.com/KlipFit/kleep-android)

## 설치

***

이 과정은 프로젝트에 SDK를 처음 설치할 때 한 번만 수행하면 됩니다. 이후 업데이트 방법은 **업데이트** 섹션을 참고하세요.

1. *gradle.properties*에 다음 토큰을 추가합니다:

   `authToken=jp_9ibcequhrjtge3cmavt2k4sq6a`

2. *settings.gradle* 또는 *settings.gradle.kts*에 다음 줄을 추가합니다:

```groovy theme={null}
// for *settings.gradle*

dependencyResolutionManagement {
*// ...*
    repositories {
        *// ...*
~~~~        maven {
            url "https://jitpack.io"
            credentials { username authToken }
        }
    }
}
```

```kotlin theme={null}
// for *settings.gradle.kts*

*dependencyResolutionManagement {
// ...
    repositories {
	      // ... 
        maven {
            url = uri("https://jitpack.io")
            credentials(PasswordCredentials::class) {
                val authToken: String by settings
                username = authToken*
            }
        *}
    }
}*
```

1. 모듈의 *build.gradle* 또는 *build.gradle.kts* 파일에 다음 줄을 추가하여 의존성을 생성합니다:

```groovy theme={null}
// *build.gradle*
dependencies {
	implementation 'com.github.KlipFit:kleep-android:version'
}
```

```kotlin theme={null}
// *build.gradle.kts*
dependencies {
	implementation("com.github.KlipFit:kleep-android:version")
}
```

## **초기화**

***

커스텀 `Application` 클래스를 수정하여 초기화를 위한 `applicationContext`를 제공합니다.

```kotlin theme={null}
import com.kleep.sdk.KleepResult
import com.kleep.sdk.Kleep

class CustomApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        Kleep.init(applicationContext)
    }
}
```

\*\*`Manifest.xml`\*\*에 Application 클래스를 추가하는 것을 잊지 마세요

```kotlin theme={null}
<application
        android:name=".CustomApplication"
        ...
        >
...
</application>
```

## 가져오기

***

**`MainActivity.kt`** 시작 부분에서 모듈을 수동으로 가져올 수 있습니다

```kotlin theme={null}
import com.kleep.sdk.KleepResult
import com.kleep.sdk.Kleep
```

## 사용법

***

SDK에는 3가지 메서드가 있습니다:

| 메서드             | 로딩 시간       |
| --------------- | ----------- |
| `show`          | 첫 실행: 250ms |
| 이후 실행: 50-250ms |             |
| `requestSize`   | 250ms       |
| `track`         | 250ms       |

### 메서드 1: `requestSize`

이 메서드는 CTA의 로직을 구현하는 데 사용됩니다.

**로직 스키마**

이 스키마는 Kleep을 여는 CTA를 업데이트하는 방법을 설명합니다.

[https://www.figma.com/board/BlurZ01lR3JBQZeTUU98TE/Mobile---CTA-Logic?node-id=0-1\&t=ccXWciNziIdfhgew-1](https://www.figma.com/board/BlurZ01lR3JBQZeTUU98TE/Mobile---CTA-Logic?node-id=0-1\&t=ccXWciNziIdfhgew-1)

**구현 예시**

```kotlin theme={null}
Kleep.builder(this, onResult = {
	when (it) {
	    is KleepResult.NotSupported -> {
	        // Handle the NotSupported case
	    }
	
	    is KleepResult.NoRecommendationYet -> {
	        // Handle the NoRecommendationYet case
	    }
	
	    is KleepResult.RecommendationFound -> {
	        val resultText = it.size
	        val variantId = it.variantId
	        Toast.makeText(this, resultText, Toast.LENGTH_SHORT).show()         
      }

      else -> {

      }
    }
})
	.setPackageName(packageName)         // optional
	.setLang(DEFAULT_LANGUAGE)           // required: "fr", "en", "es", "it", "pt", "nl"
	.setProductId("1234")                // required
	.setRetailer("retailer_name")        // required
	.setTrackingId("uuid")               // empty if non-existent 
	.setCustomerId("unique_customer_id") // optional
	.requestSize()
```

```kotlin theme={null}
package com.kleep.sdk

/**
 * Interface with the Kleep SDK in order to compute the recommended size of a product given some user information
 */
interface KleepDialogBuilder {
    /**
     * Set the package name, not required
     * @return interface of the SDK builder
     */
    fun setPackageName(packageName: String): KleepDialogBuilder
    
    /**
     * Set the language to use: required (default to FR)
     * Values supported: "fr", "en", "es", "it", "pt", "nl"
     * @return interface of the SDK builder
     */
    fun setLang(lang: String): KleepDialogBuilder

    /**
     * Set product ID, required to compute the recommended size.
     * @return interface of the SDK builder
     */
    fun setProductId(productId: String): KleepDialogBuilder

    /**
     * Set tracking id, required. Should represent unique tracking id.
     * Should be an empty string if the tracking id does not exist.
     *
     * @return interface of the SDK builder
     */
    fun setTrackingId(tracking_id: String): KleepDialogBuilder

    /**
     * Set customer id, optonal. Should represent customer id linked to backend.
     * Should be an empty string if the tracking id does not exist.
     *
     * @return interface of the SDK builder
     */
    fun setCustomerId(customer_id: String): KleepDialogBuilder
    
    /**
     * Set retail name (mandatory), required for stock/similar_products requests.
     *
     * @return interface of the SDK builder
     */
    fun setRetailer(retailerName: String): KleepDialogBuilder
    
    /**
     * Sets the stock availability for items.
     * Providing an empty map or omitting this function disables stock checking.
     *
     * @return interface of the SDK builder
     */
    fun setStocks(stocks: Map<String, Boolean>): KleepDialogBuilder

    /**
     * Display the Kleep UI inside a BottomSheet, so the user can fill a survey or take 2 pictures
     * in order to compute and display the recommended size to the user
     */
    fun show()

    /**
     * Get the latest recommended size for the last viewed user.
     * As it's an async process and take several seconds,
		 * the result will be give by the onResult listener , provided to the SDK builder
     */
    fun requestSize()
}
```

### 메서드 2: `show`

이 메서드는 CTA가 클릭될 때 호출됩니다. 다양한 화면을 로드하는 데 사용됩니다. **SDK를 통합하는 개발자는 이를 바텀 시트에 임베드해야 합니다.**

| 파라미터                                                      | 우선순위    | 설명                       |
| --------------------------------------------------------- | ------- | ------------------------ |
| **productID**                                             | *필수*    | 상품 ID                    |
| **retailer**                                              | *필수*    | 리테일러 이름                  |
| **customerID**                                            | *선택 사항* | CRM 식별자, 분석에 사용          |
| **trackingID**                                            | *선택 사항* | 외부 추적 제공자가 사용하는 ID       |
| stocks                                                    | *선택 사항* | 상품 변형 ID와 재고 상태를 매핑하는 맵. |
| `true`는 재고 있음, `false`(기본값)는 품절, emptyMap 또는 미지정 시 확인 생략. |         |                          |

```kotlin theme={null}
Kleep.builder(this, onResult = {
	when (it) {
	    is KleepResult.NotSupported -> {
	        // Handle the NotSupported case
	    }
	
	    is KleepResult.NoRecommendationYet -> {
	        // Handle the NoRecommendationYet casem
	    }
	
	    is KleepResult.RecommendationFound -> {
	        val resultText = it.size
	        val variantId = it.variantId
	        // addToCart(variantId)
	        
	        Toast.makeText(this, resultText, Toast.LENGTH_SHORT).show()
      }

      else -> {

      }
    }
})
	.setPackageName(packageName)         // optional
	.setLang(DEFAULT_LANGUAGE)           // required: "fr", "en", "es", "it", "pt", "nl"
	.setProductId("1234")                // required
	.setRetailer("retailer_name")        // required
	.setTrackingId("tracking_id")        // optional
	.setCustomerId("unique_customer_id") // optional
	.setStocks(stocks: Map<String, Boolean>) // optional
	.show()
```

### 메서드 3: `track`

이 메서드는 커스텀 이벤트를 추적하는 데 사용됩니다.

```kotlin theme={null}
Kleep.track(eventName: String, eventInfo: Map<String, String>)
```

3가지 이벤트를 추적합니다:

| eventName               | 트리거               |
| ----------------------- | ----------------- |
| `product_viewed`        | 상품 페이지 (PDP) 조회 시 |
| `product_added_to_cart` | 장바구니에 상품 추가 시     |
| `checkout_completed`    | 결제 후 주문 확인 시      |

**`product_viewed`**

[파라미터 (CSV)](/images/android/Untitled%202c68bfd3e84981db82a9f924cf43673d.csv)

**예시**

```jsx theme={null}
{
		productId: str
}
```

**`product_added_to_cart`**

[파라미터 (CSV)](/images/android/Untitled%202c68bfd3e8498100baf9d17e8b7df5e0.csv)

**예시**

```jsx theme={null}
{
    productId: str,
    variantId: str,
    cart: [
	    {
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
				sku: "XYZ",
		    size: "S",
		    quantity: 2,
		    price: {
						amount: "50",
				    currencyCode: "EUR"		    
		    }
	    },
	    {
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
		    sku: "XYZ",
		    size: "S",
		    quantity: 1,
		    price: {
				    amount: "40",
				    currencyCode: "USD"
				}
	    }
	    ...
    ],
}
```

**`checkout_completed`**

[파라미터 (CSV)](/images/android/Untitled%202c68bfd3e84981b0bdecd417ba621e4e.csv)

**예시**

```jsx theme={null}
{
    orderId: "000001",
    cart: [
	    {
		    lineItemId: "000001#1",
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
				sku: "XYZ",
		    size: "S",
		    quantity: 2,
		    price: {
						amount: "50",
				    currencyCode: "EUR"		    
		    }
	    },
	    {
			  lineItemId: "000000#2",
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
		    sku: "XYZ",
		    size: "S",
		    quantity: 1,
		    price: {
				    amount: "40",
				    currencyCode: "USD"
				}
	    }
	    ...
    ],
}
```
