jpskill.com
💼 ビジネス コミュニティ

credits-handler

クレジットの割り当てや購入、利用状況を管理し、クレジットの種類追加や価格設定、UI構築など、クレジットシステム全般を円滑に運用・設定・構築するSkill。

📜 元の英語説明(参考)

Manage the credit system (allocation, purchasing, usage). Use when adding credit types, configuring pricing, or building credit UI.

🇯🇵 日本人クリエイター向け解説

一言でいうと

クレジットの割り当てや購入、利用状況を管理し、クレジットの種類追加や価格設定、UI構築など、クレジットシステム全般を円滑に運用・設定・構築するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o credits-handler.zip https://jpskill.com/download/16902.zip && unzip -o credits-handler.zip && rm credits-handler.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/16902.zip -OutFile "$d\credits-handler.zip"; Expand-Archive "$d\credits-handler.zip" -DestinationPath $d -Force; ri "$d\credits-handler.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して credits-handler.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → credits-handler フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

クレジットハンドラー

このスキルでは、バックエンドの設定からフロントエンドのUI実装まで、クレジットシステム全体について説明します。

1. 設定

すべてのクレジット設定は、src/lib/credits/config.ts にあります。

新しいクレジットタイプの追加

  1. タイプの定義: creditTypeSchema 列挙型に新しいタイプを追加します。

    export const creditTypeSchema = z.enum([
      "image_generation",
      "video_generation",
      "your_new_credit_type" // これを追加
    ]);
  2. 価格とメタデータの設定: creditsConfig にエントリを追加します。

    your_new_credit_type: {
      name: "New Credit Name",
      currency: "USD",
      minimumAmount: 10,
      // オプションA: 固定スラブ
      slabs: [
        { from: 1, to: 100, pricePerUnit: 0.10 },
        { from: 101, to: 1000, pricePerUnit: 0.08 },
      ],
      // オプションB: 動的計算機 (例: ユーザープランに基づく)
      priceCalculator: (amount, userPlan) => {
         // ここにロジックを記述
         return amount * 0.1;
      }
    }
  3. プラン割り当て (オプション): onPlanChangeCredits でプランをサブスクライブする際に付与されるクレジット数を定義します。

2. UI実装: クレジットの購入

ユーザーがクレジットを購入できるようにするには、useBuyCredits フックを使用します。このフックは、価格計算 (プラン割引を考慮) とチェックアウトURLの生成を処理します。

主要なフック: useBuyCredits

場所: src/lib/credits/useBuyCredits.ts

使い方

import useBuyCredits from "@/lib/credits/useBuyCredits";
import { PlanProvider } from "@/lib/plans/getSubscribeUrl";

const { 
  price,            // 計算された合計価格 (number | undefined)
  isLoading,        // 価格計算の進行状況
  error,            // エラー状態
  getBuyCreditsUrl  // 支払いURLを生成する関数
} = useBuyCredits(creditType, amount);

例: 価格カードの作成

src/components/website/website-credits-section.tsx と同様の、クレジット購入UIを作成するためのパターンを以下に示します。

"use client";

import { useState } from "react";
import useBuyCredits from "@/lib/credits/useBuyCredits";
import { PlanProvider } from "@/lib/plans/getSubscribeUrl";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";

// 1. パッケージを定義
const PACKAGE = {
  credits: 100,
  name: "Starter Pack",
};

export function BuyCreditsCard({ creditType }: { creditType: "image_generation" }) {
  const [provider] = useState(PlanProvider.STRIPE); // または LEMONSQUEEZY

  // 2. フックを呼び出す
  const { price, isLoading, error, getBuyCreditsUrl } = useBuyCredits(
    creditType,
    PACKAGE.credits
  );

  // 3. 購入を処理する
  const handleBuy = () => {
    const url = getBuyCreditsUrl(provider);
    window.location.href = url;
  };

  // 4. UIをレンダリングする
  return (
    <div className="border p-4 rounded-lg">
      <h3>{PACKAGE.name}</h3>
      <div className="text-2xl font-bold">
        {isLoading ? (
          <Loader2 className="animate-spin" />
        ) : (
          `$${price?.toFixed(2) || "0.00"}`
        )}
      </div>

      <Button 
        onClick={handleBuy}
        disabled={isLoading || !price}
        className="w-full mt-4"
      >
        Buy {PACKAGE.credits} Credits
      </Button>

      {error && <p className="text-red-500 text-sm">{error.message}</p>}
    </div>
  );
}

3. UI実装: クレジットの表示

ユーザーの現在の残高を表示するには、useCredits フックを使用します。

主要なフック: useCredits

場所: src/lib/users/useCredits.ts

返されるデータ構造

const { 
  credits,    // Record<string, number> | undefined
              // 例: { "image_generation": 100, "video_generation": 50 }
  isLoading,  // boolean
  error,      // any
  mutate      // データをリフレッシュするSWR mutate関数
} = useCredits();

使用例

import useCredits from "@/lib/users/useCredits";

export function CreditBalance() {
  const { credits, isLoading } = useCredits();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      Image Credits: {credits?.image_generation || 0}
    </div>
  );
}

4. コアオペレーション (バックエンド)

これらの関数は、APIルートとWebhookで使用されます。

クレジットの割り当て (例: プラン変更時)

ユーザーがサブスクライブ/アップグレードしたときにクレジットを付与するには、allocatePlanCredits を使用します。

  • ファイル: src/lib/credits/allocatePlanCredits.ts
  • 入力: userIdplanIdpaymentId (冪等性のために)。
  • 動作: onPlanChangeCredits 設定を確認し、該当する場合はクレジットを追加します。

クレジットの加算/減算

