credix
v2.5.1
Published
Official SDK for Credix Credit Management System
Readme
Credix
Credix Credit Management System の公式 Node.js/TypeScript SDK
📦 インストール
npm install credixまたは
yarn add credix🚀 クイックスタート
import { CredixClient } from 'credix';
// クライアントの初期化(コンストラクタのみで利用可能)
const credix = new CredixClient({
apiKey: 'credix_live_xxxxxxxxxxxxx',
secretKey: 'credix_sk_live_xxxxxxxxxxxxx',
});
// ユーザーにクレジットを付与
const allocation = await credix.allocations.grant({
externalUserId: 'user_123',
amount: 1000,
description: '初回ボーナス',
});
// クレジット残高を確認
const balance = await credix.users.getBalance('user_123');
console.log(`現在の残高: ${balance.balance}`);
// メーターでクレジットを消費
const consumption = await credix.meters.record({
meterId: 'api_calls',
externalUserId: 'user_123',
});📋 主な機能
- 🔐 認証管理 - APIキー/シークレットキーによる安全な認証
- 👥 ユーザー管理 - エンドユーザーの作成・管理・残高確認
- 📊 メーター管理 - 使用量の記録と制限チェック
- 💰 クレジット付与 - 手動付与、トリガー、クーポン、紹介
- 🎫 割引キャンペーン - アクティブな割引の取得・適用・資格確認
- 📈 分析・レポート - 使用量サマリー、トレンド、予測
- 🔔 Webhook - イベント通知の管理と署名検証
- 🔄 冪等性 - リクエストの重複実行を防止
🔧 設定
基本設定
const credix = new CredixClient({
// 必須
apiKey: 'your_api_key',
secretKey: 'your_secret_key',
// オプション
timeout: 30000, // タイムアウト(ミリ秒)
maxRetries: 3, // 最大リトライ回数
debug: false, // デバッグモード
// Webhook署名検証用
webhookSigningSecret: 'whsec_xxxxx', // Webhook署名シークレット
});環境変数での設定
# .env
Credix_API_KEY=credix_live_xxxxxxxxxxxxx
Credix_SECRET_KEY=credix_sk_live_xxxxxxxxxxxxx
Credix_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxconst credix = new CredixClient({
apiKey: process.env.Credix_API_KEY!,
secretKey: process.env.Credix_SECRET_KEY!,
});📚 API リファレンス
Users(ユーザー管理)
// ユーザー作成・更新
await credix.users.upsert({
externalUserId: 'user_123',
email: '[email protected]',
name: 'John Doe',
metadata: { plan: 'premium' },
});
// ユーザー情報取得
const user = await credix.users.getUser('user_123');
// 残高確認
const balance = await credix.users.getBalance('user_123');
// ユーザー一覧取得
const users = await credix.users.list({
limit: 20,
offset: 0,
});
// ユーザー削除
await credix.users.deleteUser('user_123');Meters(メーター管理)
// 使用量を記録
const record = await credix.meters.record({
meterId: 'api_calls',
externalUserId: 'user_123',
timestamp: new Date().toISOString(),
});
// 制限チェック
const limitCheck = await credix.meters.checkLimit({
meterId: 'api_calls',
externalUserId: 'user_123',
});
if (!limitCheck.allowed) {
console.log('制限超過:', limitCheck.reason);
}
// バッチ記録
await credix.meters.recordBatch({
records: [
{ meterId: 'api_calls', externalUserId: 'user_1' },
{ meterId: 'storage', externalUserId: 'user_2' },
],
});
// 使用統計取得
const stats = await credix.meters.getUsageStats({
meterId: 'api_calls',
frcredix: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z',
});Allocations(クレジット付与)
// 手動でクレジット付与
await credix.allocations.grant({
externalUserId: 'user_123',
amount: 1000,
reason: '月次ボーナス',
expiresAt: '2024-12-31T23:59:59Z',
});
// トリガーベースの付与
await credix.allocations.trigger({
allocationId: 'signup_bonus',
externalUserId: 'user_123',
});
// クーポン適用(新リソース)
await credix.coupons.apply({
externalUserId: 'user_123',
couponCode: 'WELCCredixE100',
})
// リファラル(新リソース)
// 紹介コードの生成(紹介者)。共有URLは導入側で構築してください。
const { referralCode } = await credix.referrals.generateCode({
referrerExternalUserId: 'user_123',
campaignId: 'friend-referral-2025', // 任意(指定しない場合は最初のアクティブ)
})
// 紹介コードの適用(被紹介者のサインアップ完了時に)
await credix.referrals.apply({
referredExternalUserId: 'user_456',
referralCode,
})
Discounts(割引キャンペーン)
// アクティブな割引を取得
const discounts = await credix.discounts.getActiveDiscounts({
externalUserId: 'user_123',
});
// 割引を適用
const result = await credix.discounts.applyDiscount({
externalUserId: 'user_123',
discountId: 'disc_123',
amount: 1000,
});
console.log(`割引適用後の金額: ${result.finalAmount}`);
// 割引適用資格をチェック
const eligibility = await credix.discounts.checkEligibility({
externalUserId: 'user_123',
discountId: 'first_time_discount',
});
if (eligibility.eligible) {
console.log('割引が適用可能です');
} else {
console.log(`適用不可: ${eligibility.reason}`);
}
// 全ての有効な割引を表示
const allDiscounts = await credix.discounts.listActiveDiscounts();
allDiscounts.discounts.forEach((discount) => {
console.log(`${discount.name}: ${discount.discountType}`);
});Transactions(トランザクション)
// トランザクション履歴取得
const transactions = await credix.transactions.list({
externalUserId: 'user_123',
type: 'allocation', // 'allocation' | 'consumption' | 'all'
frcredix: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z',
limit: 50,
});
// 特定のトランザクション取得
const transaction = await credix.transactions.getTransaction('tx_123');
// サマリー取得
const summary = await credix.transactions.getSummary({
externalUserId: 'user_123',
frcredix: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z',
});
// エクスポート
const exportData = await credix.transactions.export({
frcredix: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z',
format: 'csv', // 'json' | 'csv'
});Analytics(分析)
// 使用量サマリー
const summary = await credix.analytics.getSummary({
period: 'month', // 'day' | 'week' | 'month' | 'custcredix'
groupBy: 'meter', // 'meter' | 'day' | 'category' | 'user'
includeDiscounts: true,
});
// トレンド分析
const trends = await credix.analytics.getTrends({
period: 'week',
includeProjections: true,
});
// ユーザーランキング
const ranking = await credix.analytics.getUserRanking({
period: 'month',
limit: 10,
orderBy: 'credits', // 'credits' | 'allocations' | 'balance'
});
// 使用量予測
const predictions = await credix.analytics.getPredictions({
externalUserId: 'user_123',
basedOnDays: 30,
predictDays: 30,
});
// コスト分析
const costAnalysis = await credix.analytics.getCostAnalysis({
frcredix: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z',
groupBy: 'meter',
includeProjections: true,
});
// 異常検知
const ancredixalies = await credix.analytics.getAncredixalies({
threshold: 2.5, // 標準偏差の倍数
});Webhooks(Webhook管理)
// Webhookエンドポイント作成
const webhook = await credix.webhooks.create({
url: 'https://your-app.ccredix/webhook',
events: ['credits.allocated', 'credits.consumed'],
description: 'メインWebhook',
enabled: true,
});
// Webhook一覧取得
const webhooks = await credix.webhooks.list({
enabled: true,
});
// シークレットローテーション
const { secret } = await credix.webhooks.rotateSecret('webhook_123');
// テストイベント送信
await credix.webhooks.sendTestEvent('webhook_123', 'credits.allocated');
// 署名検証(Webhookリクエスト受信時)
app.post('/webhook', (req, res) => {
const signature = req.headers['x-webhook-signature'];
const isValid = credix.webhooks.verifySignature(
req.body,
signature,
);
if (!isValid) {
return res.status(401).send('Invalid signature');
}
const event = credix.webhooks.parsePayload(req.body);
console.log('Received event:', event);
res.status(200).send('OK');
});
// イベントハンドラー登録(ローカル処理)
credix.webhooks.on('credits.allocated', async (event) => {
console.log('Credits allocated:', event.data);
});
credix.webhooks.on('credits.low_balance', async (event) => {
// 低残高アラート処理
await sendLowBalanceEmail(event.data.userId);
});🔐 認証とセキュリティ
APIキーの種類
- Live環境:
credix_live_プレフィックス - Test環境:
credix_test_プレフィックス
シークレットキー
- Live環境:
credix_sk_live_プレフィックス - Test環境:
credix_sk_test_プレフィックス
セキュリティのベストプラクティス
- 環境変数の使用: APIキーは環境変数に保存
- シークレットの保護: シークレットキーは絶対にクライアントサイドに露出させない
- HTTPS通信: 本番環境では必ずHTTPS経由で通信
- キーローテーション: 定期的にAPIキーを更新
- アクセス制限: IPホワイトリストやCORSの適切な設定
🔄 冪等性
重複リクエストを防ぐため、SDKは自動的に冪等性キーを管理します。
// 例: クレジット付与
await credix.allocations.grant({
externalUserId: 'user_123',
amount: 1000,
});
🎯 エラーハンドリング
import { CredixError, ValidationError, NetworkError } frcredix '@credix/sdk';
try {
await credix.users.getUser('user_123');
} catch (error) {
if (error instanceof ValidationError) {
// バリデーションエラー
console.error('Validation failed:', error.field, error.message);
} else if (error instanceof NetworkError) {
// ネットワークエラー
console.error('Network error:', error.message);
} else if (error instanceof CredixError) {
// その他のSDKエラー
console.error('Credix SDK error:', error.code, error.message);
}
}🧪 テスト環境
テスト環境用のAPIキーを使用:
const credixTest = new CredixClient({
apiKey: 'credix_test_xxxxxxxxxxxxx',
secretKey: 'credix_sk_test_xxxxxxxxxxxxx',
});
// テストモードの確認
if (credixTest.isTestMode()) {
console.log('Running in test mode');
}📝 型定義
SDKは完全にTypeScriptで書かれており、すべてのAPIに型定義があります。
import type {
UserResponse,
AllocationResponse,
MeterStatistics,
WebhookEvent,
} frcredix '@credix/sdk';🔗 関連リンク
📄 ライセンス
MIT License
🤝 サポート
- Issues: GitHub Issues
- Email: [email protected]
- Discord: Ccredixmunity Server
