チェックアウトの連携
シームレスなチェックアウトソリューションを連携し、各国の最適な支払い方法でお客様をサポートしましょう。
自動インテグレーション(AI アシスト)
以下のプロンプトをプロジェクトディレクトリ内の AI コーディングツール(Claude Code、Cursor、Codex など)に貼り付けてください。エージェントが機械可読ドキュメントを取得し、チェックアウト、Webhook、そして紛争やチャージバックの際に提供の証拠となる配送記録の登録まで、テストモードのインテグレーションを最後まで実装します。変更内容をレビューし、API キーを設定すれば本番公開できます。
さらに便利に — Tokenz MCP を接続。 お使いの AI ツールが MCP に対応している場合は、当社の MCP サーバーを追加すると、エージェントがドキュメントの検索、テスト用チェックアウトセッションの作成、Webhook 署名の検証を直接実行できます。ガイド付きで自己検証しながら統合できます。下記のプロンプトは、MCP の有無どちらでも動作します。
claude mcp add --transport http tokenz https://mcp.tokenz.one/mcp --header "Authorization: Bearer secret_test_YOUR_KEY_HERE"
プロンプト: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`, 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-checkout.txt while you wait for my answers. It contains the v2 checkout guides and links to the raw OpenAPI contracts. Fetch the linked Checkout Session, Order, and Webhook JSON specs 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 new integration. If you cannot fetch URLs, ask me to paste the relevant guides and raw contracts.
2. The questions:
- What product(s) should the checkout sell (name, amount, currency)?
- 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 values myself. Remind me that the key 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: treat every entry in `warnings` as a bug and fix it. 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 から API クレデンシャル (公開キーと秘密キー) を取得していることを確認してください。 クレデンシャルは Tokenz Dashboard の開発者向けページでご確認いただけます。
Tokenz チェックアウトの仕組みの詳細については、Tokenz チェックアウト でご確認ください。
連携作業中はテスト API キー(test_ を含むキー、例: secret_test_...)を使用してください。テストキーで作成された Checkout Session はテストモードで動作し、実際の請求は発生しません。本番公開時に本番キーへ切り替えてください。
サーバーのセットアップ
import os
from flask import Flask, request, redirect
from flask_cors import CORS
import requests
# ご自身のキーに置き換えてください
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 の価格から計算されます。一部の例にあるトップレベルの amount フィールドは任意ですが、指定する場合は itemDetails の合計と一致している必要があり、一致しない場合はリクエストが拒否されます。
税について。 このクイックスタート(およびサンプルペイロード)は、Tokenz アカウントのデフォルトである Merchant of Record(MoR)モデルを前提としています。MoR では Tokenz が税を自動的に計算・徴収するため、各商品の taxCategory を設定するだけで済みます。アカウントが特別に Payment Gateway モデルに設定されている場合は、すべての Checkout Session にトップレベルの tax オブジェクト(最小通貨単位、例:"tax": { "amount": 0, "currency": "USD" })を追加で含める必要があり、含めない場合は order.tax-required エラーで拒否されます。お使いのアカウントのモデルが不明な場合は、Tokenz の担当者にご確認ください。
成功 URL とキャンセル URL の提供
成功ページとキャンセルページの URL を指定します。Tokenz がお客様をリダイレクトできるようこれらのページは公開されている必要があります。 また、成功とキャンセルの両方のステータスを同じ URL で処理することも可能です。
[オプション] 利用可能な支払い方法の定義
このチェックアウトでお客様に提供する支払い方法のリストを指定します。 支払い方法が指定されていない場合、または空のリストが送信された場合、すべての利用可能な支払い方法が表示されます。
Tokenz チェックアウトにお客様をリダイレクトする
セッションを作成したら、レスポンスで返されるチェックアウトページの 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 に表示する成功ページを作成し、注文確認メッセージや注文の詳細をお客様に表示します。 お客様がチェックアウトを正常に完了すると、このページにリダイレクトされます。
<!DOCTYPE html>
<html>
<head>
<title>ご注文ありがとうございます。</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>
ご利用いただき誠にありがとうございます。ご質問がある場合は、
<a href="mailto:orders@example.com">orders@example.com</a>までご連絡ください。
</p>
</section>
</body>
</html>
処理中の支払いページを追加する
コンビニ決済や銀行振込などの非同期型の支払い方法の場合、数分から数日間支払いが処理中の状態になる場合があります。 pendingUrl にページを追加します。 お客様が非同期型の支払いに関する説明ページを閉じると、このページにリダイレクトされます。
<!DOCTYPE html>
<html>
<head>
<title>ご注文ありがとうございます。</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>
お客様のお支払いは現在処理中です。処理が完了次第お知らせいたします。
If you have any questions, please email
<a href="mailto:orders@example.com">orders@example.com</a>.
</p>
</section>
</body>
</html>
キャンセルページを追加する
cancelUrl にページを追加します。 お客様がチェックアウトで戻るボタンをクリックすると、このページにリダイレクトされます。
<!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>
チェックアウトボタンを追加する
最後にお客様の注文のプレビューを表示するページを追加します。 お客様が注文の確認や修正をできるようにします。チェックアウトページに行くと、注文は確定し、新しい Checkout Session を作成しない限り注文を修正することはできません。
注文プレビューページにボタンを追加します。 お客様がこのボタンをクリックすると、Tokenzがホストする支払いページにリダイレクトされます。
<!DOCTYPE html>
<html>
<head>
<title>クールな新商品を購入するt</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">チェックアウト</button>
</form>
</section>
</body>
</html>