帳單 (Billing)
停止,前置條件。 在
<PricingTable />、<CheckoutButton />、has({ plan })或has({ feature })等功能運作之前,必須先啟用帳單。有兩種啟用方式:(1) Dashboard → Billing → Settings,或 (2)clerk enable billing(請參閱下方的「Agent-first:程式化帳單設定」)。啟用後會自動建立預設的free_user/free_org方案。開發實例可使用共享的 Clerk 開發閘道(無需 Stripe 帳戶);正式環境則需要 Stripe 帳戶來處理付款。注意:帳單 API 仍為實驗性功能。請鎖定您的
@clerk/nextjs和clerk-js套件版本。支援的版本表請參閱clerk技能。
快速開始
-
啟用帳單,透過 Dashboard → Billing → Settings 或
clerk enable billing(參閱 Agent-first 章節)。跳過此步驟會在開發環境拋出cannot_render_billing_disabled錯誤,並在正式環境中渲染空白內容。 -
在對應的分頁建立方案,前往 Dashboard → Billing → Plans。有兩個分頁,Slug 作用域限定在各自分頁內,建立後無法移動:
- User Plans →
<PricingTable />(預設for="user") - Organization Plans →
<PricingTable for="organization" />
將方案建立在錯誤的分頁是
<PricingTable />渲染空白的最常見原因。方案存在於 Clerk 中;不會同步到 Stripe。 - User Plans →
-
在方案內新增功能,在 Dashboard → Billing → Plans 中開啟該方案,使用其 Features 區段。功能的作用域限定在方案內,並非全域。同一個 slug 可以附加到多個方案;
has({ feature: 'export' })會比對啟用方案是否包含該 slug。 -
渲染
<PricingTable />(B2B 時傳入for="organization")。 -
使用
auth()中的has({ plan })或has({ feature })進行存取閘控。 -
處理帳單 Webhook 以管理訂閱生命週期。
Dashboard 捷徑
| 動作 | 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 |
| 編輯功能 | 方案 → 點選方案 → Features 區段(無直接 URL) |
Agent-first:程式化帳單設定
完整的帳單設定(啟用開關、方案、功能、方案-功能關聯)皆可透過 PLAPI 編輯,無需操作 Dashboard。這對於 Agent 大量建立方案、跨實例複製設定、或進行帳單結構的版本控制非常有用。
前置條件:專案已連結至 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 模式(個人使用者訂閱、Membership optional 前置條件) | references/b2c-patterns.md |
| B2B 模式(組織訂閱、席位限制方案、管理者閘控的帳單 UI) | references/b2b-patterns.md |
| Webhook 事件目錄、payload 結構、處理範本 | 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 Dashboard 中設定的方案。選擇一個方案會開啟 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 Dashboard → Billing → Features 中設定並指派給方案的。當要閘控細粒度能力時,請使用 has({ feature }) 而非 has({ plan }),檢查功能本身,而非方案。
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() hook:
'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: slug 前綴(例如 has({ plan: 'org:team' }))以保持閘控不含糊。使用 <PricingTable for="organization" /> 渲染 B2B 定價頁面,並使用 <OrganizationProfile /> 作為組織帳戶帳單 UI。
請參閱 references/b2b-patterns.md 了解分層方案命名、席位限制不變量、僅限管理員的帳單以及 Webhook 處理器。
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: 'premium 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訂閱項目逾期 invoice.payment_failedsubscriptionItem.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 的。
Payload 結構。 Clerk 帳單 Webhook payload 是巢狀的。訂閱實體位於
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
…