### 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 (
);
}
```
#### 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}
>
)}
);
}
```
```
--------------------------------
### Update @apps-in-toss/web-framework to SDK 3.x
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
Install the beta version of @apps-in-toss/web-framework to begin the migration. This command is applicable for npm, yarn, and pnpm package managers.
```sh
npm install @apps-in-toss/web-framework@beta
```
```sh
yarn add @apps-in-toss/web-framework@beta
```
```sh
pnpm add @apps-in-toss/web-framework@beta
```
--------------------------------
### Example: Handling Module Close Event
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%B9%9C%EA%B5%AC%EC%B4%88%EB%8C%80/contactsViral
Demonstrates how to process the 'close' event from contactsViral, logging the close reason and the count of friends shared with.
```typescript
contactsViral({
options: { moduleId: 'your-module-id' },
onEvent: (event) => {
if (event.type === 'close') {
console.log('종료 사유:', event.data.closeReason);
console.log('공유 완료한 친구 수:', event.data.sentRewardsCount);
}
},
onError: (error) => {
console.error('에러 발생:', error);
},
});
```
--------------------------------
### Build Mini-App
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
Execute this command to build your mini-app after migration. Ensure that all type errors have been resolved.
```bash
ait build
```
--------------------------------
### CI/CD 앱 번들 업로드 명령어
Source: https://developers-apps-in-toss.toss.im/development/test/toss
CLI를 통해 앱 번들을 업로드하고 테스트용 앱스킴을 생성합니다. SDK v1.4.0 이상에서 지원하며, API 키를 발급받아 사용합니다.
```sh
npx ait deploy --api-key {API 키}
```
```sh
npx ait token add
npx ait deploy
```
```sh
npx ait deploy -m "출시메모"
```
--------------------------------
### Loading Screen HTML Example with StreamingAssets
Source: https://developers-apps-in-toss.toss.im/unity/sdk/loading-screen
Demonstrates how to reference local assets from the StreamingAssets folder within the custom loading screen HTML. This is the recommended method for including external resources.
```html
```
--------------------------------
### Loading Screen HTML Example with CDN
Source: https://developers-apps-in-toss.toss.im/unity/sdk/loading-screen
Illustrates loading external resources from a Content Delivery Network (CDN). Use this method if assets are hosted externally, but be aware of potential network dependencies.
```html
```
--------------------------------
### PHP 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 PHP's cURL library. This snippet shows how to configure and execute a POST request with form-urlencoded data.
```php
```
--------------------------------
### JavaScript Example: Handle Contacts Viral Flow
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%B9%9C%EA%B5%AC%EC%B4%88%EB%8C%80/contactsViral
This JavaScript example demonstrates the basic flow of executing the contactsViral function and handling share completion or module close events. It includes cleanup logic.
```javascript
import { contactsViral } from '@apps-in-toss/web-framework';
function handleContactsViral(moduleId) {
const cleanup = contactsViral({
options: { moduleId: moduleId.trim() },
onEvent: (event) => {
if (event.type === 'sendViral') {
console.log('리워드 지급:', event.data.rewardAmount, event.data.rewardUnit);
} else if (event.type === 'close') {
console.log('모듈 종료:', event.data.closeReason);
cleanup();
}
},
onError: (error) => {
console.error('에러 발생:', error);
cleanup?.();
},
});
}
```
--------------------------------
### Start Real-time Location Updates (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 start real-time location tracking and display coordinates. It uses `useState` to manage location data and `useCallback` for the event handler. Handles permission errors.
```typescript
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 (
);
}
```
--------------------------------
### Initiate Toss Login (React)
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EB%A1%9C%EA%B7%B8%EC%9D%B8/appLogin
This React snippet demonstrates how to integrate the `appLogin` function with a button click. The authorization code and referrer are then passed to the server.
```tsx
import { appLogin } from '@apps-in-toss/web-framework';
import { Button } from '@toss/tds-mobile';
function Page() {
async function handleLogin() {
const { authorizationCode, referrer } = await appLogin();
// 획득한 인가 코드(`authorizationCode`)와 `referrer`를 서버로 전달해요.
}
return (
);
}
```
--------------------------------
### 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}
) : (
위치 정보를 아직 가져오지 않았어요
)}
);
}
```
--------------------------------
### Start Real-time Location Updates (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 start real-time location tracking and display coordinates using native components. It uses `useState` for location data and `useCallback` for the event handler. Handles permission errors.
```typescript
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}
>
)}
);
}
```
--------------------------------
### Successful Response: Order Purchased
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9D%B8%EC%95%B1%20%EA%B2%B0%EC%A0%9C/IAP
Example of a successful response when the in-app payment and item delivery are both completed.
```json
{
"resultType": "SUCCESS",
"success": {
"orderId": "13c9a1ff-2baa-4495-bbfa-0000000000",
"sku": "ait.0000010000.af647449.00000000000.0000000475",
"statusDeterminedAt": "2025-09-12T16:57:12",
"status": "PURCHASED",
"reason": "완료된 주문이에요."
}
}
```
--------------------------------
### Successful Response: Payment Completed
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9D%B8%EC%95%B1%20%EA%B2%B0%EC%A0%9C/IAP
Example of a successful response when the payment is completed but the item has not yet been delivered.
```json
{
"resultType": "SUCCESS",
"success": {
"orderId": "13c9a1ff-2baa-4495-bbfa-a0826ba8c7c0",
"sku": "ait.0000010000.af647449.3bd55cfd00.0000000475",
"statusDeterminedAt": "2025-09-12T16:57:12",
"status": "PAYMENT_COMPLETED",
"reason": "결제가 완료되었어요."
}
}
```
--------------------------------
### Initiate Toss Login (JavaScript)
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EB%A1%9C%EA%B7%B8%EC%9D%B8/appLogin
Use this JavaScript snippet to call the `appLogin` function and obtain the authorization code. The obtained code and referrer should be sent to your server.
```js
import { appLogin } from '@apps-in-toss/web-framework';
async function handleLogin() {
const { authorizationCode, referrer } = await appLogin();
// 획득한 인가 코드(`authorizationCode`)와 `referrer`를 서버로 전달해요.
```
--------------------------------
### Get TossCert Result
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EC%9D%B8%EC%A6%9D/tosscertResult
Retrieves the result of a specific TossCert authentication request using the transaction ID.
```APIDOC
## GET /v1/cert/result
### Description
Retrieves the result of a TossCert authentication request. This endpoint is used to check the status and obtain details of a completed authentication transaction.
### Method
GET
### Endpoint
/v1/cert/result
### Parameters
#### Query Parameters
- **txId** (string) - Required - The transaction ID of the authentication request for which to check the result.
- **sessionKey** (string) - Required - A session key used for AES encryption/decryption of the request and response. This key must be newly generated for each request and cannot be reused from the authentication request.
### Request Example
```
GET /v1/cert/result?txId=YOUR_TX_ID&sessionKey=YOUR_SESSION_KEY
```
### Response
#### Success Response (200)
- **resultType** (string) - Indicates 'SUCCESS' if the request was processed successfully.
- **success.txId** (string) - The transaction ID of the authentication for which the result was retrieved.
- **success.status** (string) - The status of the authentication, expected to be 'COMPLETED' if the result retrieval was successful.
- **success.userIdentifier** (string) - Currently unused and will be null.
- **success.userCiToken** (string) - Currently unused and will be null.
- **success.signature** (string) - The electronic signature value signed by the user, Base64 encoded DER format. This must be stored and managed along with the txId.
- **success.randomValue** (string) - Currently unused and will be null.
- **success.completedDt** (string) - The timestamp when the user authentication was completed, in ISO 8601 format (YYYY-MM-DDThh:mm:ss±hh:mm).
- **success.requestedDt** (string) - The timestamp when the initial authentication request was made, in ISO 8601 format (YYYY-MM-DDThh:mm:ss±hh:mm).
- **success.personalData** (object) - Encrypted personal data used in the authentication. Refer to the sub-field table for details.
#### Response Example
```json
{
"resultType": "SUCCESS",
"success": {
"txId": "YOUR_TX_ID",
"status": "COMPLETED",
"userIdentifier": null,
"userCiToken": null,
"signature": "BASE64_ENCODED_DER_SIGNATURE",
"randomValue": null,
"completedDt": "2023-10-27T10:00:00+09:00",
"requestedDt": "2023-10-27T09:59:00+09:00",
"personalData": {
// ... encrypted personal data fields ...
}
}
}
```
```
--------------------------------
### Supabase 환경 변수 설정
Source: https://developers-apps-in-toss.toss.im/supabase/intro
Supabase 연결 정보를 보안을 위해 환경 변수로 관리합니다. 프로젝트 루트에 .env 파일을 생성하여 URL과 Publishable key를 설정하세요.
```bash
VITE_SUPABASE_URL=https://.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_xxxxxxxxxxxx
```
--------------------------------
### grantPromotionRewardForGame
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EB%B9%84%EA%B2%8C%EC%9E%84/promotion
게임 카테고리 미니앱에서 사용자에게 토스 포인트를 지급하는 함수입니다. 별도의 서버 연동 없이 게임 미니앱 내에서 직접 호출할 수 있습니다.
```APIDOC
## grantPromotionRewardForGame
### Description
게임 카테고리 미니앱에서 사용자에게 토스 포인트를 지급하는 함수입니다. 별도의 서버 연동 없이 게임 미니앱 내에서 직접 호출할 수 있습니다.
### Method
SDK 함수 호출
### Endpoint
N/A (SDK 함수)
### Parameters
#### Parameters
- **params** (object) - Required - 포인트 지급에 필요한 파라미터 객체
- **promotionCode** (string) - Required - 지급할 프로모션의 코드
- **amount** (number) - Required - 지급할 포인트 금액
### Request Example
```javascript
{
params: {
promotionCode: 'GAME_EVENT_2024',
amount: 1000
}
}
```
### Response
#### Success Response (200)
- **key** (string) - 포인트 지급에 성공했을 경우 반환되는 리워드 키
#### Error Response
- **errorCode** (string) - 포인트 지급에 실패했을 경우 반환되는 에러 코드
- **message** (string) - 포인트 지급 실패 시 에러 메시지
#### Response Example
```json
{
"key": "reward_key_12345"
}
```
```json
{
"errorCode": "4109",
"message": "프로모션이 실행중이 아니에요"
}
```
### Error Codes
- `40000`: 게임이 아닌 미니앱에서 호출한 경우
- `4100`: 프로모션 정보를 찾을 수 없어요 (콘솔에 등록되지 않은 프로모션 키)
- `4109`: 프로모션이 실행중이 아니에요 (프로모션 미시작 또는 예산 소진으로 자동 종료)
- `4110`: 리워드를 지급/회수할 수 없어요 (내부 시스템 오류, 재지급 로직 적용 필요)
- `4111`: 리워드 지급내역을 찾을 수 없어요 (존재하지 않는 지급 내역 조회)
- `4112`: 프로모션 머니가 부족해요 (예산 부족, 콘솔에서 예산 증액 또는 비즈월렛 충전 필요)
- `4114`: 1회 지급 금액을 초과했어요
- `4116`: 최대 지급 금액이 예산을 초과했어요
- `ERROR`: 알 수 없는 오류가 발생했어요.
- `undefined`: 앱 버전이 최소 지원 버전보다 낮아요.
```
--------------------------------
### Update WebView 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/web-framework` package to version 2.x. This command installs version 2.4.1.
```bash
# npm
npm install @apps-in-toss/web-framework@2.4.1
# yarn
yarn add @apps-in-toss/web-framework@2.4.1
# pnpm
pnpm add @apps-in-toss/web-framework@2.4.1
```
--------------------------------
### 게임 프로모션 리워드 지급 (React)
Source: https://developers-apps-in-toss.toss.im/bedrock/reference/framework/%EB%B9%84%EA%B2%8C%EC%9E%84/promotion
React 컴포넌트에서 버튼 클릭 시 `grantPromotionRewardForGame` 함수를 호출하여 사용자에게 포인트를 지급합니다. 결과에 따라 성공, 실패 또는 앱 버전 미지원 메시지를 처리합니다.
```tsx
import { grantPromotionRewardForGame } from '@apps-in-toss/web-framework';
function GrantRewardButton() {
async function handleClick() {
const result = await grantPromotionRewardForGame({
params: {
promotionCode: 'GAME_EVENT_2024',
amount: 1000,
},
});
if (!result) {
console.warn('지원하지 않는 앱 버전이에요.');
return;
}
if (result === 'ERROR') {
console.error('포인트 지급 중 알 수 없는 오류가 발생했어요.');
return;
}
if ('key' in result) {
console.log('포인트 지급 성공!', result.key);
} else if ('errorCode' in result) {
console.error('포인트 지급 실패:', result.errorCode, result.message);
}
}
return 포인트 지급하기;
}
```
--------------------------------
### 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.
```