@blocklet/payment-js
TypeScript icon, indicating that this package has built-in type declarations

1.20.3 • Public • Published

PaymentKit Node.js SDK

A Node.js SDK for the PaymentKit API. This package allows you to manage resources in PaymentKit including customers, subscriptions, products, prices, payments, checkout sessions, usage records, webhooks, and credit-based billing with meters and credit grants.

Related Links

Installation

npm install @blocklet/payment-js

Getting Started

Configuration

Configure the SDK with your desired environment and API key:

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

// Set environment mode
payment.environments.setTestMode(true);      // Use test environment
// payment.environments.setLiveMode(true);   // Use live environment

Environment Variables

The SDK supports the following environment variables for configuration:

  • PAYMENT_LIVE_MODE: Set to 'true' for live mode, 'false' for test mode
  • PAYMENT_TEST_MODE: Set to 'true' to enable test mode

Usage Examples

Listing Subscriptions

const subscriptions = await payment.subscriptions.list({
  order: 'updated_at:ASC',    // Sort by update time
  activeFirst: true,          // Show active first
});

Creating a Checkout Session

const session = await payment.checkout.sessions.create({
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel',
  mode: 'payment',
  line_items: [
    { price_id: 'price_xxx', quantity: 1 }
  ],
  subscription_data: {
    service_actions: [
      {
        type: 'notification',
        text: { zh: '查看文档', en: 'View Documentation' },
        link: 'https://docs.example.com',
        triggerEvents: ['customer.subscription.started']
      }
    ]
  },
  expires_at: 1729243800
});

Managing Products and Prices

// Create product
const product = await payment.products.create({
  name: 'Test Product',
  description: 'Product description',
  type: 'service'
});

// Create price with EVM support
const price = await payment.prices.create({
  product_id: product.id,
  type: 'recurring',
  unit_amount: '0.001',
  currency_id: 'pc_xxx',
  recurring: {
    interval: 'month',
    interval_count: 1,
    usage_type: 'licensed'
  },
  quantity_available: 10,
  quantity_limit_per_checkout: 2,
  currency_options: [
    {
      currency_id: 'pc_xxx',
      unit_amount: '0.001'
    }
  ]
});

Managing Subscriptions

// get subscription
await payment.subscriptions.retrieve('sub_xxx');

// Report usage
await payment.subscriptionItems.createUsageRecord({
  subscription_item_id: 'si_xxx',
  quantity: 1,
  action: 'increment',
  timestamp: Math.floor(Date.now() / 1000)
});

Credit-Based Billing with Meters

// Create a meter to track usage
const meter = await payment.meters.create({
  name: 'API Calls',
  event_name: 'api_calls',
  aggregation_method: 'sum',
  unit: 'calls',
  description: 'Track API usage'
});

// Create a credit grant for a customer
const creditGrant = await payment.creditGrants.create({
  customer_id: 'cus_xxx',
  amount: '1000',
  currency_id: 'pc_xxx',
  category: 'promotional',
  name: 'New user bonus credits',
  expires_at: Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60) // 30 days
});

// Report usage events
const meterEvent = await payment.meterEvents.create({
  event_name: 'api_calls',
  payload: {
    customer_id: 'cus_xxx',
    value: '10',
    subscription_id: 'sub_xxx'
  },
  identifier: `unique_${Date.now()}`,
  timestamp: Math.floor(Date.now() / 1000)
});

// Check credit balance
const creditSummary = await payment.creditGrants.summary({
  customer_id: 'cus_xxx'
});


// View transaction history
const transactions = await payment.creditTransactions.list({
  customer_id: 'cus_xxx',
  page: 1,
  pageSize: 20
});

Handling Refunds

const refund = await payment.paymentIntents.refund('pi_xxx', {
  amount: '0.001',
  reason: 'requested_by_customer',
  description: 'Refund description'
});

Setting up Webhooks

const webhook = await payment.webhookEndpoints.create({
  url: 'https://example.com/webhook',
  enabled_events: [
    'checkout.session.completed',
    'checkout.session.nft_minted',
    'customer.subscription.created',
    'customer.subscription.deleted',
    'customer.subscription.paused',
    'customer.subscription.updated',
    'customer.subscription.started',
    'customer.subscription.renewed',
    'payment_intent.created',
    'payment_intent.succeeded'
  ]
});

API Resources

Customers

  • payment.customers.retrieve(id)
  • payment.customers.update(id, data)
  • payment.customers.list(params)
  • payment.customers.search(params)
  • payment.customers.del(id)
  • payment.customers.me()

Subscriptions

  • payment.subscriptions.retrieve(id)
  • payment.subscriptions.update(id, data)
  • payment.subscriptions.list(params)
  • payment.subscriptions.search(params)
  • payment.subscriptions.cancel(id, options)
  • payment.subscriptions.recover(id)
  • payment.subscriptions.pause(id)
  • payment.subscriptions.resume(id)
  • payment.subscriptions.del(id)

