# 브랜드페이 연동

원문: https://developers.bootpay.ai/api/pg/brandpay/integration

> 결제위젯에 user_token을 연결해 저장된 결제수단으로 다시 결제하는 브랜드페이 연동 가이드

[결제위젯](https://developers.bootpay.ai/api/pg/widget/one-time) 연동에 브랜드페이 설정과 `user_token` 전달을 더해, 로그인 회원이 저장한 결제수단을 위젯에 보여 줍니다. 별도 결제 SDK는 필요하지 않고, [결제위젯 연동](https://developers.bootpay.ai/api/pg/widget/one-time)이 먼저 끝나 있어야 합니다.

순서는 관리자에서 위젯의 브랜드페이 결제수단 켜기 → 백엔드에서 로그인 회원의 `user_token` 발급 → 위젯 렌더링 payload 에 `user_token` 전달입니다. 브랜드페이가 맞는 경우와 화면 분기는 가이드 [PG 결제 › 브랜드페이](https://developers.bootpay.ai/docs/pg#결제-방식-고르기)에 있습니다.

## 0. 전체 동작 방식

로그인 회원의 `user_token`을 받아 위젯 렌더링에 넣습니다. 브랜드페이가 추가로 관여하는 지점은 **회원 식별 → 저장 수단 표시**까지입니다.

### 요청 흐름

:::canvas-sequence
{
  "participants": [
    { "id": "user", "label": "구매자" },
    { "id": "fe", "label": "프론트엔드" },
    { "id": "be", "label": "백엔드" },
    { "id": "widget", "label": "결제위젯" },
    { "id": "bp", "label": "Bootpay/PG" }
  ],
  "messages": [
    { "from": "user", "to": "fe", "label": "결제 페이지 진입", "type": "solid" },
    { "from": "fe", "to": "be", "label": "로그인 회원 user_token 요청", "type": "solid" },
    { "from": "be", "to": "bp", "label": "requestUserToken()", "type": "solid" },
    { "from": "bp", "to": "be", "label": "user_token 응답", "type": "dashed" },
    { "from": "be", "to": "fe", "label": "user_token 전달", "type": "dashed" },
    { "from": "fe", "to": "widget", "label": "user_token 포함해 위젯 렌더링", "type": "solid" },
    { "from": "widget", "to": "user", "label": "저장된 결제수단 표시", "type": "dashed" },
    { "from": "user", "to": "fe", "label": "결제 요청", "type": "solid" },
    { "from": "fe", "to": "bp", "label": "requestPayment()", "type": "solid" },
    { "from": "bp", "to": "fe", "label": "receipt_id 응답", "type": "dashed" },
    { "from": "fe", "to": "be", "label": "receipt_id 전달", "type": "solid" },
    { "from": "be", "to": "bp", "label": "결제 조회 API 호출", "type": "solid" }
  ]
}
:::

결제 요청 이후에는 결제위젯 문서의 서버 검증 흐름으로 돌아갑니다. 결제 결과는 서버에서 `receipt_id` 기준으로 처리해야 합니다.

## 1. 관리자에서 브랜드페이 켜기

브랜드페이는 위젯마다 켭니다. 관리자 화면 순서는 매뉴얼 [저장한 카드로 빠르게 결제받기](https://blog.bootpay.ai/articles/pg-brandpay)에 있습니다. 결제위젯 자체의 설정은 [단건결제위젯 › widget_key 규칙](https://developers.bootpay.ai/api/pg/widget/one-time#widget_key-규칙)에 있습니다.

브랜드페이를 켠 결제수단은 위젯 안에서 저장된 카드 · 계좌를 먼저 보여 주고, 첫 결제 때 저장 동의 화면을 띄웁니다. 켜지 않은 결제수단은 결제는 되지만 저장 흐름이 동작하지 않습니다.

::: warning 정기결제는 구독 결제 위젯으로 만듭니다
빌링키 결제 방식 옵션은 구독 결제 위젯에서만 노출됩니다. `하나만 선택`은 사용자가 매번 결제수단을 고르고, `우선순위대로 결제`는 등록된 우선순위에 따라 자동으로 결제합니다.
:::

## 2. 서버에서 회원 토큰 발급

결제 페이지가 로드될 때 서버에서 로그인 세션을 확인하고 `user_token`을 발급합니다. `user_id`에는 가맹점 DB의 회원 PK, user idx, UUID처럼 **같은 회원을 다시 식별할 수 있는 고유값**을 넣습니다. 토큰은 **1시간 유효**하므로 결제 페이지 진입 시마다 새로 발급합니다.

::: code-group sync=backend

```javascript [Node.js]
import { Bootpay } from '@bootpay/backend-js'

// 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
app.get('/api/checkout', async (req, res) => {
    Bootpay.setConfiguration({
        client_key: '[ Client Key ]',
        secret_key: '[ Secret Key ]'
    })
    const tokenResponse = await Bootpay.requestUserToken({
        user_id: req.user.id,          // 로그인된 회원 고유 ID
        email: req.user.email,
        username: req.user.name,
        phone: req.user.phone,
        gender: 1,                     // 선택. 1 남성 / 0 여성 (미지정은 -1)
        birth: '1990-01-01'            // 선택. 생년월일
    })

    res.json({
        user_token: tokenResponse.user_token,
        order: req.order
    })
})
```

```python [Python]
from bootpay_backend import BootpayBackend

# 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
@app.route('/api/checkout')
@login_required
def checkout():
    bootpay = BootpayBackend(client_key='CLIENT_KEY', secret_key='SECRET_KEY')
    token_response = bootpay.request_user_token(
        user_id=current_user.id,
        email=current_user.email,
        username=current_user.name,
        phone=current_user.phone
    )

    return jsonify({
        'user_token': token_response['user_token'],  # SDK 는 응답 JSON 을 dict 로 그대로 돌려준다
        'order': order_data
    })
```

```php [PHP]
use Bootpay\ServerPhp\BootpayApi;

// 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
BootpayApi::setClientKeyConfiguration('CLIENT_KEY', 'SECRET_KEY');
$tokenResponse = BootpayApi::requestUserToken([
    'user_id'  => $user->id,
    'email'    => $user->email,
    'username' => $user->name,
    'phone'    => $user->phone,
]);

echo json_encode([
    'user_token' => $tokenResponse->user_token,
]);
```

```java [Java]
import kr.co.bootpay.pg.Bootpay;
import kr.co.bootpay.pg.model.request.UserToken;

// 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
Bootpay bootpay = Bootpay.withClientKey("CLIENT_KEY", "SECRET_KEY");
UserToken params = new UserToken();
params.userId = user.getId();
params.email = user.getEmail();
params.username = user.getName();
params.phone = user.getPhone();

var tokenResponse = bootpay.getUserToken(params);
// tokenResponse.get("user_token") → 프론트엔드에 전달
```

```ruby [Ruby]
bootpay = Bootpay::RestClient.new(client_key: 'CLIENT_KEY', secret_key: 'SECRET_KEY')
# 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
token_response = bootpay.request_user_token(
  user_id: current_user.id,
  email: current_user.email,
  username: current_user.name,
  phone: current_user.phone
)

render json: { user_token: token_response.data[:user_token] }
```

```go [Go]
import "github.com/bootpay/backend-go/v2"

// 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
api := bootpay.NewAPIWithClientKey("CLIENT_KEY", "SECRET_KEY", nil, "")
tokenResponse, _ := api.RequestUserToken(bootpay.UserTokenRequest{
    UserId:   user.ID,
    Email:    user.Email,
    Username: user.Name,
    Phone:    user.Phone,
})
// tokenResponse["user_token"] → 프론트엔드에 전달
```

```csharp [.NET]
using Bootpay;
using Bootpay.models;

// 결제 페이지 API — 회원 토큰을 발급하여 프론트엔드에 전달
var bootpay = BootpayApi.WithClientKey("CLIENT_KEY", "SECRET_KEY");
var tokenResponse = await bootpay.GetUserToken(new UserToken
{
    userId = user.Id,
    email = user.Email,
    username = user.Name,
    phone = user.Phone
});
// tokenResponse 는 HttpResponseMessage — 본문(await tokenResponse.Content.ReadAsStringAsync())의 user_token → 프론트엔드에 전달
```

:::

::: tip
`user_id`·`email`·`username`·`phone` 외에 `gender`(`1` 남성 / `0` 여성, 미지정은 `-1`)와 `birth`(생년월일)도 함께 보낼 수 있습니다. 회원 토큰 API의 전체 파라미터·응답 스펙은 [회원 토큰](https://developers.bootpay.ai/api/common/user-token) 문서를 참고합니다.
:::

## 3. 결제위젯에 `user_token` 전달

서버에서 받은 `user_token`을 결제위젯 렌더링 payload에 전달합니다. 아래 예제는 기존 렌더링 코드에서 토큰이 들어가는 위치를 보여줍니다.

::: code-group sync=platform

```javascript [Web (NPM)]
import { BootpayWidget } from '@bootpay/client-js'

// 서버에서 받은 user_token
const { user_token } = await fetch('/api/checkout').then(r => r.json())

BootpayWidget.render('#bootpay-widget', {
    client_key: '[ Client Key ]',
    price: 39000,
    sandbox: true,
    use_terms: true,
    user_token: user_token,      // 로그인 회원의 브랜드페이 식별 토큰
    hooks: {
        ready: (data) => console.log('위젯 준비 완료', data),
        allTermsAccepted: () => {
            document.getElementById('pay-button').disabled = false
        }
    }
})
```

```html [Web (CDN)]
<div id="bootpay-widget"></div>
<button id="pay-button" disabled>결제하기</button>

<script src="https://js.bootpay.co.kr/bootpay-5.5.2.min.js"></script>
<script>
fetch('/api/checkout')
    .then(function(r) { return r.json() })
    .then(function(data) {
        BootpayWidget.render('#bootpay-widget', {
            client_key: '[ Client Key ]',
            price: 39000,
            sandbox: true,
            use_terms: true,
            user_token: data.user_token,  // 로그인 회원의 브랜드페이 식별 토큰
            hooks: {
                ready: function() { console.log('위젯 준비 완료') },
                allTermsAccepted: function() {
                    document.getElementById('pay-button').disabled = false
                }
            }
        })
    })
</script>
```

```kotlin [Android]
// 가맹점 서버 API에서 user_token을 받아온 후
val token = api.getUserToken()

val payload = Payload().apply {
    clientKey = "[ Client Key ]"
    price = 39000.0
    widgetSandbox = true
    widgetUseTerms = true
    userToken = token  // 로그인 회원의 브랜드페이 식별 토큰
}

// widgetEventListener 는 결제위젯 문서의 BootpayWidgetEventListener 를 그대로 씁니다
BootpayWidget.bindViewUpdate(this, supportFragmentManager, webViewContainer)
BootpayWidget.renderWidget(this, payload, widgetEventListener)
```

```swift [iOS]
// 가맹점 서버 API에서 user_token을 받아온 후
let userToken = api.getUserToken()

let payload = Payload()
payload.clientKey = "[ Client Key ]"
payload.price = 39000
payload.widgetSandbox = true
payload.widgetUseTerms = true
payload.userToken = userToken  // 로그인 회원의 브랜드페이 식별 토큰

// widgetView · widgetController 는 결제위젯 문서의 설정을 그대로 씁니다
widgetView.controller = widgetController
widgetView.payload = payload
widgetView.startWidget()
```

```dart [Flutter]
final userToken = await api.getUserToken();

final payload = Payload()
  ..clientKey = '[ Client Key ]'
  ..price = 39000
  ..widgetSandbox = true
  ..widgetUseTerms = true
  ..userToken = userToken;  // 로그인 회원의 브랜드페이 식별 토큰

// 위젯은 BootpayWidget 으로 그립니다 (_controller 는 결제위젯 문서의 설정)
BootpayWidget(payload: payload, controller: _controller);
```

```dart [Flutter Web]
final userToken = await api.getUserToken();

final payload = Payload()
  ..clientKey = '[ Client Key ]'
  ..price = 39000
  ..widgetSandbox = true
  ..widgetUseTerms = true
  ..userToken = userToken;  // 로그인 회원의 브랜드페이 식별 토큰

// 위젯은 BootpayWidget 으로 그립니다 (_controller 는 결제위젯 문서의 설정)
BootpayWidget(payload: payload, controller: _controller);
// Flutter Web은 web/index.html에 JS SDK 스크립트 추가 필수
```

```tsx [React Native]
// react-native-bootpay-api 13.15.1 의 WidgetPayload 에는 user_token 필드가 없고,
// renderWidget() 도 위젯에 user_token 을 넘기지 않습니다.
// 아래 코드는 위젯을 비회원(user_token 없음) 상태로 그립니다.
<BootpayWidget
    ref={bootpayWidget}
    client_key={'[ Client Key ]'}
    onWidgetReady={() => {
        bootpayWidget.current?.renderWidget({
            price: 39000,
            widget_sandbox: true,
            widget_use_terms: true,
        })
    }}
    onDone={(data) => console.log('Done:', data)}
    onError={(data) => console.log('Error:', data)}
/>
```

:::

## 4. 로그인 상태와 저장 수단에 따른 분기

같은 위젯이라도 로그인 여부와 저장 수단 존재 여부에 따라 동작이 달라집니다. 구매자가 보는 화면은 가이드 [PG 결제](https://developers.bootpay.ai/docs/pg#결제-방식-고르기) 브랜드페이 탭에 있습니다.

::: preview brandpay-token
:::

| 분기 | 구현 포인트 |
|------|-------------|
| `user_token` 미전달 | 비로그인 주문서는 토큰 없이 렌더링합니다. 일반 결제위젯으로 뜹니다 |
| `user_token` 전달 + 저장된 수단 없음 | 브랜드페이 아래에 「첫 결제수단 등록하기」가 뜨고, 카드 등록 창에서 동의한 뒤 등록합니다 |
| `user_token` 전달 + 저장된 수단 있음 | 저장된 카드·계좌가 먼저 보여 재방문 회원이 원클릭으로 결제합니다 |

## 5. FAQ

### user_token이 만료되면 어떻게 됩니까?

위젯 렌더 시점에 토큰이 만료돼 있으면 브랜드페이가 비활성화되고 일반 결제위젯으로 동작합니다. 토큰은 1시간 유효하므로 결제 페이지 진입 시마다 새로 발급합니다.

### 같은 회원이 여러 디바이스에서 결제하면 저장된 수단이 공유됩니까?

`user_token`의 식별자(`user_id`)가 같으면 디바이스가 달라도 같은 회원으로 보고 저장된 결제수단을 함께 보여줍니다. 회원 식별자를 바꾸지 않는 것이 전제입니다.

## 함께 보기

- [저장한 카드로 빠르게 결제받기](https://blog.bootpay.ai/articles/pg-brandpay) — 관리자에서 브랜드페이 켜기 (매뉴얼)
