開發者指南Examples
基本結帳範例
實作最簡單的訂閱結帳流程
基本結帳範例
這個範例展示如何快速整合 Recur SDK(0.4.4+)來建立基本的訂閱結帳流程。
重要:從 SDK 0.4.3 開始,customerEmail 為必填欄位。
完整範例程式碼
// 1. 初始化 SDK
const recur = RecurCheckout.init({
publishableKey: 'pk_test_xxx', // 您的 Publishable Key
});
// 2. 建立結帳按鈕並綁定事件
const checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', async () => {
try {
// 3. 開啟結帳視窗
await recur.checkout({
productId: 'prod_xxx', // 產品 ID(或使用 productSlug)
customerEmail: 'user@example.com', // 必填
customerName: '使用者名稱', // 選填
externalCustomerId: 'user_123', // 選填:連結您系統的用戶
mode: 'modal',
onSuccess: (result) => {
console.log('Checkout session 建立成功:', result);
},
onPaymentComplete: (result) => {
console.log('付款完成:', result);
window.location.href = '/subscription/success';
},
onError: (error) => {
console.error('訂閱失敗:', error);
alert('訂閱失敗,請稍後再試');
},
onClose: () => {
console.log('使用者關閉結帳視窗');
},
});
} catch (error) {
console.error('開啟結帳視窗時發生錯誤:', error);
}
});import { RecurCheckout } from 'recur-tw';
import { useState, useCallback } from 'react';
export function SubscriptionButton({ productId }: { productId: string }) {
const [isLoading, setIsLoading] = useState(false);
const handleSubscribe = useCallback(async () => {
setIsLoading(true);
const recur = RecurCheckout.init({
publishableKey: process.env.NEXT_PUBLIC_RECUR_PUBLISHABLE_KEY!,
});
try {
await recur.checkout({
productId, // 產品 ID(或使用 productSlug)
customerEmail: 'user@example.com', // 必填
customerName: '使用者名稱',
mode: 'modal',
onPaymentComplete: (result) => {
console.log('付款完成:', result);
window.location.href = '/subscription/success';
},
onError: (error) => {
console.error('訂閱失敗:', error);
alert('訂閱失敗,請稍後再試');
setIsLoading(false);
},
onClose: () => {
setIsLoading(false);
},
});
} catch (error) {
console.error('開啟結帳視窗時發生錯誤:', error);
setIsLoading(false);
}
}, [productId]);
return (
<button
onClick={handleSubscribe}
disabled={isLoading}
className="subscribe-button"
>
{isLoading ? '處理中...' : '立即訂閱'}
</button>
);
}HTML 結構
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recur SDK - 基本結帳範例</title>
</head>
<body>
<div class="container">
<h1>訂閱我們的服務</h1>
<p>選擇您想要的訂閱方案</p>
<div class="plan-card">
<h2>專業方案</h2>
<p class="price">NT$ 999 / 月</p>
<ul>
<li>功能 A</li>
<li>功能 B</li>
<li>功能 C</li>
</ul>
<button id="checkout-button">立即訂閱</button>
</div>
</div>
<!-- 載入 Recur SDK -->
<script src="https://unpkg.com/recur-tw@latest/dist/recur.umd.js"></script>
<!-- 你的應用程式腳本 -->
<script src="app.js"></script>
</body>
</html>步驟說明
1. 安裝 SDK
npm install recur-tw
# 或
yarn add recur-tw
# 或
pnpm add recur-tw<script src="https://unpkg.com/recur-tw@latest/dist/recur.umd.js"></script>2. 取得必要的資訊
你需要以下資訊:
- Publishable Key:在 Recur 儀表板 → 設定 → 開發者 → API 金鑰
- Product ID:在儀表板的「商品管理」中建立並取得
3. 初始化 SDK
使用你的 Publishable Key 初始化 SDK:
const recur = RecurCheckout.init({
publishableKey: 'pk_test_xxx',
});4. 開啟結帳視窗
呼叫 recur.checkout() 並傳入參數:
| 參數 | 必填 | 說明 |
|---|---|---|
productId | ✅* | 產品 ID(與 productSlug 二擇一) |
productSlug | ✅* | 產品 Slug(與 productId 二擇一) |
customerEmail | ✅ | 客戶 Email(0.4.3+ 必填) |
customerName | ❌ | 客戶姓名 |
externalCustomerId | ❌ | 外部客戶 ID |
mode | ❌ | 'modal' 或 'iframe' |
重點提醒
測試模式:開發時請使用測試環境的 API Key(pk_test_xxx),避免產生實際交易。
安全性:Publishable Key 可以在前端使用,但 Secret Key 必須保持在後端。
常見問題
Q: 為什麼 customerEmail 是必填?
A: 從 SDK 0.4.3 開始,為了確保訂閱建立時有完整的客戶資訊,customerEmail 為必填。如果未提供,SDK 會顯示表單讓用戶填寫。
Q: 如何處理使用者取消訂閱?
A: 使用 onClose 回調函數來處理使用者關閉結帳視窗的情況。
Q: 可以自訂結帳視窗的樣式嗎?
A: 可以!請參考 自訂樣式範例。
Q: 如何驗證訂閱是否成功?
A: 建議在後端透過 Webhook 來驗證訂閱狀態,詳見 Webhook 處理範例。
下一步
- API 參考 - 查看完整的 API 文件
- 自訂樣式 - 學習如何自訂樣式
- Webhook 通知 - 設定即時付款通知