Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V2 SDK readme에 ESM 설명 복붙 & V2 API Secret 발급 안내에 access token 관련 내용 제거 #357

Merged
merged 3 commits into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/content/docs/ko/ready/readme.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ import IntegrationTosspayments from './_components/integration-guide/tosspayment
</Hint>

<Hint style="danger">
API Secret은 **결제 거래 건을 컨트롤할 수 있는 민감 정보**로 외부로 유출되지 않도록 주의가 필요합니다.
API Secret은 **결제 거래 건을 컨트롤할 수 있는 민감 정보**로 고객사 서버에서만 사용되어야 하며, 브라우저 등 외부에 노출되어서는 안 됩니다.
</Hint>
</Fragment>
</VersionGate>
61 changes: 61 additions & 0 deletions src/content/docs/ko/v2-payment/_components/sdk-installation.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Tab from "~/components/gitbook/tabs/Tab.astro";
import Tabs from "~/components/gitbook/tabs/Tabs.astro";
import Hint from "~/components/Hint.astro";
import * as prose from '~/components/prose';

export const components = prose;

포트원 V2 SDK는 npm 레지스트리와 CDN을 통해 배포되고 있습니다.

- npm, yarn 등 패키지 매니저를 사용한다면 의존
대상으로 [@portone/browser-sdk](https://www.npmjs.com/package/@portone/browser-sdk)를 추가하세요.

- 패키지 매니저를 사용하지 않는다면 `<script>` 요소를 이용하여 CDN에서 SDK를 직접 불러오세요.

- CDN에서 ESM 모듈 형태로도 SDK를 제공하고 있습니다.

<Tabs>
<Tab title="패키지 의존 대상으로 추가">
사용하는 패키지 매니저에 알맞은 명령어를 실행하세요.

```shell
npm i @portone/browser-sdk
```

```shell
yarn add @portone/browser-sdk
```

```shell
pnpm add @portone/browser-sdk
```

패키지 매니저로 SDK를 불러온 경우 `PortOne` 객체를 import해서 사용합니다.

```javascript
import * as PortOne from "@portone/browser-sdk/v2";
```
</Tab>

<Tab title="<script> 요소로 추가">
```html
<script src="https://cdn.portone.io/v2/browser-sdk.js"></script>
```

`<script>` 요소로 SDK를 불러온 경우 전역 객체 `window`에 `PortOne` 객체가 추가됩니다.
</Tab>

<Tab title="ESM 모듈로 추가">
ESM 모듈을 사용하는 경우 URL에서 `PortOne` 객체를 직접 import할 수 있습니다.

```javascript
import * as PortOne from "https://cdn.portone.io/v2/browser-sdk.esm.js";
```
</Tab>
</Tabs>

<Hint style="info">
**타입스크립트 지원**

포트원 V2 SDK는 타입스크립트 선언 파일(`.d.ts`)의 형식으로 타입 정보를 제공하고 있습니다. npm 레지스트리를 이용하는 경우 각종 개발 환경에서 별도 설정 없이 사용 가능합니다.
</Hint>
146 changes: 45 additions & 101 deletions src/content/docs/ko/v2-payment/authpay.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,85 +4,24 @@ description: PG 결제창을 이용하는 인증 결제를 연동합니다.
---

import Details from "~/components/gitbook/Details.astro";
import Youtube from "~/components/gitbook/Youtube.astro";
import Hint from "~/components/Hint.astro";
import Tabs from "~/components/gitbook/tabs/Tabs.astro";
import Tab from "~/components/gitbook/tabs/Tab.astro";

import Youtube from "~/components/gitbook/Youtube.astro";
import SdkInstallation from "./_components/sdk-installation.mdx"

<Details>
<p slot="summary">
<strong>영상으로 보기</strong>
</p>
<Youtube
videoId="DhcQFLYV9Q8"
caption="포트원 인증 결제의 이해 - 쇼핑몰 멀티PG 연동하기"
/>

<Youtube videoId="DhcQFLYV9Q8" caption="포트원 인증 결제의 이해 - 쇼핑몰 멀티PG 연동하기" />
</Details>

## 1. 포트원 SDK 설치

포트원은 다양한 PG의 결제창을 통일된 방법으로 호출할 수 있도록 자바스크립트 SDK를 제공합니다. 브라우저에서 포트원 SDK를 호출하여 결제를 진행하게 됩니다.

포트원 V2 SDK는 npm 레지스트리와 CDN을 통해 배포되고 있습니다.

- npm, yarn 등 패키지 매니저를 사용한다면 의존 대상으로 [@portone/browser-sdk][npm-sdk]를 추가하세요.
- 패키지 매니저를 사용하지 않는다면 `<script>` 요소를 이용하여 CDN에서 SDK를 직접 불러오세요.
- CDN에서 ESM 모듈 형태로도 SDK를 제공하고 있습니다.

[1]: https://www.npmjs.com/package/@portone/browser-sdk

<Tabs>

<Tab title="패키지 의존 대상으로 추가">

사용하는 패키지 매니저에 알맞은 명령어를 실행하세요.

```shell
npm i @portone/browser-sdk
```

```shell
yarn add @portone/browser-sdk
```

```shell
pnpm add @portone/browser-sdk
```

패키지 매니저로 SDK를 불러온 경우 `PortOne` 객체를 import해서 사용합니다.

```typescript
import * as PortOne from "@portone/browser-sdk/v2";
```

</Tab>

<Tab title="<script> 요소로 추가">
```html
<script src="https://cdn.portone.io/v2/browser-sdk.js"></script>
```

`<script>` 요소로 SDK를 불러온 경우 전역 객체 `window`에 `PortOne` 객체가 추가됩니다.

</Tab>

<Tab title="ESM 모듈로 추가">
ESM 모듈을 사용하는 경우 URL에서 `PortOne` 객체를 직접 import할 수 있습니다.

```javascript
import * as PortOne from "https://cdn.portone.io/v2/browser-sdk.esm.js";
```
</Tab>

</Tabs>

<Hint style="info">
**타입스크립트 지원**

포트원 V2 SDK는 타입스크립트 선언 파일(`.d.ts`)의 형식으로 타입 정보를 제공하고 있습니다. npm 레지스트리를 이용하는 경우 각종 개발 환경에서 별도 설정 없이 사용 가능합니다.

</Hint>
<SdkInstallation />

## 2. 결제 요청

Expand All @@ -106,7 +45,8 @@ const response = await PortOne.requestPayment({
});
```

**paymentId**는 결제 건을 구분하는 문자열로, 결제 요청 및 조회에 필요합니다. 같은 paymentId에 대해 여러 번의 결제 시도가 가능하나, 최종적으로 결제에 성공하는 것은 단 한 번만 가능합니다. (중복 결제 방지)
**paymentId**는 결제 건을 구분하는 문자열로, 결제 요청 및 조회에 필요합니다. 같은 paymentId에 대해 여러 번의 결제 시도가 가능하나,
최종적으로 결제에 성공하는 것은 단 한 번만 가능합니다. (중복 결제 방지)

**orderName**은 주문 내용을 나타내는 문자열입니다. 특정한 형식이 있지는 않지만, 결제 처리에 필요하므로 필수적으로 전달해 주셔야 합니다.

Expand All @@ -123,41 +63,42 @@ const response = await PortOne.requestPayment({
결제가 성공한 경우 paymentId를 서버에 전달하여 서버측 결제 완료 처리를 하도록 합니다. (가상 계좌 결제의 경우 결제가 아직 완료되지 않은 상태일 수 있습니다.)

```javascript
const response = await PortOne.requestPayment({
/* 파라미터 생략 */
});

if (response.code != null) {
// 오류 발생
return alert(response.message);
}
async function requestPayment() {
const response = await PortOne.requestPayment({
/* 파라미터 생략 */
});

if (response.code != null) {
// 오류 발생
return alert(response.message);
}

// /payment/complete 엔드포인트를 구현해야 합니다. 다음 목차에서 설명합니다.
const notified = await fetch(
`${SERVER_BASE_URL}/payment/complete`,
{
// /payment/complete 엔드포인트를 구현해야 합니다. 다음 목차에서 설명합니다.
const notified = await fetch(`${SERVER_BASE_URL}/payment/complete`, {
method: "POST",
headers: { "Content-Type": "application/json" },
// paymentId와 주문 정보를 서버에 전달합니다
body: JSON.stringify({
paymentId: paymentId,
// 주문 정보...
}),
}
);
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 return 안 하면 아래 fetch 실행되는 모양이 될 것 같은데.... 아마 파싱 에러 때문이었을 것 같은데 function requestPayment(){...}로 코드 감싸면 어떨까요?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그렇네요 ㅎㅎ 반영했습니다

```

결과값에 들어 있는 필드는 다음과 같습니다.

| 필드명 | 설명 | 비고 |
| --------- | ---------- | ------- |
| paymentId | 결제 건 ID | 공통 |
| code | 오류 코드 | 실패 시 |
| message | 오류 문구 | 실패 시 |
|필드명 |설명 |비고 |
|---------|----------|-------|
|paymentId|결제 건 ID|공통 |
|code |오류 코드 |실패 시|
|message |오류 문구 |실패 시|

### 3-1. redirect 방식의 경우

모바일 환경에서의 결제는 대부분 redirect 방식으로 이루어집니다. redirect 방식에서는 브라우저가 결제창으로 리다이렉트되었다가, 결제창에서의 작업이 끝나면 지정한 `redirectUrl`로 다시 리다이렉트됩니다. 이 경우에는 함수 호출 결과를 이용할 수 없고, 결제 성공 여부 등은 [쿼리 문자열](https://en.wikipedia.org/wiki/Query_string)로 전달받게 됩니다.
모바일 환경에서의 결제는 대부분 redirect 방식으로 이루어집니다. redirect 방식에서는 브라우저가 결제창으로 리다이렉트되었다가, 결제창에서의 작업이 끝나면
지정한 `redirectUrl`로 다시 리다이렉트됩니다. 이 경우에는 함수 호출 결과를 이용할 수 없고,
결제 성공 여부 등은 [쿼리 문자열](https://en.wikipedia.org/wiki/Query_string)로 전달받게 됩니다.

```javascript
PortOne.requestPayment({
Expand All @@ -168,27 +109,31 @@ PortOne.requestPayment({

쿼리 문자열로 전달되는 내용은 다음과 같습니다.

| 키 | 설명 | 비고 |
| ---------- | ---------- | ------- |
| payment_id | 결제 건 ID | 공통 |
| code | 오류 코드 | 실패 시 |
| message | 오류 문구 | 실패 시 |
|키 |설명 |비고 |
|-----------|----------|-------|
|payment\_id|결제 건 ID|공통 |
|code |오류 코드 |실패 시|
|message |오류 문구 |실패 시|

예를 들어 paymentId가 `payment-39ecfa97`, redirectUrl이 `https://example.com/payment-redirect`인 경우, 결제 성공 시에 `https://example.com/payment-redirect?payment_id=payment-39ecfa97`로 리다이렉트됩니다.
예를 들어 paymentId가 `payment-39ecfa97`, redirectUrl이 `https://example.com/payment-redirect`인 경우,
결제 성공 시에 `https://example.com/payment-redirect?payment_id=payment-39ecfa97`로 리다이렉트됩니다.

## 4. 결제 완료 처리 (서버)

paymentId를 서버에 전달하면, 서버는 포트원의 [결제 조회 API](/api/rest-v2/payment#get%20%2Fpayments%2F%7BpaymentId%7D)를 호출하여 해당 결제 건의 상태를 확인하고 결제 완료 처리를 하여야 합니다.
paymentId를 서버에 전달하면, 서버는 포트원의 [결제 조회 API](/api/rest-v2/payment#get%20%2Fpayments%2F%7BpaymentId%7D)를
호출하여 해당 결제 건의 상태를 확인하고 결제 완료 처리를 하여야 합니다.

<Hint style="info">
**결제 검증 필수**

인증 결제의 흐름상 결제 금액 등 정보가 고객의 브라우저 측에서 처리되므로, 의도한 결제 내용이 맞는지 꼭 확인하여야 위변조를 막을 수 있습니다.
**결제 검증 필수**

인증 결제의 흐름상 결제 금액 등 정보가 고객의 브라우저 측에서 처리되므로, 의도한 결제 내용이 맞는지 꼭 확인하여야 위변조를 막을 수 있습니다.
</Hint>

예시로, 위에서 사용했던 `/payment/complete` 엔드포인트를 다음과 같이 구현할 수 있습니다.

[PORTONE\_API\_SECRET](/docs/ko/ready/readme?v=v2#4-2-v2-api-secret-%EB%B0%9C%EA%B8%89%ED%95%98%EA%B8%B0)
은 V2 전용 시크릿으로, 포트원 콘솔 내 결제연동 탭에서 발급받을 수 있습니다.

```javascript title="Express"
app.use(bodyParser.json());

Expand All @@ -202,10 +147,11 @@ app.post("/payment/complete", async (req, res) => {
const paymentResponse = await fetch(
`https://api.portone.io/payments/${encodeURIComponent(paymentId)}`,
{
headers: { "Authorization": `PortOne ${PORTONE_API_SECRET}` },
headers: { Authorization: `PortOne ${PORTONE_API_SECRET}` },
},
);
if (!paymentResponse.ok) throw new Error(`paymentResponse: ${paymentResponse.statusText}`);
if (!paymentResponse.ok)
throw new Error(`paymentResponse: ${paymentResponse.statusText}`);
const payment = await paymentResponse.json();

// 2. 고객사 내부 주문 데이터의 가격과 실제 지불된 금액을 비교합니다.
Expand All @@ -226,11 +172,9 @@ app.post("/payment/complete", async (req, res) => {
} else {
// 결제 금액이 불일치하여 위/변조 시도가 의심됩니다.
}

} catch (e) {
// 결제 검증에 실패했습니다.
res.status(400).send(e);
}
});

```
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: 빌링키 발급 요청 파라미터
description: 빌링키 발급 요청 파라미터를 확인 할 수 있습니다.
description: 빌링키 발급 요청 파라미터를 확인할 수 있습니다.
---

## 빌링키 발급 요청 파라미터 정의
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: 빌링키 발급 응답 파라미터
description: 빌링키 발급 응답 파라미터를 확인 할 수 있습니다.
description: 빌링키 발급 응답 파라미터를 확인할 수 있습니다.
---

## 빌링키 발급 응답 파라미터 정의
Expand Down
Loading