@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
- Payment Kit Documentation - Official documentation with detailed guides and API references
Installation
npm install @blocklet/payment-jsGetting 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 modePAYMENT_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 eventspayment.meters.retrieve(id)- Get meter detailspayment.meters.update(id, data)- Update meter configurationpayment.meters.list(params)- List all meterspayment.meters.activate(id)- Activate a meterpayment.meters.deactivate(id)- Deactivate a meter
Meter Events
payment.meterEvents.create(data)- Report usage eventspayment.meterEvents.retrieve(id)- Get meter event detailspayment.meterEvents.list(params)- List meter eventspayment.meterEvents.stats(params)- Get usage statisticspayment.meterEvents.pendingAmount(params)- Get pending credit consumption
Credit Grants
payment.creditGrants.create(data)- Create credit grants for customerspayment.creditGrants.retrieve(id)- Get credit grant detailspayment.creditGrants.update(id, data)- Update credit grant metadatapayment.creditGrants.list(params)- List credit grantspayment.creditGrants.summary(params)- Get credit balance summary
Credit Transactions
payment.creditTransactions.retrieve(id)- Get transaction detailspayment.creditTransactions.list(params)- List credit transactionspayment.creditTransactions.summary(params)- Get usage and credit summary
Coupons & Promotion Codes
Coupons
payment.coupons.create(data)- Create coupon with optional promotion codespayment.coupons.retrieve(id)- Get coupon details with related datapayment.coupons.update(id, data)- Update coupon informationpayment.coupons.list(params)- List coupons with filteringpayment.coupons.del(id)- Delete couponpayment.coupons.used(id)- Check if coupon is being usedpayment.coupons.redemptions(id, params)- Get coupon redemption details
Promotion Codes
payment.promotionCodes.create(data)- Create promotion codepayment.promotionCodes.retrieve(id)- Get promotion code detailspayment.promotionCodes.update(id, data)- Update promotion codepayment.promotionCodes.list(params)- List promotion codespayment.promotionCodes.archive(id)- Archive promotion codepayment.promotionCodes.del(id)- Delete promotion codepayment.promotionCodes.used(id)- Check if promotion code is being usedpayment.promotionCodes.byCode(code)- Get promotion code by code stringpayment.promotionCodes.redemptions(id, params)- Get promotion code redemptions
Invoices
payment.invoices.retrieve(id)- Get invoice with discount and related datapayment.invoices.update(id, data)- Update invoice metadatapayment.invoices.list(params)- List invoices with comprehensive filteringpayment.invoices.search(params)- Search invoices by querypayment.invoices.getReturnStake(id)- Get stake return informationpayment.invoices.returnStake(id)- Execute stake return operationpayment.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:
- Track Usage with Meters: Create meters to track specific usage events (API calls, storage usage, etc.)
- Grant Credits: Issue credits to customers through various methods (purchases, promotions, etc.)
- Report Usage: Submit usage events that consume credits automatically
- Monitor Balances: Check remaining credit balances and transaction history
- Usage Analytics: Get detailed statistics on usage patterns
Credit Grant Categories
paid: Credits purchased by the customerpromotional: Free credits given as promotions or bonuses
Meter Aggregation Methods
sum: Sum all usage valuescount: Count number of eventslast: 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 standingcanceled: The subscription has been canceledincomplete: Initial payment attempt failedincomplete_expired: Initial payment failed and retry period expiredpast_due: Latest payment failedtrialing: In trial periodpaused: 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
