課金(Billing)
重要:前提条件。
<PricingTable />、<CheckoutButton />、has({ plan })、has({ feature })を使用する前に、課金を有効にする必要があります。有効化方法は2通り:(1) ダッシュボード → 課金 → 設定、または (2)clerk enable billing(下記「エージェント主導:プログラム的な課金設定」を参照)。有効化すると、デフォルトでfree_user/free_orgプランが自動生成されます。開発インスタンスでは共有のClerk開発ゲートウェイを使用可能(Stripeアカウント不要)。本番環境では支払い処理にStripeアカウントが必要です。注釈:課金APIはまだ実験的です。
@clerk/nextjsとclerk-jsのパッケージバージョンを固定してください。対応バージョン一覧はclerkスキルを参照。
クイックスタート
-
課金を有効化:ダッシュボード → 課金 → 設定 または
clerk enable billing(エージェント主導セクション参照)。スキップすると開発環境ではcannot_render_billing_disabledエラー、本番環境では空表示になります。 -
対応タブでプランを作成:ダッシュボード → 課金 → プラン。2つのタブがあり、スラッグはタブごとにスコープされ、作成後の移動は不可。
- ユーザープラン →
<PricingTable />(デフォルトfor="user") - 組織プラン →
<PricingTable for="organization" />
間違ったタブに作成するのが、
<PricingTable />が空になる最も多い原因です。プランはClerk内で管理され、Stripeとは同期しません。 - ユーザープラン →
-
プラン内に機能を追加:ダッシュボード → 課金 → プランでプランを開き、機能セクションを使用。機能はプランごとにスコープされ、グローバルではありません。同じスラッグを複数のプランに付与可能;
has({ feature: 'export' })はアクティブなプランにそのスラッグが含まれている場合に一致します。 -
<PricingTable />をレンダリング(B2Bの場合はfor="organization"を渡す)。 -
auth()を使ってhas({ plan })またはhas({ feature })でアクセスを制御。 -
サブスクリプションライフサイクル用の課金Webhookを処理。
ダッシュボードショートカット
| アクション | URL |
|---|---|
| 課金を有効化 | https://dashboard.clerk.com/last-active?path=billing/settings |
| プランを作成・編集 | https://dashboard.clerk.com/last-active?path=billing/plans |
| メンバーシップモード(B2C + B2B共存) | https://dashboard.clerk.com/last-active?path=organizations-settings |
| 機能を編集 | プラン → プランをクリック → 機能セクション(直接URLなし) |
エージェント主導:プログラム的な課金設定
課金設定全体(有効化トグル、プラン、機能、プラン-機能の紐付け)は、ダッシュボードを使わずにPLAPI経由で編集可能。エージェントがプランを初期設定したり、設定をインスタンス間で複製したり、課金構造をバージョン管理するのに便利です。
前提条件:プロジェクトがClerkアプリにリンクされていること(clerk auth login + clerk link、clerk-setup を参照)。
CLIで課金を有効化
clerk enable billing # 両方のターゲット(デフォルト、free_user + free_org プランを自動生成)
clerk enable billing --for org # 組織のみ
clerk enable billing --for user # ユーザーのみ
現在の課金設定を取得
clerk config pull --keys billing > billing.json
これにより、リンクされたインスタンスの現在の課金設定(トグル + プラン + 機能)が billing.json に書き込まれます。
編集して適用
billing.json を編集してプランや機能を追加・削除し、差分をプレビューして適用:
clerk config patch --file billing.json --dry-run
clerk config patch --file billing.json
--instance prod を渡すと、開発インスタンスではなく本番インスタンスをターゲットにします。
生のPATCH(完全制御)
設定ファイルを使わずにワンショットでプラン・機能を更新:
clerk api --platform PATCH /v1/platform/applications/<app_id>/instances/<ins_id>/config \
-d '{"billing":{"plans":[{"slug":"pro","name":"Pro","amount":2000,"currency":"usd","payer_type":"user","is_recurring":true}],"features":[{"slug":"export","name":"Export"}]}}'
注意事項
- これは課金設定(トグル + プラン + 機能カタログ)を扱います。サブスクリプションライフサイクル(ユーザーがプランを選択、チェックアウト、更新、キャンセル)は引き続き
<PricingTable />+ 課金Webhookを通じて行われます。ライフサイクルイベントについてはclerk-webhooksスキルを参照してください。 - トップレベルの
featuresマップ操作とプラン-機能の紐付け(同期)は、PLAPI課金設定ハンドラーで完全にサポートされています。
何が必要ですか?
| タスク | 参照先 |
|---|---|
<PricingTable /> のprops、<CheckoutButton />、<Show> の課金パターン | references/billing-components.md |
| B2Cパターン(個人ユーザーサブスクリプション、「メンバーシップはオプション」前提条件) | references/b2c-patterns.md |
| B2Bパターン(組織サブスクリプション、シート制限プラン、管理者制御の課金UI) | references/b2b-patterns.md |
| Webhookイベントカタログ、ペイロード形式、ハンドラーテンプレート | references/billing-webhooks.md |
参照
| 参照 | 説明 |
|---|---|
references/billing-components.md | <PricingTable /> とサブスクリプションUI |
references/b2c-patterns.md | B2Cサブスクリプション課金パターン |
references/b2b-patterns.md | B2B課金(組織サブスクリプションとシート制限プラン) |
references/billing-webhooks.md | サブスクリプションライフサイクルイベント処理 |
ドキュメント
機能 vs プラン:どちらを使うべきか
特定の機能を制限する場合は has({ feature: 'slug' }) を使用:エクスポート、分析、APIアクセス、監査ログなど。
ティア(階層)を制限する場合は has({ plan: 'slug' }) を使用:プロダッシュボードの表示、組織サブスクリプションレベルの確認、フリーユーザーのリダイレクトなど。
| シナリオ | 正しいチェック |
|---|---|
| 「CSVエクスポート」ボタンを制限 | has({ feature: 'export' }) |
| 「分析」セクションを制限 | has({ feature: 'analytics' }) |
| /dashboard/pro 全体を制限 | has({ plan: 'pro' }) |
| 組織がチームサブスクリプションを持っているか確認 | has({ plan: 'org:team' }) |
| SSO設定を制限 | has({ feature: 'sso' }) |
ユーザーが「エクスポート機能を制限」や「分析を制限」と言った場合は、常に has({ feature }) を使用してください。has({ plan }) は、特定の機能ではなくプランティアそのものを制限する場合にのみ使用します。
主要パターン
1. 価格表をレンダリング
単一のコンポーネントで利用可能なプランをユーザーに表示:
import { PricingTable } from '@clerk/nextjs'
export default function PricingPage() {
return (
<main>
<h1>プランを選択</h1>
<PricingTable />
</main>
)
}
<PricingTable /> は、Clerkダッシュボードで設定されたすべてのプランを自動的にレンダリングします。プランを選択すると、Clerkのアプリ内チェックアウトドロワーが開きます。基本的な使用にはpropsは不要です。B2Bの場合は、for="organization" を渡してユーザープランではなく組織レベルのプランをレンダリングします。
2. 機能エンタイトルメントのチェック(サーバーサイド)
個別の機能で制限する場合、特定の機能にはこの方法が推奨されます:
import { auth } from '@clerk/nextjs/server'
export default async function AnalyticsPage() {
const { has } = await auth()
const canViewAnalytics = has({ feature: 'analytics' })
const canExport = has({ feature: 'export' })
return (
<div>
{canViewAnalytics && <AnalyticsChart />}
{canExport && <ExportButton />}
</div>
)
}
機能はClerkダッシュボード → 課金 → 機能で設定し、プランに割り当てます。細かい機能を制限する場合は、has({ plan }) ではなく has({ feature }) を使用してください。プランではなく機能をチェックします。
3. 機能エンタイトルメントのチェック(クライアントサイド)
クライアントサイドの機能制限には useAuth() を使用します。完全なカバレッジのためにサーバーサイドのチェックと組み合わせてください:
'use client'
import { useAuth } from '@clerk/nextjs'
export function FeatureGatedUI() {
const { has, isLoaded } = useAuth()
if (!isLoaded) return null
const canExport = has?.({ feature: 'export' })
const canAnalytics = has?.({ feature: 'analytics' })
return (
<div>
{canAnalytics && <AnalyticsSection />}
{canExport ? <ExportButton /> : <UpgradeToExport />}
</div>
)
}
サーバーコンポーネントでは auth()、クライアントコンポーネントでは useAuth() を使用します。どちらも has({ feature }) と has({ plan }) をサポートしています。
4. サブスクリプションプランのチェック(サーバーサイド)
サブスクリプションプランでアクセスを制限(個別の機能ではなくティアレベルの制限に使用):
import { auth } from '@clerk/nextjs/server'
import { redirect } from 'next/navigation'
export default async function ProDashboard() {
const { has } = await auth()
if (!has({ plan: 'pro' })) {
redirect('/pricing')
}
return <ProFeatures />
}
5. クライアントサイドのプランチェック
クライアントコンポーネントでは useAuth() フックを使用:
'use client'
import { useAuth } from '@clerk/nextjs'
export function UpgradePrompt() {
const { has } = useAuth()
if (has?.({ plan: 'pro' })) {
return null
}
return (
<div>
<p>この機能を利用するにはProにアップグレードしてください</p>
<a href="/pricing">プランを表示</a>
</div>
)
}
6. B2Bシートベースの課金と組織
組織プランにはシート制限(メンバーシップ上限)を設定でき、Clerkが招待時にこれを強制します。組織側のプランチェックでは org: プレフィックスを使用して(例:has({ plan: 'org:team' }))、制限を明確にします。B2B価格ページは <PricingTable for="organization" /> でレンダリングし、組織アカウントの課金UIには <OrganizationProfile /> を使用します。
階層化プラン名、シート制限の不変条件、管理者のみの課金、Webhookハンドラーについては references/b2b-patterns.md を参照してください。
7. サブスクリプションステータスの表示
特定のプランを has({ plan }) でチェックするか、クライアントコンポーネントで完全なサブスクリプション詳細を得るために useSubscription() を使用します。sessionClaims から直接プラン情報を読み取らないでください。これはサポートされていない方法です。
サーバーコンポーネントで、特定のプランをチェック:
import { auth } from '@clerk/nextjs/server'
export default async function AccountPage() {
const { has } = await auth()
const currentPlan = has({ plan: 'pro' })
? 'pro'
: has({ plan: 'starter' })
? 'starter'
: 'free'
return (
<div>
<h2>現在のプラン</h2>
<p>現在 {currentPlan} プランを利用中です</p>
{currentPlan === 'free' && <a href="/pricing">アップグレード</a>}
</div>
)
}
クライアントコンポーネントで、useSubscription() による完全なサブスクリプション詳細:
'use client'
import { useSubscription } from '@clerk/nextjs/experimental'
export function SubscriptionDetails() {
const { data: subscription, isLoading } = useSubscription()
if (isLoading) return null
if (!subscription) return <a href="/pricing">プランを選択</a>
return (
<div>
<p>ステータス: {subscription.status}</p>
{subscription.nextPayment && (
<p>次回支払い日: {subscription.nextPayment.date.toLocaleDateString()}</p>
)}
</div>
)
}
useSubscription()は表示専用です。認可チェック(コンテンツやルートの制限)には、常にhas({ plan })またはhas({ feature })を使用してください。
8. プランによるAPIルートの保護
auth() を使用してAPIルートを制限:
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
export async function GET() {
const { has } = await auth()
if (!has({ plan: 'pro' })) {
return NextResponse.json({ error: 'Proプランが必要です' }, { status: 403 })
}
return NextResponse.json({ data: 'プレミアムデータ' })
}
9. 課金Webhookの処理
Clerkのイベント名はStripeのイベント名と異なります。 Clerkの課金Webhookは、Stripeのアンダースコア形式ではなく、ドット記法とキャメルケースを使用します。
subscription.canceledイベントはありません。キャンセルはアイテムレベルで発生し、subscriptionItem.canceledとして発火します。
意図 Stripeイベント名 Clerkイベント名 サブスクリプション作成 customer.subscription.createdsubscription.createdサブスクリプション更新 customer.subscription.updatedsubscription.updatedサブスクリプション有効 (なし) subscription.activeサブスクリプション期限切れ (なし) subscription.pastDueサブスクリプションアイテムキャンセル customer.subscription.deletedsubscriptionItem.canceledサブスクリプションアイテム期限切れ (なし) subscriptionItem.pastDueサブスクリプションアイテム更新 (なし) subscriptionItem.updatedサブスクリプションアイテム有効 (なし) subscriptionItem.activeサブスクリプションアイテム更新迫る (なし) subscriptionItem.upcomingサブスクリプションアイテム終了 (なし) subscriptionItem.endedサブスクリプションアイテム放棄 (なし) subscriptionItem.abandonedサブスクリプションアイテム期限切れ (なし) subscriptionItem.expiredサブスクリプションアイテム不完全 (なし) subscriptionItem.incomplete無料トライアル終了間近 (なし) subscriptionItem.freeTrialEnding支払い試行作成 (なし) paymentAttempt.created支払い試行更新 (なし) paymentAttempt.updated
evt.typeのチェックでは、常にClerkのイベント名を使用し、Stripeの名前は決して使わないでください。
ペイロード形式。 Clerkの課金Webhookペイロードはネストされています。サブスクライブしているエンティティは
evt.data.payerにあります(フィールド:user_id?、organization_id?)。プラン情報は各アイテムのevt.data.items[i].plan.slugにあります。サブスクリプションIDは単にevt.data.idです。サブスクリプションアイテムにはsubscription_idフィールドの逆参照がないため、subscriptionItem.*ハンドラーではアイテムID(evt.data.id)または支払い者とプランでレコードを特定します。
パターンを固定する最小限のハンドラー(@clerk/nextjs/webhooks からインポート、検証、Clerkイベント名で分岐):
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import { NextRequest } from 'next/server'
import { db } from '@/lib/db'
export async function POST(req: NextRequest) {
let evt
try {
evt = await verifyWebhook(req)
} catch {
return new Response('検証に失敗しました', { status: 400 })
}
if (evt.type === 'subscription.created') {
const { id, payer, items, status } = evt.data
const entityId = p
…
[翻訳のため省略]
参考文献
完全なWebhookイベントカタログ、ペイロード形式、ハンドラーテンプレートについては references/billing-webhooks.md を参照してください。