Products & Prices

  • payment.products.create(data)
  • payment.products.retrieve(id)
  • payment.products.update(id, data)
  • payment.products.list(params)
  • payment.products.search(params)
  • payment.products.archive(id)
  • payment.products.del(id)
  • payment.prices.create(data)
  • payment.prices.retrieve(id)
  • payment.prices.update(id, data)
  • payment.prices.list(params)
  • payment.prices.search(params)
  • payment.prices.archive(id)
  • payment.prices.del(id)
  • payment.prices.inventory(id, data)

Payments & Refunds

  • payment.paymentIntents.retrieve(id)
  • payment.paymentIntents.update(id, data)
  • payment.paymentIntents.list(params)
  • payment.paymentIntents.search(params)
  • payment.paymentIntents.refund(id, data)
  • payment.refunds.create(data)
  • payment.refunds.retrieve(id)
  • payment.refunds.list(params)
  • payment.refunds.search(params)

Payment Links

  • payment.paymentLinks.create(data)
  • payment.paymentLinks.retrieve(id)
  • payment.paymentLinks.update(id, data)
  • payment.paymentLinks.archive(id)
  • payment.paymentLinks.list(params)

Checkout

  • payment.checkout.sessions.create(data)
  • payment.checkout.sessions.retrieve(id)
  • payment.checkout.sessions.update(id, data)
  • payment.checkout.sessions.expire(id)
  • payment.checkout.sessions.list(params)

Usage & Metering

  • payment.subscriptionItems.create(data)
  • payment.subscriptionItems.retrieve(id)
  • payment.subscriptionItems.update(id, data)
  • payment.subscriptionItems.list(params)
  • payment.subscriptionItems.del(id)
  • payment.subscriptionItems.createUsageRecord(data)
  • payment.subscriptionItems.listUsageRecordSummaries(id)
  • payment.subscriptionItems.listUsageRecords(params)

Credit-Based Billing

Meters

  • payment.meters.create(data) - Create a meter to track usage events
  • payment.meters.retrieve(id) - Get meter details
  • payment.meters.update(id, data) - Update meter configuration
  • payment.meters.list(params) - List all meters
  • payment.meters.activate(id) - Activate a meter
  • payment.meters.deactivate(id) - Deactivate a meter

Meter Events

  • payment.meterEvents.create(data) - Report usage events
  • payment.meterEvents.retrieve(id) - Get meter event details
  • payment.meterEvents.list(params) - List meter events
  • payment.meterEvents.stats(params) - Get usage statistics
  • payment.meterEvents.pendingAmount(params) - Get pending credit consumption

Credit Grants

  • payment.creditGrants.create(data) - Create credit grants for customers
  • payment.creditGrants.retrieve(id) - Get credit grant details
  • payment.creditGrants.update(id, data) - Update credit grant metadata
  • payment.creditGrants.list(params) - List credit grants
  • payment.creditGrants.summary(params) - Get credit balance summary

Credit Transactions

  • payment.creditTransactions.retrieve(id) - Get transaction details
  • payment.creditTransactions.list(params) - List credit transactions
  • payment.creditTransactions.summary(params) - Get usage and credit summary

Webhooks

  • payment.webhookEndpoints.create(data)
  • payment.webhookEndpoints.retrieve(id)
  • payment.webhookEndpoints.update(id, data)
  • payment.webhookEndpoints.list(params)
  • payment.webhookEndpoints.del(id)

Credit-Based Billing

The PaymentKit SDK supports credit-based billing, allowing you to:

  1. Track Usage with Meters: Create meters to track specific usage events (API calls, storage usage, etc.)
  2. Grant Credits: Issue credits to customers through various methods (purchases, promotions, etc.)
  3. Report Usage: Submit usage events that consume credits automatically
  4. Monitor Balances: Check remaining credit balances and transaction history
  5. Usage Analytics: Get detailed statistics on usage patterns

Credit Grant Categories

  • paid: Credits purchased by the customer
  • promotional: Free credits given as promotions or bonuses

Meter Aggregation Methods

  • sum: Sum all usage values
  • count: Count number of events
  • last: Use the last reported value

Subscription Status

A subscription can have the following statuses:

  • active: The subscription is in good standing
  • canceled: The subscription has been canceled
  • incomplete: Initial payment attempt failed
  • incomplete_expired: Initial payment failed and retry period expired
  • past_due: Latest payment failed
  • trialing: In trial period
  • paused: Temporarily paused

Error Handling

try {
  const subscription = await payment.subscriptions.retrieve('sub_xxx');
} catch (error) {
  console.error('An error occurred:', error.message);
}

TypeScript Support

The SDK is written in TypeScript and includes full type definitions for all resources and methods.

License

Apache-2.0

Readme

Keywords

Package Sidebar

Install

npm i @blocklet/payment-js

Weekly Downloads

1,456

Version

1.20.3

License

Apache-2.0

Unpacked Size

84.8 kB

Total Files

40

Last publish

Collaborators

  • wangshijun
  • gxw