### Example: Before Migration (granite.config.ts) Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0/SDK3.0 This is an example of the configuration file before migrating to SDK 3.x. Note the structure and properties like 'brand', 'web', and 'webViewProps'. ```typescript import { defineConfig } from '@apps-in-toss/web-framework/config'; export default defineConfig({ appName: 'my-app', brand: { displayName: '내 앱', primaryColor: '#3182F6', icon: 'https://...', }, web: { host: 'localhost', port: 3000, commands: { dev: 'vite --port 3000', build: 'vite build', }, }, webViewProps: { type: 'partner', }, permissions: [], outdir: 'dist', }); ``` -------------------------------- ### Install Pixel Script Source: https://developers-apps-in-toss.toss.im/tosspixel/develop Add this script to the `` section of your HTML to enable the pixel. This is a one-time setup. ```html ``` -------------------------------- ### Example: After Migration (apps-in-toss.config.ts) Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0/SDK3.0 This is an example of the configuration file after migrating to SDK 3.x. Observe the changes in property names like 'brand', 'webView', and 'webBundleDir'. ```typescript import { defineConfig } from '@apps-in-toss/web-framework/config'; export default defineConfig({ appName: 'my-app', brand: { primaryColor: '#3182F6', }, webView: {}, permissions: [], webBundleDir: 'dist', }); ``` -------------------------------- ### Install plugin-env with npm, yarn, or pnpm Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%ED%99%98%EA%B2%BD%20%EB%B3%80%EC%88%98/env Install the plugin-env package using your preferred package manager. ```bash # npm을 사용하는 경우 npm install '@granite-js/plugin-env'; ``` ```bash # yarn을 사용하는 경우 yarn add '@granite-js/plugin-env'; ``` ```bash # pnpm을 사용하는 경우 pnpm add '@granite-js/plugin-env'; ``` -------------------------------- ### Shell (curl) Request Example Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9D%B8%EC%A6%9D/tosscertAccessToken Example of how to request an Access Token using curl. Ensure to replace placeholders with your actual client ID and secret. ```bash curl --request POST 'https://oauth2.cert.toss.im/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'grant_type=client_credentials' \ --data-urlencode 'client_id=test_a8e23336d673ca70922b485fe806eb2d' \ --data-urlencode 'client_secret=test_418087247d66da09fda1964dc4734e453c7cf66a7a9e3' \ --data-urlencode 'scope=ca' ``` -------------------------------- ### Run Development Server with npm Source: https://developers-apps-in-toss.toss.im/tosspixel/develop Use this command to start your local development server using npm. ```sh npm run dev ``` -------------------------------- ### Java Request Example Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9D%B8%EC%A6%9D/tosscertAccessToken Example of how to request an Access Token using Java's HttpURLConnection. This demonstrates setting headers and request body for the POST request. ```java URL url = new URL("https://oauth2.cert.toss.im/token"); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream()); writer.write("grant_type=client_credentials&" + "client_id=test_a8e23336d673ca70922b485fe806eb2d&" + "client_secret=test_418087247d66da09fda1964dc4734e453c7cf66a7a9e3&" + "scope=ca"); writer.flush(); writer.close(); httpConn.getOutputStream().close(); InputStream responseStream = httpConn.getResponseCode() == 200 ? httpConn.getInputStream() : httpConn.getErrorStream(); Scanner s = new Scanner(responseStream).useDelimiter("\\A"); String response = s.hasNext() ? s.next() : ""; System.out.println(response); ``` -------------------------------- ### Run Development Server with pnpm Source: https://developers-apps-in-toss.toss.im/tosspixel/develop Use this command to start your local development server using pnpm. ```sh pnpm run dev ``` -------------------------------- ### Install Android App via ADB Source: https://developers-apps-in-toss.toss.im/development/test/sandbox Use the adb command to install the APK file on an Android device or emulator. Ensure you are in the directory containing the APK file. ```shell # APK 파일이 있는 폴더로 이동 후 실행 adb install -r -t {파일이름} # 예시 adb install -r -t apssintoss-debug.apk ``` -------------------------------- ### Run Development Server with Yarn Source: https://developers-apps-in-toss.toss.im/tosspixel/develop Use this command to start your local development server using Yarn. ```sh yarn dev ``` -------------------------------- ### Start Real-time Location Updates (Web JS) Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9C%84%EC%B9%98%20%EC%A0%95%EB%B3%B4/Location Starts real-time location tracking and logs latitude and longitude. Call the returned cleanup function to stop tracking. Handles permission errors. ```javascript import { Accuracy, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/web-framework'; let cleanup; function handleStartUpdateLocation() { cleanup?.(); cleanup = startUpdateLocation({ options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 }, onEvent: (location) => { console.log(`위도: ${location.coords.latitude}, 경도: ${location.coords.longitude}`); }, onError: (error) => { if (error instanceof StartUpdateLocationPermissionError) { console.log('위치 정보 권한 없음'); } }, }); } window.addEventListener('pagehide', () => cleanup?.()); ``` -------------------------------- ### Example: Handling Reward on Share Completion Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%B9%9C%EA%B5%AC%EC%B4%88%EB%8C%80/contactsViral Shows how to handle the 'sendViral' event to log the reward amount and unit when a friend is successfully invited. ```typescript contactsViral({ options: { moduleId: 'your-module-id' }, onEvent: (event) => { if (event.type === 'sendViral') { console.log('리워드 지급:', event.data.rewardAmount, event.data.rewardUnit); } }, onError: (error) => { console.error('에러 발생:', error); }, }); ``` -------------------------------- ### startUpdateLocation Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9C%84%EC%B9%98%20%EC%A0%95%EB%B3%B4/Location Starts real-time location tracking. It executes a callback whenever the location changes. The returned cleanup function stops the tracking. ```APIDOC ## startUpdateLocation ### Description Starts real-time location tracking. It executes a callback whenever the location changes. The returned cleanup function stops the tracking. ### Method Signature ```typescript function startUpdateLocation(options: { onError: (error: unknown) => void; onEvent: (location: Location) => void; options: StartUpdateLocationOptions; }): () => void; ``` ### Parameters - **options** (object) - Required - Configuration for starting location updates. - **onError** (function) - Required - Callback function to handle errors. - **error** (unknown) - The error object. - **onEvent** (function) - Required - Callback function to handle location events. - **location** (Location) - The updated location object. - **options** (StartUpdateLocationOptions) - Required - Additional options for location tracking. - **accuracy** (Accuracy) - The desired accuracy level (e.g., `Accuracy.Balanced`). - **timeInterval** (number) - The interval in milliseconds between location updates. - **distanceInterval** (number) - The minimum distance in meters to trigger a new update. ### Return Value - **() => void** - A function that, when called, stops the location tracking. ### Error Handling - **StartUpdateLocationPermissionError**: Thrown when location permission is denied. Check using `error instanceof StartUpdateLocationPermissionError`. ### Examples #### Web (JS) ```javascript import { Accuracy, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/web-framework'; let cleanup; function handleStartUpdateLocation() { cleanup?.(); cleanup = startUpdateLocation({ options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 }, onEvent: (location) => { console.log(`위도: ${location.coords.latitude}, 경도: ${location.coords.longitude}`); }, onError: (error) => { if (error instanceof StartUpdateLocationPermissionError) { console.log('위치 정보 권한 없음'); } }, }); } window.addEventListener('pagehide', () => cleanup?.()); ``` #### Web (React) ```jsx import { Accuracy, Location, startUpdateLocation, StartUpdateLocationPermissionError, } from '@apps-in-toss/web-framework'; import { useCallback, useState } from 'react'; function LocationWatcher() { const [location, setLocation] = useState(null); const handlePress = useCallback(() => { startUpdateLocation({ options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 }, onEvent: (location) => setLocation(location), onError: (error) => { if (error instanceof StartUpdateLocationPermissionError) { // 위치 정보 권한 없음 } }, }); }, []); return (
{location != null && ( <> 위도: {location.coords.latitude} 경도: {location.coords.longitude} )}
); } ``` #### React Native ```jsx import { Accuracy, Location, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/framework'; import { useCallback, useState } from 'react'; import { Button, Text, View } from 'react-native'; function LocationWatcher() { const [location, setLocation] = useState(null); const handlePress = useCallback(() => { startUpdateLocation({ options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 }, onEvent: (location) => setLocation(location), onError: (error) => { if (error instanceof StartUpdateLocationPermissionError) { // 위치 정보 권한 없음 } }, }); }, []); return ( {location != null && ( <> 위도: {location.coords.latitude} 경도: {location.coords.longitude} )} ); } ``` -------------------------------- ### Loading Screen HTML Example with Data URI Source: https://developers-apps-in-toss.toss.im/unity/sdk/loading-screen Shows how to embed small image resources directly into the HTML using Data URIs. This method is suitable for very small assets to avoid external dependencies. ```html ``` -------------------------------- ### Get Current Location (Web React) Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9C%84%EC%B9%98%20%EC%A0%95%EB%B3%B4/Location A React component to fetch and display the device's current location. Includes buttons to get location, check permission status, and request permission. Requires location permissions. ```typescript import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError, Location } from '@apps-in-toss/web-framework'; import { useState } from 'react'; function CurrentPosition() { const [position, setPosition] = useState(null); const handlePress = async () => { try { const response = await getCurrentLocation({ accuracy: Accuracy.Balanced }); setPosition(response); } catch (error) { if (error instanceof GetCurrentLocationPermissionError) { // 위치 정보 권한 없음 } } }; return (
{position ? ( 위치: {position.coords.latitude}, {position.coords.longitude} ) : ( 위치 정보를 아직 가져오지 않았어요 )} alert(await getCurrentLocation.getPermission())} /> alert(await getCurrentLocation.openPermissionDialog())} />
); } ``` -------------------------------- ### Get Current Location (React Native) Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9C%84%EC%B9%98%20%EC%A0%95%EB%B3%B4/Location A React Native component to fetch and display the device's current location. Includes buttons for getting location, checking permission, and opening the permission dialog. Requires location permissions. ```typescript import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError, Location } from '@apps-in-toss/framework'; import { useState } from 'react'; import { Alert, Button, Text, View } from 'react-native'; function CurrentPosition() { const [position, setPosition] = useState(null); const handlePress = async () => { try { const response = await getCurrentLocation({ accuracy: Accuracy.Balanced }); setPosition(response); } catch (error) { if (error instanceof GetCurrentLocationPermissionError) { // 위치 정보 권한 없음 } } }; return ( {position ? ( 위치: {position.coords.latitude}, {position.coords.longitude} ) : ( 위치 정보를 아직 가져오지 않았어요 )} ; } ``` -------------------------------- ### Update React Native Framework to 2.x Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0/SDK2.0.1 Update the `@apps-in-toss/framework` package to version 2.x. This command installs version 2.4.1. ```bash # npm npm install @apps-in-toss/framework@2.4.1 # yarn yarn add @apps-in-toss/framework@2.4.1 # pnpm pnpm add @apps-in-toss/framework@2.4.1 ``` -------------------------------- ### Initiate TossPay Payment and Handle Authentication (JavaScript) Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%ED%86%A0%EC%8A%A4%ED%8E%98%EC%9D%B4/TossPay Launches the TossPay payment window for user authentication. Actual payment execution must be handled server-side after successful authentication. Requires fetching a payToken from a backend API. ```js import { checkoutPayment } from '@apps-in-toss/web-framework'; async function handleCheckoutPayment() { try { // 실제 구현 시 결제 생성 역할을 하는 API 엔드포인트로 대체해주세요. const { payToken } = await fetch('/my-api/payment/create').then((res) => res.json()); const { success, reason } = await checkoutPayment({ payToken }); if (success) { // 실제 구현 시 결제를 실행하는 API 엔드포인트로 대체해주세요. await fetch('/my-api/payment/execute', { method: 'POST', body: JSON.stringify({ payToken }), headers: { 'Content-Type': 'application/json' }, }); console.log('결제 성공'); } else { console.log('인증 실패:', reason); } } catch (error) { console.error('결제 인증 중 오류가 발생했어요:', error); } } ``` -------------------------------- ### Get Payment Status Source: https://developers-apps-in-toss.toss.im/tosspay/develop Retrieves the transaction status and details for a generated payment. This can be used even if approval or refund responses were not received. ```APIDOC ## POST /api-partner/v1/apps-in-toss/pay/get-payment-status ### Description Retrieves the transaction status and details for a generated payment. This can be used even if approval or refund responses were not received. ### Method POST ### Endpoint /api-partner/v1/apps-in-toss/pay/get-payment-status ### Headers - **x-toss-user-key** (string) - Required - The userKey value obtained through Toss login. ### Parameters #### Query Parameters - **payToken** (String) - Required - The Toss Payments token. - **orderNo** (String) - Required - The merchant's order number. - **isTestPayment** (boolean) - Required - Set to `true` if the `payToken` was issued in the sandbox, `false` if issued in the live app. ```