Node.js client for Payment Kit
npm install @blocklet/payment-jsA 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.
- Payment Kit Documentation - Official documentation with detailed guides and API references
``bash`
npm install @blocklet/payment-js
Configure the SDK with your desired environment and API key:
`js
import payment from '@blocklet/payment-js';
// Set environment mode
payment.environments.setTestMode(true); // Use test environment
// payment.environments.setLiveMode(true); // Use live environment
`
The SDK supports the following environment variables for configuration:
- PAYMENT_LIVE_MODE: Set to 'true' for live mode, 'false' for test modePAYMENT_TEST_MODE
- : Set to 'true' to enable test mode
`js`
const subscriptions = await payment.subscriptions.list({
order: 'updated_at:ASC', // Sort by update time
activeFirst: true, // Show active first
});
`js`
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
});
`js
// 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'
}
]
});
`
`js
// 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)
});
`
`js
// 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
});
`
`js
// 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
});
`
`js
// 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');
`
`js`
const refund = await payment.paymentIntents.refund('pi_xxx', {
amount: '0.001',
reason: 'requested_by_customer',
description: 'Refund description'
});
`js`
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'
]
});
- payment.customers.update(id, data)
- payment.customers.list(params)
- payment.customers.search(params)
- payment.customers.del(id)
- payment.customers.me()$3
- 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)$3
- 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)$3
- 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)$3
- payment.paymentLinks.create(data)
- payment.paymentLinks.retrieve(id)
- payment.paymentLinks.update(id, data)
- payment.paymentLinks.archive(id)
- payment.paymentLinks.list(params)$3
- 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)$3
- 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)$3
#### 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$3
#### 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$3
- 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$3
- 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
$3
- paid: Credits purchased by the customer
- promotional: Free credits given as promotions or bonuses$3
- sum: Sum all usage values
- count: Count number of events
- last: Use the last reported valueDiscount Management
The PaymentKit SDK provides comprehensive discount management through coupons and promotion codes:
$3
- 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$3
- 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$3
- 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 modificationsInvoice Management
The PaymentKit SDK offers comprehensive invoice operations:
$3
- 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$3
- 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 shortfallsSubscription 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 pausedError Handling
`js
try {
const subscription = await payment.subscriptions.retrieve('sub_xxx');
} catch (error) {
console.error('An error occurred:', error.message);
}
``The SDK is written in TypeScript and includes full type definitions for all resources and methods.
Apache-2.0