import { isMinVersionSupported } from './isMinVersionSupported'; import { safePostMessage } from '../../natives'; import { USER_KEY_MIN_VERSION } from '../constants'; export interface GetAnonymousKeySuccessResponse { hash: string; type: 'HASH'; } export type GetAnonymousKeyResponse = GetAnonymousKeySuccessResponse; /** * @public * @name getAnonymousKey * @description * 미니앱에서 사용자의 고유 키를 가져와요. 이 키를 사용해서 사용자를 식별하고 데이터를 관리할 수 있어요. * @returns {Promise} * 사용자 키 조회 결과를 반환해요. * - `GetAnonymousKeyResponse`: 사용자 키 조회에 성공했어요. `{ type: 'HASH', hash: string }` 형태로 반환돼요. * - `'ERROR'`: 알 수 없는 오류가 발생했어요. * - `undefined`: 앱 버전이 최소 지원 버전보다 낮아요. * * @example * ```tsx * // react-native * import { Button } from 'react-native'; * import { getAnonymousKey } from '@apps-in-toss/framework'; * * function UserKeyButton() { * async function handlePress() { * const result = await getAnonymousKey(); * * if (!result) { * console.warn('지원하지 않는 앱 버전이에요.'); * return; * } * * if (result === 'ERROR') { * console.error('사용자 키 조회 중 오류가 발생했어요.'); * return; * } * * if (result.type === 'HASH') { * console.log('사용자 키:', result.hash); * // 여기에서 사용자 키를 사용해 데이터를 관리할 수 있어요. * } * } * * return ( * * ); * } * ``` */ export async function getAnonymousKey(): Promise { const isSupported = isMinVersionSupported(USER_KEY_MIN_VERSION); if (!isSupported) { return; } try { const response = (await safePostMessage('getUserKeyForGame', {})) as GetAnonymousKeyResponse; if (response.type === 'HASH') { return response; } return 'ERROR'; } catch { return 'ERROR'; } }