Checkout 연동하기
테스트 결제를 만들고 아이템 지급 흐름에 연결하세요.
연동 방법 선택
전체 연동에는 Checkout Session 생성, 결제 웹훅 서명 검증, 중복 없는 아이템 지급, 지급 기록 등록이 포함됩니다.
AI를 이용한 자동 연동
프로젝트 디렉터리에서 AI 코딩 도구(Claude Code, Cursor, Codex 등)에 아래 프롬프트를 복사하세요. 에이전트가 기계 판독용 문서를 읽고 Checkout, 웹훅, 분쟁·차지백 시 지급 증빙이 되는 아이템 지급 기록을 포함한 테스트 모드 연동을 구현합니다. 변경 사항을 검토하고 API 키를 추가한 후 운영에 적용하세요.
프롬프트: 테스트 모드에서 Tokenz Checkout 전체 연동
You are integrating Tokenz — a Merchant of Record (MoR) checkout — into this project, end to end, in TEST MODE.
If a Tokenz MCP server is connected to you (you will see tools like `search_docs`, `get_openapi`, `create_test_checkout_session`, and `verify_webhook_signature`), use it throughout the steps below: prefer `search_docs`/`get_doc` over fetching raw doc URLs, take test cards from `list_test_cards`, run `check_auth` once the key is in place, test the webhook handler locally with `sign_test_webhook_payload` before any real purchase (pass a realistic `order.succeeded` body from the v2 webhooks docs as `payload`, because the tool's built-in sample is a v3 event, and use a throwaway Base64 secret until I register the endpoint), and use `create_test_checkout_session` + `get_order` to prove the integration works against the real API. Everything below still applies either way.
Before writing any code:
1. Detect my project's stack and find the code that grants purchased items to a customer (fulfillment). Then ask me the questions below immediately, and fetch https://docs.tokenz.one/llms-v2.txt while you wait for my answers. Download it with your shell (for example with `curl -fsSL`) to a temporary file outside this project and read the whole file, because web-fetch tools often read only the start of a long page and summarize the rest. It contains the v2 guides and links to the raw OpenAPI contracts. Download the linked Checkout Session, Order, and Webhook JSON specs the same way before implementing their requests and payloads; those raw specs are authoritative for fields, constraints, errors, and response formats. Use https://docs.tokenz.one/llms.txt to find any additional guides you need. Stay on v2 for this integration. If you cannot fetch URLs, ask me to paste the relevant guides and raw contracts.
2. The questions:
- What should the checkout sell? Propose the products (name, amount, currency) from what you find in the code, and ask me to confirm or correct them.
- Which environment file should hold my Tokenz test secret key (secret_test_...) and webhook signing secret (e.g. .env.local)? I will fill in the signing secret myself. For the key: if the Tokenz MCP is connected with a Dashboard sign-in rather than an API key, offer to create it with `create_test_api_key` and the scopes `CheckoutSessionCreate`, `OrderGet`, and `OrderDeliveryRecordCreate`, and write it straight into that file without showing it in chat. Otherwise, or if that tool refuses, I will add the key myself, so remind me that it needs the `CreateCheckoutSession`, `GetOrder`, and `RegisterDeliveryRecord` permissions.
- Confirm the framework/stack and the fulfillment code you found before patching anything. If the project has no fulfillment code yet, ask me how a paid order should be delivered and which ID identifies the customer.
- If this project only runs locally: how should Tokenz reach the webhook endpoint? (Offer to set up a tunnel such as ngrok or cloudflared, or ask me for a deployed HTTPS URL.)
Constraints (non-negotiable):
- Never hardcode, log, or commit secrets — API keys and webhook signing secrets alike; read them from environment variables only.
- Create Checkout Sessions server-side only; never expose the secret key to the browser.
- Define products and prices server-side; never trust amounts sent by the browser. Amounts are in minor units, and every product item needs a taxCategory from the docs' enum.
- Verify webhook signatures (Tokenz-Signature header) over the raw, unparsed request body; do not skip this.
- Fulfill orders from verified webhook events (order.succeeded), never from the customer reaching the success page — redirects prove navigation, webhooks prove payment. Handle webhook retries idempotently, keyed on the event's top-level `id`; the same event can be delivered more than once.
- Register a delivery record with Tokenz for every order you fulfill (POST /v2/order/{orderId}/delivery). This is a required part of the integration, not an extra: the delivery record is the proof of delivery sent to the bank or card issuer when a customer disputes a payment or files a chargeback, and an order without one has no evidence to defend it. Do not skip it, stub it, or offer it to me as optional.
- Build redirect URLs from a configured base URL, not from request headers such as Origin.
- Stay in Tokenz test mode until I explicitly ask to go live.
- Keep changes minimal; do not refactor unrelated code.
- Communicate with me in the language I use with you.
Deliverables — verify each actually works before claiming it is done:
1. A server endpoint that creates a Tokenz Checkout Session and returns its URL.
2. A checkout button/flow that redirects the customer to the hosted checkout.
3. Success, processing, and canceled pages wired to the session's redirect URLs. (Some payment methods settle asynchronously — the processing page is not optional.)
4. A webhook endpoint that receives events, verifies the signature, and updates order state. As soon as the webhook URL is known, tell me so I can register it in the Tokenz Dashboard (remind me: register it in TEST mode; the Dashboard shows the signing secret once, and I will put it into the env file myself — never ask me to paste it in chat) — then keep building while I do that.
5. Delivery registration, for every order the webhook fulfills:
- Order of operations: in the webhook handler, mark the event as processed, grant the items, and store the delivery record (or a job for it) as one transaction or one durable write, and only then acknowledge with 2xx. A retried webhook must find either nothing done or everything done, never granted items with no delivery record; if the project's storage cannot make that atomic, have the handler re-check fulfilled orders that lack a record and create it. Call the Delivery Registration API from outside the webhook response path (a queued job or background task), so a slow or unreachable API never delays the acknowledgement.
- Payload: send the full payload the docs recommend — `status`, `progress`, `at`, `user`, `items` with `deliveredQuantity` (plus the in-app balance before and after, when the item is a currency), `cartContext`, `deliveryContext`, and `deliveryInfo` — built from the real fulfillment data, never from placeholders. `cartContext` and `deliveryContext` describe the customer's device: capture the IP address, user agent, and device ID from the customer's own requests (when the Checkout Session is created, and at delivery if the customer is present), and store them with the order. Never fill them from the webhook request, which comes from Tokenz's servers; leave out a field you do not have.
- One record per delivery: register a failed delivery too (`status: failed`), send one record per delivery when an order is delivered in parts, and never let a retried webhook create a second record for the same delivery.
- Response: a 201 Created response has created the record even when it carries `warnings`, so never re-send that record. Treat every warning as a bug and fix the payload for later deliveries. A failed call must never repeat or undo the fulfillment.
- Retries: each call creates a new record and there is no idempotency key, so keep every record Tokenz has not accepted in the project's own storage, in one of three states. Retryable (Tokenz answered 5xx): re-send automatically, including after a restart. Blocked (Tokenz answered 4xx): fix the cause before re-sending — 403 Forbidden means the key lacks the `RegisterDeliveryRecord` permission (on by default for secret keys), so tell me to use a secret key that has it; 401 Unauthorized means the key is missing, invalid, or revoked, so tell me to fix the key; re-send either once the key changes. Any other 4xx means the request is wrong, so fix it first. Needs review (no answer: timeout or dropped connection): never resend automatically; flag it for me to check.
6. A completed end-to-end test purchase using the test cards from the docs, with the webhook received and verified, the items granted once, and the delivery record accepted (201 Created, no warnings). If you have browser-automation tools, perform the test purchase yourself; otherwise give me exact steps.
7. A short go-live checklist for me: everything that must change to leave test mode (a live secret key with the permissions this integration uses, including `RegisterDeliveryRecord`; live webhook registration with its new signing secret; a stable public webhook URL; real tax/fulfillment handling), plus anything you stubbed.
If any step is blocked (missing key, docs ambiguity, unsupported stack), stop and ask me instead of guessing.
Tokenz MCP를 연결하면 더 편리합니다. AI 코딩 도구가 MCP를 지원하면 서버를 추가하세요. 에이전트가 문서 검색, 테스트 Checkout Session 생성, 웹훅 서명 검증을 직접 수행할 수 있습니다. 위 프롬프트는 MCP 연결 여부와 관계없이 사용할 수 있습니다.
로그인 (API 키를 붙여 넣을 필요 없음)
https://mcp.tokenz.one/mcp를 사용합니다. 클라이언트는 OAuth 2.1(authorization code와 PKCE)로 로그인하게 합니다. Merchant Dashboard 계정으로 로그인한 뒤, 동의 화면에서 라이브 또는 테스트 모드를 선택합니다. API 키를 붙여 넣을 필요가 없습니다. 연결은 dashboard:read와 test_api_keys:create 스코프를 요청합니다. 웹숍 편집과 게시를 위한 선택 권한인 webshop:write와 webshop:publish도 요청할 수 있으며, 동의 화면에서 이 권한을 줄일 수 있습니다. 로그인한 연결에서는 테스트 도구가 테스트 키를 자동으로 발급합니다. 이 서버에는 문서, 웹훅, 테스트 동작, Merchant Dashboard 데이터, 웹숍 설정까지 모든 도구가 있습니다. 로그인도 키도 없는 요청에는 로그인을 요구하는 401 응답이 반환됩니다.
claude mcp add --transport http tokenz https://mcp.tokenz.one/mcp
이전에 https://mcp.tokenz.one/merchant로 연결했다면, 이 기존 URL은 같은 서버이며 계속 동작합니다. 새로 설정할 때는 /mcp를 사용하세요. 로그인은 로그인한 URL에 묶이므로, 연결을 /merchant에서 /mcp로 옮기면 다시 로그인해야 합니다.
선택 사항인 테스트 키
로그인 대신 https://mcp.tokenz.one/mcp에 테스트 키를 Authorization: Bearer secret_test_... 형식으로 보낼 수도 있습니다. 테스트 키로는 문서와 웹훅 도구, check_auth, 테스트 동작 도구를 사용할 수 있습니다. 테스트 동작 도구는 create_test_checkout_session, get_checkout_session, get_order, cancel_test_order, create_test_refund, get_refund입니다. Merchant Dashboard와 웹숍 도구에는 로그인이 필요합니다. 라이브 키는 거부됩니다.
일부 클라이언트는 키 헤더를 설정해도, 서버가 로그인을 제공하면 로그인을 시작합니다. Cursor는 2026년 10월에 이렇게 동작했습니다. 사용 중인 클라이언트가 그렇다면 로그인하세요. 문서만 필요하면 아래의 문서 전용 서버를 사용할 수도 있습니다.
claude mcp add --transport http tokenz https://mcp.tokenz.one/mcp --header "Authorization: Bearer secret_test_YOUR_KEY_HERE"
문서 전용 (로그인 불필요)
https://docs.mcp.tokenz.one/mcp는 로그인과 API 키가 필요 없으며, OAuth를 제공하지 않습니다. 문서와 웹훅 도구만 있습니다. search_docs, get_doc, list_docs, get_openapi, list_test_cards, verify_webhook_signature, sign_test_webhook_payload입니다. check_auth, 테스트 동작, Merchant Dashboard 도구는 없습니다.
claude mcp add --transport http tokenz-docs https://docs.mcp.tokenz.one/mcp
다른 클라이언트에서는 위 로그인 탭의 설정을 복사한 뒤, 서버 이름을 tokenz-docs 등으로 정하고 URL을 https://docs.mcp.tokenz.one/mcp로 바꾸세요. 로그인 단계는 필요 없습니다.
사전 준비
대시보드의 설정 > 개발자 > API 키에서 서버용 비밀 키를 생성하세요. 새 비밀 키에는 이 가이드에서 사용하는 네 가지 권한(CreateCheckoutSession, GetCheckoutSession, GetOrder, RegisterDeliveryRecord)이 기본으로 부여됩니다. API 키를 참고하세요.
Tokenz Checkout의 동작 방식은 Checkout을 참고하세요.
연동 중에는 secret_test_로 시작하는 테스트 비밀 키를 사용하세요. 이 키로 생성한 Checkout Session은 테스트 모드로 동작하며 실제 결제가 발생하지 않습니다. 실제 결제를 받으려면 라이브 비밀 키로 전환하세요.
서버 설정
import os
from flask import Flask, request, redirect
from flask_cors import CORS
import requests
# Replace the keys with yours
SECRET_KEY = os.environ.get("SECRET_KEY", "secret_test_YOUR_KEY_HERE")
app = Flask(__name__, static_url_path="")
CORS(app)
root = "../client/build"
@app.route("/", methods=["GET"])
def index():
return redirect("http://localhost:3080")
Checkout Session 생성
서버에 Checkout Session을 생성하는 엔드포인트를 추가하세요. Checkout Session은 상품 항목, 주문 금액, 통화, 사용 가능한 결제 수단 등 Tokenz 호스팅 결제 페이지에 표시할 내용을 제어합니다.
상품 항목 정의
가격과 재고 등 민감한 상품 정보는 고객이 클라이언트에서 조작할 수 없도록 항상 서버에 보관하세요. 모든 Checkout Session에 itemDetails가 필요합니다.
주문 합계는 항상 itemDetails의 가격으로 계산됩니다. 일부 예제의 최상위 amount는 선택 사항이지만 지정한다면 itemDetails 합계와 같아야 합니다. 다르면 요청이 거부됩니다.
세금. 이 빠른 시작 가이드와 예제 페이로드는 Tokenz 계정의 기본 설정인 Merchant of Record(MoR) 모델을 설명합니다. 이 모델에서는 Tokenz가 세금을 자동으로 계산하고 징수하므로 각 항목의 taxCategory만 지정하면 됩니다. 계정이 별도로 Payment Gateway 모델로 설정되어 있다면 모든 Checkout Session에 최소 단위의 최상위 tax 객체도 포함해야 합니다(예: "tax": { "amount": 0, "currency": "USD" }). 이를 생략하면 order.tax-required 오류로 요청이 거부됩니다. 계정에 적용된 모델이 확실하지 않으면 Tokenz 담당자에게 문의하세요.
성공, 처리 중, 취소 URL 지정
모든 Checkout Session에는 외부에서 접근할 수 있는 리디렉션 URL 세 개가 필요합니다. Tokenz는 결제를 처리하는 동안 고객을 pendingUrl로 이동시킵니다. 결제에 실패하거나 결제가 차단되거나 고객이 결제 절차를 취소하면 cancelUrl로 이동시킵니다. 그 외에는 successUrl로 이동시킵니다.
세 URL 모두 같은 페이지를 가리킬 수 있습니다. 서버에서 조회한 주문 상태에 따라 결과를 표시하세요. 리디렉션 URL만으로는 주문 상태를 확인할 수 없습니다. 고객이 모바일 앱에서 결제를 시작했다면 세 URL 모두 고객을 앱으로 돌려보내는 데 사용할 수 있습니다. 앱으로 돌아가기를 참고하세요.
[선택] 사용 가능한 결제 수단 지정
이번 결제에서 고객에게 제공할 결제 수단 목록을 지정하세요. 생략하거나 빈 목록을 전송하면 사용 가능한 모든 결제 수단이 표시됩니다.
고객을 Tokenz Checkout으로 이동
세션을 생성한 후 응답에 반환된 결제 페이지 URL로 고객을 이동시키세요.
@app.route("/create-tokenz-checkout", methods=['POST'])
def create_tokenz_checkout():
CALLBACK_URL_PREFIX = request.headers['referer']
headers = {"Authorization": f'Bearer {SECRET_KEY}'}
print(headers)
payload = {
"amount": {
"currency": "JPY",
"amount": 5200
},
"itemDetails": [
{
"product": {
"label": "ひとにぎりのエメラルド",
"description": "80+8",
"images": [
"https://images.ctfassets.net/z82qbo7cv7ia/1dWPbk5Qx2M1Qikj6Knyuc/e37b2c26829c0d30793a348ae3adb3b0/fake-pass.webp"
],
"quantity": 3,
"price": {
"currency": "JPY",
"amount": 1200
},
"taxCategory": "DIGITAL_GOODS_AND_SERVICES"
}
},
{
"product": {
"label": "エメラルドの荷車",
"description": "100+10",
"images": [],
"quantity": 1,
"price": {
"currency": "JPY",
"amount": 1600
},
"taxCategory": "DIGITAL_GOODS_AND_SERVICES"
}
}
],
"customerInfo": {},
"successUrl": "http://localhost:9000/success",
"pendingUrl": "http://localhost:9000/pending",
"cancelUrl": "http://localhost:9000/cancel"
}
res = requests.post(
"https://api.tokenz.one/v2/checkoutsession", json=payload, headers=headers
)
session = res.json()
return redirect(session["url"], 303)
결제 화면 구성
성공 페이지 추가
Checkout Session의 successUrl에 지정한 URL에 성공 페이지를 만들어 주문 확인 메시지나 주문 정보를 표시하세요. 고객이 결제를 완료하면 Tokenz가 이 페이지로 이동시킵니다.
<!DOCTYPE html>
<html>
<head>
<title>Thanks for your order!</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>
We appreciate your business! If you have any questions, please email
<a href="mailto:orders@example.com">orders@example.com</a>.
</p>
</section>
</body>
</html>
결제 처리 중 페이지 추가
편의점 결제나 계좌이체 같은 비동기 결제 수단은 결제 처리 중 상태가 몇 분에서 며칠까지 이어질 수 있습니다. pendingUrl에 해당하는 페이지를 추가하세요. 고객이 비동기 결제 안내 페이지를 닫으면 Tokenz가 이 페이지로 이동시킵니다.
<!DOCTYPE html>
<html>
<head>
<title>Thanks for your order!</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>
Your payment is being processed! We will let you know as soon as it is completed.
If you have any questions, please email
<a href="mailto:orders@example.com">orders@example.com</a>.
</p>
</section>
</body>
</html>
취소 페이지 추가
cancelUrl에 해당하는 페이지도 추가하세요. 고객이 결제 중 뒤로 가기 버튼을 클릭하면 Tokenz가 이 페이지로 이동시킵니다.
<!DOCTYPE html>
<html>
<head>
<title>Checkout canceled</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>Forgot to add something to your cart? Shop around then come back to pay!</p>
</section>
</body>
</html>
앱으로 돌아가기
고객이 모바일 앱에서 결제를 시작하는 경우, 결제 후 고객을 앱으로 돌려보낼 수 있습니다. successUrl, pendingUrl, cancelUrl에는 웹 페이지 URL뿐 아니라 앱 링크도 지정할 수 있습니다.
- 유니버설 링크(iOS) 또는 App Links(Android): 앱에서 열리도록 설정한
https://URL(예:https://example.com/app/purchase-complete) - 앱이 등록한 커스텀 URL 스킴(예:
myapp://purchase-complete)
각 URL은 scheme://... 형식의 절대 URL이어야 하며 300자를 넘을 수 없습니다. javascript:, data:, vbscript:, file:, blob:, about:를 사용하는 URL은 거부됩니다.
Tokenz Checkout은 결과 페이지에서 자동으로 이동하지 않습니다. 결제가 끝나면 고객에게 결과 페이지가 표시되고, 이 페이지의 버튼을 누르면 successUrl이 열립니다. 결제가 처리 중이면 pendingUrl, 결제에 실패하면 cancelUrl이 열립니다. 결제 중 뒤로 가기 버튼을 누르면 cancelUrl이 열립니다.
링크로 앱이 열리는지는 앱이 링크를 등록한 방식과 결제 화면을 표시하는 브라우저에 따라 달라집니다. 가장 확실한 방법은 successUrl을 직접 호스팅하는 https:// 페이지로 지정하고, 그 페이지에 앱을 여는 버튼을 두는 것입니다.
<!DOCTYPE html>
<html>
<head>
<title>Thanks for your order!</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>Your purchase is complete.</p>
<a href="myapp://purchase-complete">Return to the app</a>
</section>
</body>
</html>
앱이 열렸다고 해서 고객이 결제한 것은 아닙니다. 다른 리디렉션과 마찬가지로 order.succeeded 웹훅을 기준으로 아이템을 지급하세요.
결제 버튼 추가
마지막으로 고객이 주문을 미리 볼 수 있는 페이지를 추가하세요. 이 페이지에서 주문을 확인하거나 수정할 수 있게 하세요. Checkout 페이지에 진입하면 주문이 확정되므로, 수정하려면 새 Checkout Session을 생성해야 합니다.
주문 미리 보기 페이지에 버튼을 추가하세요. 고객이 이 버튼을 클릭하면 Tokenz 호스팅 결제 페이지로 이동합니다.
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<div class="product">
<img src="https://images.ctfassets.net/z82qbo7cv7ia/1dWPbk5Qx2M1Qikj6Knyuc/e37b2c26829c0d30793a348ae3adb3b0/fake-pass.webp" alt="ひとにぎりのエメラルド" />
<div class="description">
<h3>ひとにぎりのエメラルド</h3>
<h5>1,200円</h5>
</div>
</div>
<form action="/create-tokenz-checkout" method="POST">
<button type="submit" id="checkout-button">Checkout</button>
</form>
</section>
</body>
</html>
아이템 지급 및 지급 기록 등록
- 웹훅 엔드포인트에서
order.succeeded이벤트의 서명을 검증한 후 처리하세요. - 이벤트의 최상위
id를 확인해 이미 처리한 이벤트는 건너뛰세요. 아이템은 한 번만 지급하세요. 주문에playerId가 있으면 해당 플레이어에게 지급하세요. 재시도와 멱등성을 참고하세요. - 가맹점 계약 제10.8조에 따라 지급 후 24시간 이내에 아이템 지급 기록 등록 API로 지급 기록을 등록하세요.
RegisterDeliveryRecord권한이 있는 비밀 키로POST /v2/order/{orderId}/delivery를 호출하세요.
리디렉션을 아이템 지급의 근거로 삼지 마세요.