メインコンテンツへスキップ

クレジット付与

クレジット付与オブジェクトは、顧客にクレジットを発行するために使用されます。これらのクレジットは、特に使用量ベースまたはクレジットベースの請求モデルにおいて、将来の請求書に適用できます。各付与は、総額、残高、ステータス、および特定の適用可能性ルールを追跡します。

完全なクレジットベースのシステムを実装する方法についての詳細は、クレジットベースの請求に関するガイドをご参照ください。

クレジット付与オブジェクト

CreditGrant オブジェクトには、顧客への特定のクレジット発行に関するすべての詳細が含まれています。

クレジット付与オブジェクト

json
{
  "id": "crdg_1B2c3D4e5F6g7H8i9J0k1L2m",
  "object": "credit_grant",
  "amount": "5000",
  "currency_id": "curr_usd",
  "customer_id": "cus_a1b2c3d4e5f6g7h8",
  "name": "プロモーション用オンボーディングクレジット",
  "category": "promotional",
  "priority": 50,
  "status": "granted",
  "effective_at": 1672531200,
  "expires_at": 1704067199,
  "granted_at": 1672531200,
  "remaining_amount": "3500",
  "applicability_config": {
    "scope": {
      "price_type": "metered"
    }
  },
  "metadata": {
    "campaign_id": "promo_q1_2024"
  },
  "livemode": true,
  "created_at": "2023-01-01T00:00:00.000Z",
  "updated_at": "2023-01-15T10:30:00.000Z",
  "customer": {
    "id": "cus_a1b2c3d4e5f6g7h8",
    "did": "did:abt:z1...",
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  "paymentCurrency": {
    "id": "curr_usd",
    "name": "米ドル",
    "symbol": "$",
    "decimal": 2
  }
}

クレジット付与の作成

顧客に新しいクレジット付与を発行します。指定された顧客が存在しない場合、提供された customer_id (DID) に基づいて新しい顧客が自動的に作成されます。

クレジット付与の作成

javascript
import payment from '@blocklet/payment-js';

async function createCreditGrant() {
  try {
    const creditGrant = await payment.creditGrants.create({
      amount: '100.00',
      currency_id: 'curr_usd', // 有効な通貨IDに置き換えてください
      customer_id: 'cus_a1b2c3d4e5f6g7h8', // またはユーザーDID
      name: 'Initial sign-up bonus',
      category: 'promotional',
      priority: 50,
      expires_at: Math.floor(new Date('2024-12-31').getTime() / 1000),
      metadata: {
        source: 'marketing_campaign_fall_2024'
      }
    });
    console.log('Credit grant created:', creditGrant);
  } catch (error) {
    console.error('Error creating credit grant:', error.message);
  }
}

createCreditGrant();

パラメータ

NameTypeDescription
amountstring必須。 付与するクレジットの額。数値の文字列表現として指定します。
currency_idstring必須。 この付与の通貨ID。
customer_idstring必須。 クレジットを受け取る顧客のIDまたはDID。
namestring内部参照用のクレジット付与のオプション名。
category'paid' | 'promotional'必須。 付与のカテゴリ。paid は通常顧客が購入したもので、promotional は無料で提供されるものです。
prioritynumberオプション。適用順序を決定するために使用される0から100までの数値。数値が小さいほど先に適用されます。デフォルトは 50 です。
effective_atnumberオプション。付与が有効になる時期を示すUnixタイムスタンプ。指定しない場合、即時に有効になります。
expires_atnumberオプション。付与が失効する時期を示すUnixタイムスタンプ。
applicability_configobjectオプション。このクレジットを適用できる場所のルールを定義します。詳細は下記を参照してください。設定されていない場合、デフォルトですべての従量課金価格に適用されます。
metadataobjectオプション。オブジェクトに添付できるキーと値のペアのセット。追加情報を保存するのに便利です。

applicability_config オブジェクトのプロパティ

NameTypeDescription
scopeobjectクレジット付与が適用される価格の範囲を定義します。

scope オブジェクトのプロパティ

NameTypeDescription
pricesstring[]価格IDの配列。指定された場合、クレジット付与はこれらの価格にのみ適用されます。
price_typestring'metered' に設定できます。指定された場合、クレジット付与はこのタイプのすべての価格に適用されます。

戻り値

呼び出しが成功した場合、TCreditGrantExpanded オブジェクトを返します。

クレジット付与の取得

一意の識別子によって、既存のクレジット付与の詳細を取得します。

クレジット付与の取得

javascript
import payment from '@blocklet/payment-js';

async function getCreditGrant(grantId) {
  try {
    const creditGrant = await payment.creditGrants.retrieve(grantId);
    console.log('Retrieved credit grant:', creditGrant);
  } catch (error) {
    console.error(`Error retrieving credit grant ${grantId}:`, error.message);
  }
}

getCreditGrant('crdg_1B2c3D4e5F6g7H8i9J0k1L2m'); // 有効なクレジット付与IDに置き換えてください

パラメータ

NameTypeDescription
idstring必須。 取得するクレジット付与の一意の識別子。

戻り値

applicability_config.scope.prices が設定されている場合、展開された価格オブジェクトの配列を含む追加の items プロパティを持つ TCreditGrantExpanded オブジェクトを返します。

クレジット付与の更新

metadata プロパティを設定または設定解除することにより、指定されたクレジット付与を更新します。他のプロパティは更新できません。

クレジット付与の更新

javascript
import payment from '@blocklet/payment-js';

async function updateCreditGrantMetadata(grantId) {
  try {
    const result = await payment.creditGrants.update(grantId, {
      metadata: {
        source: 'marketing_campaign_fall_2024',
        updated_by: 'admin_user_xyz'
      }
    });
    console.log('Update successful:', result.success);
  } catch (error) {
    console.error(`Error updating credit grant ${grantId}:`, error.message);
  }
}

updateCreditGrantMetadata('crdg_1B2c3D4e5F6g7H8i9J0k1L2m'); // 有効なクレジット付与IDに置き換えてください

パラメータ

NameTypeDescription
idstring必須。 更新するクレジット付与のID。
metadataobjectオブジェクトに保存するキーと値のペアのセット。キーを削除するには、その値を null に設定します。

戻り値

success ブール値を含むオブジェクト。

レスポンス

json
{
  "success": true
}

クレジット付与の一覧表示

ページ分割されたクレジット付与のリストを返します。さまざまなパラメータに基づいてリストをフィルタリングできます。

クレジット付与の一覧表示

javascript
import payment from '@blocklet/payment-js';

async function listCustomerCreditGrants() {
  try {
    const grants = await payment.creditGrants.list({
      customer_id: 'cus_a1b2c3d4e5f6g7h8', // 有効な顧客IDに置き換えてください
      status: 'granted,pending',
      pageSize: 10
    });
    console.log(`Found ${grants.count} grants.`);
    grants.list.forEach(grant => {
      console.log(`- ${grant.id} (${grant.status})`);
    });
  } catch (error) {
    console.error('Error listing credit grants:', error.message);
  }
}

listCustomerCreditGrants();

パラメータ

NameTypeDescription
customer_idstringオプション。特定の顧客IDまたはDIDで付与をフィルタリングします。
currency_idstringオプション。通貨IDで付与をフィルタリングします。
statusstringオプション。フィルタリングするステータスのコンマ区切り文字列(例:'granted,pending,depleted')。
livemodebooleanオプション。ライブモードでフィルタリングします。
qstringオプション。一般的な検索クエリ文字列。
pagenumberオプション。ページネーション用のページ番号。デフォルトは 1 です。
pageSizenumberオプション。ページあたりのアイテム数。デフォルトは 20 です。

戻り値

TCreditGrantExpanded オブジェクトの list と、レコードの総数を示す count を含むページ分割されたオブジェクト。

クレジット概要の取得

顧客の有効なクレジット残高の概要を、通貨別にグループ化して取得します。これは、顧客の利用可能なクレジット総額を表示するのに便利です。

クレジット概要の取得

javascript
import payment from '@blocklet/payment-js';

async function getCustomerCreditSummary(customerId) {
  try {
    const summary = await payment.creditGrants.summary({ customer_id: customerId });
    console.log('Customer Credit Summary:', summary);
  } catch (error) {
    console.error(`Error fetching credit summary for ${customerId}:`, error.message);
  }
}

getCustomerCreditSummary('cus_a1b2c3d4e5f6g7h8'); // 有効な顧客IDに置き換えてください

パラメータ

NameTypeDescription
customer_idstring必須。 クレジット概要を取得したい顧客のIDまたはDID。
subscription_idstringオプション。指定された場合、概要にはこの特定のサブスクリプションの価格に適用可能なクレジットのみが含まれます。

戻り値

CreditSummary オブジェクトを返します。これは、各キーが通貨IDであるマップです。値は、その通貨のクレジット総額と残高、および有効な付与の数を含むオブジェクトです。

レスポンス

json
{
  "curr_usd": {
    "paymentCurrency": {
      "id": "curr_usd",
      "name": "米ドル",
      "symbol": "$",
      "decimal": 2
    },
    "totalAmount": "15000",
    "remainingAmount": "8500",
    "grantCount": 2
  },
  "curr_eur": {
    "paymentCurrency": {
      "id": "curr_eur",
      "name": "ユーロ",
      "symbol": "€",
      "decimal": 2
    },
    "totalAmount": "2000",
    "remainingAmount": "2000",
    "grantCount": 1
  }
}

次に、クレジットトランザクション API を参照して、クレジット消費がどのように記録されるかについて詳しく知ることができます。