残高を手動で操作するには、src/lib/credits/recalculate.ts のヘルパー (例: addCreditsdeductCredits) を使用します。 注: 重複を防ぐために、クレジットを追加する際は常に一意の paymentId またはトランザクション参照があることを確認してください。

5. 残高の確認 (バックエンド/共通)

アクションを実行する前に canDeductCredits を使用します。

import { canDeductCredits } from "@/lib/credits/credits";

// ユーザーが十分なクレジットを持っているか確認
const hasBalance = canDeductCredits(
  "image_generation", 
  1, 
  user // { credits: { ... } } を含む必要がある
);

if (!hasBalance) {
  throw new Error("Insufficient credits");
}

6. リファレンス

データベーススキーマとアーキテクチャの詳細については、reference.md を参照してください。

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Credits Handler

This skill guides you through the entire credit system, from backend configuration to frontend UI implementation.

1. Configuration

All credit configuration lives in src/lib/credits/config.ts.

Adding a New Credit Type

  1. Define the Type: Add the new type to creditTypeSchema enum.

    export const creditTypeSchema = z.enum([
      "image_generation",
      "video_generation",
      "your_new_credit_type" // Add this
    ]);
  2. Configure Pricing & Metadata: Add an entry to creditsConfig.

    your_new_credit_type: {
      name: "New Credit Name",
      currency: "USD",
      minimumAmount: 10,
      // Option A: Fixed Slabs
      slabs: [
        { from: 1, to: 100, pricePerUnit: 0.10 },
        { from: 101, to: 1000, pricePerUnit: 0.08 },
      ],
      // Option B: Dynamic Calculator (e.g., based on user plan)
      priceCalculator: (amount, userPlan) => {
         // Logic here
         return amount * 0.1;
      }
    }
  3. Plan Allocations (Optional): Define how many credits are given when subscribing to a plan in onPlanChangeCredits.

2. UI Implementation: Buying Credits

To let users purchase credits, use the useBuyCredits hook. This hook handles price calculation (factoring in plan discounts) and generating checkout URLs.

Key Hook: useBuyCredits

Location: src/lib/credits/useBuyCredits.ts

Usage

import useBuyCredits from "@/lib/credits/useBuyCredits";
import { PlanProvider } from "@/lib/plans/getSubscribeUrl";

const { 
  price,            // Calculated total price (number | undefined)
  isLoading,        // Price calculation in progress
  error,            // Error state
  getBuyCreditsUrl  // Function to generate payment URL
} = useBuyCredits(creditType, amount);

Example: Building a Pricing Card

Here is a pattern for creating a credit purchase UI, similar to src/components/website/website-credits-section.tsx.

"use client";

import { useState } from "react";
import useBuyCredits from "@/lib/credits/useBuyCredits";
import { PlanProvider } from "@/lib/plans/getSubscribeUrl";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";

// 1. Define your packages
const PACKAGE = {
  credits: 100,
  name: "Starter Pack",
};

export function BuyCreditsCard({ creditType }: { creditType: "image_generation" }) {
  const [provider] = useState(PlanProvider.STRIPE); // or LEMONSQUEEZY

  // 2. Call the hook
  const { price, isLoading, error, getBuyCreditsUrl } = useBuyCredits(
    creditType,
    PACKAGE.credits
  );

  // 3. Handle Purchase
  const handleBuy = () => {
    const url = getBuyCreditsUrl(provider);
    window.location.href = url;
  };

  // 4. Render UI
  return (
    <div className="border p-4 rounded-lg">
      <h3>{PACKAGE.name}</h3>
      <div className="text-2xl font-bold">
        {isLoading ? (
          <Loader2 className="animate-spin" />
        ) : (
          `$${price?.toFixed(2) || "0.00"}`
        )}
      </div>

      <Button 
        onClick={handleBuy}
        disabled={isLoading || !price}
        className="w-full mt-4"
      >
        Buy {PACKAGE.credits} Credits
      </Button>

      {error && <p className="text-red-500 text-sm">{error.message}</p>}
    </div>
  );
}

3. UI Implementation: Displaying Credits

To show the user's current balance, use the useCredits hook.

Key Hook: useCredits

Location: src/lib/users/useCredits.ts

Return Data Structure

const { 
  credits,    // Record<string, number> | undefined
              // e.g. { "image_generation": 100, "video_generation": 50 }
  isLoading,  // boolean
  error,      // any
  mutate      // SWR mutate function to refresh data
} = useCredits();

Usage Example

import useCredits from "@/lib/users/useCredits";

export function CreditBalance() {
  const { credits, isLoading } = useCredits();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      Image Credits: {credits?.image_generation || 0}
    </div>
  );
}

4. Core Operations (Backend)

These functions are used in API routes and webhooks.

Allocating Credits (e.g., on Plan Change)

Use allocatePlanCredits to give users credits when they subscribe/upgrade.

  • File: src/lib/credits/allocatePlanCredits.ts
  • Input: userId, planId, paymentId (for idempotency).
  • Behavior: Checks onPlanChangeCredits config and adds credits if applicable.

Adding/Deducting Credits

To manually manipulate balances, use helpers from src/lib/credits/recalculate.ts (e.g., addCredits, deductCredits). Note: Always ensure you have a unique paymentId or transaction reference when adding credits to prevent duplicates.

5. Checking Balance (Backend/Common)

Use canDeductCredits before performing an action.

import { canDeductCredits } from "@/lib/credits/credits";

// Check if user has enough credits
const hasBalance = canDeductCredits(
  "image_generation", 
  1, 
  user // Must contain { credits: { ... } }
);

if (!hasBalance) {
  throw new Error("Insufficient credits");
}

6. Reference

For deep dives into database schema and architecture, see reference.md.