npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@blocklet/payment-js

v1.23.0

Published

Node.js client for Payment Kit

Readme

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, credit-based billing with meters and credit grants, discount management with coupons and promotion codes, and comprehensive invoice operations.

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
});

Managing Coupons and Promotion Codes

// Create a coupon with promotion codes
const result = await payment.coupons.create({
  name: 'New User Discount',
  percent_off: 20,
  duration: 'once',
  max_redemptions: 1000,
  promotion_codes: [
    {
      code: 'WELCOME20',
      description: 'Welcome discount for new users',
      max_redemptions: 100,
      expires_at: Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60) // 30 days
    }
  ]
});

// Create standalone promotion code
const promotionCode = await payment.promotionCodes.create({
  coupon_id: 'coupon_xxx',
  description: 'Save 15% on your purchase',
  verification_type: 'code',
  max_redemptions: 500
});

// Get promotion code by code
const promoByCode = await payment.promotionCodes.byCode('WELCOME20');

// Check coupon usage
const { used } = await payment.coupons.used('coupon_xxx');

// Get redemptions data
const redemptions = await payment.coupons.redemptions('coupon_xxx', {
  type: 'customer',
  page: 1,
  pageSize: 20
});

Managing Invoices

// Retrieve invoice with discount details
const invoice = await payment.invoices.retrieve('inv_xxx');
console.log(invoice.discountDetails); // Applied discounts
console.log(invoice.relatedCreditGrants); // Related credit grants

// List invoices with filters
const invoices = await payment.invoices.list({
  customer_id: 'cus_xxx',
  status: 'paid,open',
  ignore_zero: true,
  include_staking: false,
  page: 1,
  pageSize: 20
});

// Search invoices
const searchResults = await payment.invoices.search({
  query: 'invoice number or customer',
  page: 1,
  pageSize: 10
});

// Update invoice metadata
const updatedInvoice = await payment.invoices.update('inv_xxx', {
  metadata: { notes: 'Updated invoice' }
});

// Void an invoice
const voidedInvoice = await payment.invoices.void('inv_xxx');

// Handle staking operations
const stakeInfo = await payment.invoices.getReturnStake('inv_stake_xxx');
const returnResult = await payment.invoices.returnStake('inv_stake_xxx');

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',
    'checkout.session.expired',
    'customer.subscription.created',
    'customer.subscription.deleted',
    'customer.subscription.paused',
    'customer.subscription.updated',
    'customer.subscription.started',
    'customer.subscription.renewed',
    'invoice.created',
    'invoice.paid',
    'invoice.payment_failed',
    'invoice.voided',
    '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

Coupons & Promotion Codes

Coupons

  • payment.coupons.create(data) - Create coupon with optional promotion codes
  • payment.coupons.retrieve(id) - Get coupon details with related data
  • payment.coupons.update(id, data) - Update coupon information
  • payment.coupons.list(params) - List coupons with filtering
  • payment.coupons.del(id) - Delete coupon
  • payment.coupons.used(id) - Check if coupon is being used
  • payment.coupons.redemptions(id, params) - Get coupon redemption details

Promotion Codes

  • payment.promotionCodes.create(data) - Create promotion code
  • payment.promotionCodes.retrieve(id) - Get promotion code details
  • payment.promotionCodes.update(id, data) - Update promotion code
  • payment.promotionCodes.list(params) - List promotion codes
  • payment.promotionCodes.archive(id) - Archive promotion code
  • payment.promotionCodes.del(id) - Delete promotion code
  • payment.promotionCodes.used(id) - Check if promotion code is being used
  • payment.promotionCodes.byCode(code) - Get promotion code by code string
  • payment.promotionCodes.redemptions(id, params) - Get promotion code redemptions

Invoices

  • payment.invoices.retrieve(id) - Get invoice with discount and related data
  • payment.invoices.update(id, data) - Update invoice metadata
  • payment.invoices.list(params) - List invoices with comprehensive filtering
  • payment.invoices.search(params) - Search invoices by query
  • payment.invoices.getReturnStake(id) - Get stake return information
  • payment.invoices.returnStake(id) - Execute stake return operation
  • payment.invoices.void(id) - Void an invoice

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

Discount Management

The PaymentKit SDK provides comprehensive discount management through coupons and promotion codes:

Coupons

  • Amount-based or Percentage Discounts: Create fixed amount or percentage-based discounts
  • Duration Control: Set discounts for 'once', 'forever', or 'repeating' billing cycles
  • Usage Limits: Control maximum redemptions and expiration dates
  • Multi-Currency Support: Configure different discount amounts per currency
  • Product Targeting: Apply discounts to specific products

Promotion Codes

  • Access Control: Create codes for public use or restrict to specific customers
  • Verification Types: Support code-based, NFT-based, VC-based, or user-restricted verification
  • Usage Tracking: Monitor redemption statistics and usage patterns
  • Flexible Restrictions: Set minimum purchase amounts and other conditions

Key Features

  • Automatic Application: Discounts are automatically calculated during checkout
  • Usage Rollback: Failed payments don't consume discount usage quotas
  • Analytics: Track redemption patterns and discount effectiveness
  • Audit Trail: Complete history of discount applications and modifications

Invoice Management

The PaymentKit SDK offers comprehensive invoice operations:

Core Features

  • Rich Details: Retrieve invoices with discount details, payment information, and related data
  • Advanced Filtering: Filter by customer, status, currency, subscription, and custom metadata
  • Search Capability: Full-text search across invoice data
  • Staking Operations: Handle stake deposits and returns for subscription-based services
  • Status Management: Void invoices and handle payment state transitions

Special Invoice Types

  • Regular Billing: Standard subscription and one-time payment invoices
  • Staking Invoices: Handle deposits and collateral for services
  • Recharge Invoices: Credit top-ups and account funding
  • Overdraft Protection: Automatic coverage for account shortfalls

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