# 회원 토큰

원문: https://developers.bootpay.ai/api/common/user-token

> 브랜드페이·지갑결제에 필요한 회원 토큰(UserToken) 발급 방법

브랜드페이·지갑결제에 쓰는 회원 토큰(UserToken)을 발급합니다.

서버에서 부트페이 API를 호출해 회원토큰을 발급받습니다. 회원 토큰이 하는 일은 가이드 [PG 결제 > 결제 방식 고르기](https://developers.bootpay.ai/docs/pg#결제-방식-고르기)의 브랜드페이에 있습니다.

일반 결제(PG 결제창 호출)만 사용하는 경우에는 회원토큰이 필요하지 않습니다.

## API 엔드포인트

::: endpoint
method: POST
url: https://api.bootpay.co.kr/v2/request/user/token
auth: Basic Auth
:::

::: tip 발급 시점과 유효기간
회원토큰은 발급 후 1시간 동안 유효합니다. 브랜드페이·지갑결제 화면을 띄우기 직전에 발급해 클라이언트로 전달하고, 만료되면 다시 발급합니다. 회원 식별은 `user_id` 기준이라, 재발급하더라도 같은 회원은 이전에 등록한 결제수단을 그대로 재사용합니다.
:::

## 요청 파라미터

::: parameters

| 파라미터 | 타입 | 필수 | 설명 |
|---------|------|------|------|
| user_id | String | Y | 회원 고유 ID. 저장한 결제수단이 이 값에 묶이므로 회원 PK · UUID 처럼 바뀌지 않는 값을 넣습니다 |
| email | String | N | 회원 이메일 주소 |
| username | String | N | 회원 이름 |
| phone | String | N | 회원 전화번호 |
| gender | Number | N | 회원 성별 (1: 남자, 0: 여자) |
| birth | String | N | 회원 생년월일 |

:::

::: tip 값 보정 규칙
- `email`을 넣지 않아도 `user_id`가 이메일 형식이면 서버가 그 값을 `email`로 대신 채웁니다.
- `phone`은 하이픈(`-`)을 서버에서 제거한 뒤 저장하고, 남은 자릿수가 8~12자를 벗어나면 `USER_PHONE_INVALID`로 거절합니다.
- `gender`를 넣지 않으면 `-1`(미상)로 저장됩니다.
:::

## 코드 예제

::: code-group sync=backend

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

Bootpay.setConfiguration({
    client_key: '[ Client Key ]',
    secret_key: '[ Secret Key ]'
})

try {
    const response = await Bootpay.requestUserToken({
        user_id: 'user_12345',
        email: 'user@example.com',
        username: '홍길동',
        phone: '01012345678',
        gender: 1
    })
    // user_token을 프론트엔드에 전달
    console.log(response)
} catch (e) {
    console.log(e)
}
```

```python [Python]
from bootpay_backend import BootpayBackend

bootpay = BootpayBackend(client_key='CLIENT_KEY', secret_key='SECRET_KEY')

response = bootpay.request_user_token(
    user_id='user_12345',
    email='user@example.com',
    username='홍길동',
    phone='01012345678',
    gender=1
)
print(response)
```

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

BootpayApi::setClientKeyConfiguration('CLIENT_KEY', 'SECRET_KEY');
$response = BootpayApi::requestUserToken([
    'user_id' => 'user_12345',
    'email' => 'user@example.com',
    'username' => '홍길동',
    'phone' => '01012345678',
    'gender' => 1,
]);
print_r($response);
```

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

Bootpay bootpay = Bootpay.withClientKey("CLIENT_KEY", "SECRET_KEY");
UserToken userToken = new UserToken();
userToken.userId = "user_12345";
userToken.email = "user@example.com";
userToken.username = "홍길동";
userToken.phone = "01012345678";
userToken.gender = 1;

var response = bootpay.getUserToken(userToken);
System.out.println(response);
```

```ruby [Ruby]
bootpay = Bootpay::RestClient.new(client_key: 'CLIENT_KEY', secret_key: 'SECRET_KEY')
response = bootpay.request_user_token(
  user_id: 'user_12345',
  email: 'user@example.com',
  username: '홍길동',
  phone: '01012345678',
  gender: 1
)
puts response.data
```

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

api := bootpay.NewAPIWithClientKey("CLIENT_KEY", "SECRET_KEY", nil, "")
response, err := api.RequestUserToken(bootpay.UserTokenRequest{
    UserId:   "user_12345",
    Email:    "user@example.com",
    Username: "홍길동",
    Phone:    "01012345678",
    Gender:   1,
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(response)
```

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

var bootpay = BootpayApi.WithClientKey("CLIENT_KEY", "SECRET_KEY");
var response = await bootpay.GetUserToken(new UserToken
{
    userId = "user_12345",
    email = "user@example.com",
    username = "홍길동",
    phone = "01012345678",
    gender = 1
});
Console.WriteLine(await response.Content.ReadAsStringAsync());
```

:::

## 응답

#### 성공 응답

```json
{
  "user_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expired_at": "2025-01-15T15:32:00+09:00"
}
```

## 응답 파라미터

| 파라미터 | 타입 | 설명 |
|---------|------|------|
| user_token | String | 발급 후 1시간 동안 유효한 토큰. SDK 에 전달합니다 |
| expired_at | Date | Token 만료 시간 |

## 에러 코드

::: info 공통 에러
인증·권한 관련 에러는 [에러 코드표](https://developers.bootpay.ai/api/reference/codes#인증-관련-에러)를 참고합니다.
:::

::: error-codes

| 코드 | 메시지 | 대처 방법 |
|------|--------|-----------|
| `USER_ID_BLANK` (1500) | user_id를 입력합니다 | `user_id`를 반드시 전달합니다 |
| `USER_EMAIL_INVALID` (1501) | 사용자 이메일 정보가 이메일 포맷에 맞지 않습니다. 다시 확인해주세요. | `email` 형식을 확인합니다. `user_id`가 이메일 형식이면 자동으로 대입되므로 그 값도 함께 확인합니다 |
| `USER_PHONE_INVALID` (1502) | 사용자 전화번호 정보가 전화번호 자리수에 맞지 않습니다. 다시 확인해주세요. | 하이픈을 제거한 `phone`이 8~12자인지 확인합니다 |

:::

::: info
회원정보(`email`, `username`, `phone`, `gender`, `birth`)는 프로젝트별로 생성된 암호화 키로 암호화해 저장하고, 결제할 때처럼 필요한 시점에 같은 키로 복호화해 사용합니다. 결제·통계 목적으로만 쓰이며 제3자에게 제공하지 않습니다.
:::
