Sir Chargly SDK Reference
Complete reference for the @sirchargly/sdk package.
Version: 1.0.0
Updated: January 2026
Installation
npm install @sirchargly/sdk
# or
yarn add @sirchargly/sdk
Quick Start
import SirChargly from '@sirchargly/sdk';
const client = new SirChargly('sk_dev_sirchargly_your_api_key');
// Create a fee estimate
const estimate = await client.estimates.create({
amount: 10000,
currency: 'usd',
regionCode: 'US-CA',
paymentMethod: 'visa_credit'
});
console.log(`Fee: $${estimate.fee.amount / 100}`);
console.log(`Total: $${estimate.total / 100}`);
Client Initialization
`new SirChargly(apiKey, config?)`
Creates a new Sir Chargly client instance.
Parameters:
apiKey (string, required): Your Sir Chargly API key (e.g., sk_dev_sirchargly_...)config (object, optional): - baseUrl (string): Custom API base URL (default: https://api.sirchargly.com)
- timeout (number): Request timeout in milliseconds (default: 30000)
- apiVersion (string): API version (default: '2025-01')
Example:
const client = new SirChargly('sk_dev_sirchargly_your_api_key', {
timeout: 60000,
apiVersion: '2025-01'
});
Estimates Resource
Calculate convenience fee estimates before creating charges.
`client.estimates.create(params)`
Calculate a convenience fee estimate with regional compliance checking.
Parameters:
amount (number, required): Amount in cents (e.g., 10000 for $100.00)currency (string, required): Three-letter ISO currency code (e.g., 'usd')paymentMethod (string, optional): Payment method type (e.g., 'visa_credit', 'amex_credit', 'visa_debit')customerId (string, optional): Stripe customer ID for location-based complianceregionCode (string, optional): Explicit region code (e.g., 'US-CA', 'US-NY')Returns: Promise<Estimate>
Example:
const estimate = await client.estimates.create({
amount: 10000,
currency: 'usd',
regionCode: 'US-CA',
paymentMethod: 'visa_credit',
customerId: 'cus_123'
});
console.log(`Base: $${estimate.baseAmount / 100}`);
console.log(`Fee: $${estimate.fee.amount / 100}`);
console.log(`Total: $${estimate.total / 100}`);
console.log(`Compliant: ${estimate.compliance.passed}`);
if (estimate.fee.appliedRules) {
console.log('Applied rules:', estimate.fee.appliedRules);
}
Response:
{
baseAmount: 10000,
currency: 'usd',
fee: {
amount: 320,
percentage: 2.9,
flatFee: 0.30,
calculation: '($100.00 × 2.9%) + $0.30',
appliedRules: ['region_max_percentage'],
region: 'US-CA',
cardType: 'credit',
cardFunding: 'credit',
cardBrand: 'visa'
},
total: 10320,
sircharglyCut: 25,
merchantPortion: 295,
compliance: {
passed: true,
checks: ['region_rules', 'card_type_allowed'],
warnings: []
}
}
Charges Resource
Create and manage payment charges with convenience fees.
`client.charges.create(params)`
Create a new charge with automatic convenience fee calculation and compliance checking.
Parameters:
amount (number, required): Amount in centscurrency (string, required): Three-letter ISO currency codecustomer (string, required): Stripe customer IDpaymentMethod (string, required): Stripe payment method IDdescription (string, optional): Description for this chargemetadata (object, optional): Key-value pairs for additional informationReturns: Promise<Charge>
Example:
const charge = await client.charges.create({
amount: 10000,
currency: 'usd',
customer: 'cus_123',
paymentMethod: 'pm_card_visa',
description: 'Order #1234',
metadata: {
orderId: '1234',
productIds: ['prod_abc', 'prod_xyz']
}
});
console.log(`Charge ID: ${charge.id}`);
console.log(`Status: ${charge.status}`);
console.log(`Total: $${charge.total / 100}`);
console.log(`Platform billing: ${charge.platformBilling?.calculation}`);
Response:
{
id: 'ch_123456',
object: 'charge',
baseAmount: 10000,
currency: 'usd',
customer: 'cus_123',
description: 'Order #1234',
fee: {
amount: 320,
percentage: 2.9,
flatFee: 0.30,
calculation: '($100.00 × 2.9%) + $0.30',
appliedRules: ['region_max_percentage'],
region: 'US-CA',
cardType: 'credit',
cardFunding: 'credit',
cardBrand: 'visa',
cardLast4: '4242'
},
total: 10320,
sircharglyCut: 25,
merchantPortion: 295,
platformBilling: {
immediateAmount: 320,
deferredAmount: 0,
calculation: 'immediate'
},
billingMode: 'direct',
stripeChargeId: 'ch_stripe_123',
separateChargeId: null,
status: 'succeeded',
compliance: {
passed: true,
checks: ['region_rules', 'card_type_allowed'],
warnings: []
},
metadata: { orderId: '1234' }
}
`client.charges.retrieve(id)`
Retrieve a charge by ID.
Parameters:
id (string, required): Charge IDReturns: Promise<Charge>
Example:
const charge = await client.charges.retrieve('ch_123456');
console.log(`Status: ${charge.status}`);
console.log(`Amount: $${charge.baseAmount / 100}`);
`client.charges.list(params?)`
List all charges with pagination and filtering.
Parameters:
limit (number, optional): Max results to return (1-100, default: 10)starting_after (string, optional): Cursor for pagination (charge ID)created (object, optional): Filter by creation timestamp - gte (number): Return charges created on or after this timestamp
- lte (number): Return charges created on or before this timestamp
Returns: Promise<List<Charge>>
Example:
// Get 10 most recent charges
const charges = await client.charges.list({ limit: 10 });
// Get charges from last 30 days
const recentCharges = await client.charges.list({
limit: 25,
created: {
gte: Math.floor(Date.now() / 1000) - 30 * 24 * 60 * 60
}
});
// Paginate through charges
const nextPage = await client.charges.list({
limit: 10,
starting_after: charges.data[charges.data.length - 1].id
});
Subscriptions Resource
Create and manage recurring subscriptions with automatic fee line items.
`client.subscriptions.create(params)`
Create a new Stripe subscription with automatic convenience fee line item.
Parameters:
customer (string, required): Stripe customer IDpriceId (string, required): Stripe price ID for the base subscriptionmetadata (object, optional): Key-value pairs for additional informationtrialPeriodDays (number, optional): Trial period in daysReturns: Promise<Subscription>
Example:
const subscription = await client.subscriptions.create({
customer: 'cus_123',
priceId: 'price_monthly_pro',
metadata: {
planName: 'Pro Plan'
},
trialPeriodDays: 14
});
console.log(`Subscription ID: ${subscription.id}`);
console.log(`Status: ${subscription.status}`);
console.log(`Fee amount: $${subscription.fee.amount / 100}`);
Response:
{
id: 'sub_123456',
object: 'subscription',
customer: 'cus_123',
status: 'active',
items: {
data: [
{
id: 'si_123',
object: 'subscription_item',
subscription: 'sub_123456',
price: { id: 'price_monthly_pro', amount: 2000 },
quantity: 1
}
]
},
created: 1704067200,
fee: {
amount: 58,
label: 'Convenience Fee',
config: {
percentage: 2.9,
flatFee: 0.30
},
region: 'US-CA',
appliedRules: ['region_max_percentage']
},
sircharglyCut: 5,
merchantPortion: 53,
platformBilling: {
immediateAmount: 58,
deferredAmount: 0,
calculation: 'immediate'
},
compliance: {
passed: true,
checks: ['region_rules'],
warnings: []
},
metadata: { planName: 'Pro Plan' }
}
`client.subscriptions.retrieve(id)`
Retrieve a subscription by ID.
Parameters:
id (string, required): Subscription IDReturns: Promise<Subscription>
Example:
const subscription = await client.subscriptions.retrieve('sub_123456');
console.log(`Status: ${subscription.status}`);
console.log(`Customer: ${subscription.customer}`);
`client.subscriptions.update(id, params)`
Update an existing subscription.
Parameters:
id (string, required): Subscription IDparams (object, required): Update parameters - metadata (object, optional): Updated metadata
Returns: Promise<Subscription>
Example:
const subscription = await client.subscriptions.update('sub_123', {
metadata: {
upgraded: 'true',
plan: 'premium'
}
});
`client.subscriptions.cancel(id)`
Cancel an active subscription. Both the base subscription and fee line item will be canceled.
Parameters:
id (string, required): Subscription IDReturns: Promise<Subscription>
Example:
const subscription = await client.subscriptions.cancel('sub_123456');
console.log(`Subscription ${subscription.id} canceled`);
console.log(`Status: ${subscription.status}`);
Invoices Resource
Create and manage invoices with automatic fee line items.
`client.invoices.create(params)`
Create a new Stripe invoice with automatic convenience fee line item.
Parameters:
customer (string, required): Stripe customer IDamount (number, required): Base invoice amount in centsdescription (string, required): Description of the invoicedueDate (number, optional): Unix timestamp for due datemetadata (object, optional): Key-value pairs for additional informationReturns: Promise<Invoice>
Example:
const invoice = await client.invoices.create({
customer: 'cus_123',
amount: 50000,
description: 'Professional services - January 2025',
dueDate: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,
metadata: {
projectId: 'proj_456'
}
});
console.log(`Invoice ID: ${invoice.id}`);
console.log(`Base amount: $${invoice.amount / 100}`);
console.log(`Fee amount: $${invoice.fee.amount / 100}`);
Response:
{
id: 'in_123456',
object: 'invoice',
customer: 'cus_123',
amount: 50000,
status: 'draft',
created: 1704067200,
fee: {
amount: 1480,
label: 'Convenience Fee',
config: {
percentage: 2.9,
flatFee: 0.30
},
region: 'US-CA',
appliedRules: ['region_max_percentage']
},
compliance: {
passed: true,
checks: ['region_rules'],
warnings: []
},
metadata: { projectId: 'proj_456' }
}
`client.invoices.retrieve(id)`
Retrieve an invoice by ID.
Parameters:
id (string, required): Invoice IDReturns: Promise<Invoice>
Example:
const invoice = await client.invoices.retrieve('in_123456');
console.log(`Status: ${invoice.status}`);
console.log(`Customer: ${invoice.customer}`);
`client.invoices.finalize(id)`
Finalize a draft invoice, making it ready to be sent to the customer.
Parameters:
id (string, required): Invoice IDReturns: Promise<Invoice>
Example:
const invoice = await client.invoices.finalize('in_123456');
console.log(`Invoice finalized: ${invoice.id}`);
console.log(`Status: ${invoice.status}`);
`client.invoices.pay(id)`
Attempt to pay an open invoice.
Parameters:
id (string, required): Invoice IDReturns: Promise<Invoice>
Example:
const invoice = await client.invoices.pay('in_123456');
console.log(`Invoice paid: ${invoice.id}`);
console.log(`Status: ${invoice.status}`);
Configs Resource
Manage convenience fee configuration settings.
`client.configs.retrieve()`
Get current fee configuration.
Returns: Promise<Config>
Example:
const config = await client.configs.retrieve();
console.log(`Percentage: ${config.percentage}%`);
console.log(`Flat Fee: $${config.flatFee}`);
console.log(`Label: ${config.label}`);
console.log(`Billing Mode: ${config.billingMode}`);
Response:
{
percentage: 2.9,
flatFee: 0.30,
label: 'Convenience Fee',
billingMode: 'direct',
regions: {
'US-CA': {
maxPercentage: 3.0,
requiresDisclosure: true
},
'US-NY': {
maxPercentage: 4.0,
requiresDisclosure: false
}
}
}
`client.configs.update(params)`
Update fee configuration. Changes take effect immediately for new transactions.
Parameters:
percentage (number, optional): Fee percentage (e.g., 2.9 for 2.9%)flatFee (number, optional): Flat fee in dollars (e.g., 0.30 for $0.30)label (string, optional): Fee label shown on customer documentsbillingMode ('direct' | 'separate', optional): Billing modeReturns: Promise<Config>
Example:
const newConfig = await client.configs.update({
percentage: 3.0,
flatFee: 0.35,
label: 'Processing Fee',
billingMode: 'separate'
});
console.log('Configuration updated');
console.log(`New percentage: ${newConfig.percentage}%`);
console.log(`New label: ${newConfig.label}`);
Fee Configs Resource (Deprecated)
Note: This resource is deprecated. Use client.configs instead.
The feeConfigs resource provides the same functionality as configs but is maintained for backward compatibility.
`client.feeConfigs.retrieve()`
Get current fee configuration (same as client.configs.retrieve()).
`client.feeConfigs.update(params)`
Update fee configuration (same as client.configs.update()).
Webhooks Resource
Manage webhook configurations for receiving event notifications.
`client.webhooksResource.retrieve()`
Get current webhook configuration.
Returns: Promise<WebhookConfig>
Example:
const webhookConfig = await client.webhooksResource.retrieve();
console.log(`URL: ${webhookConfig.url}`);
console.log(`Enabled: ${webhookConfig.enabled}`);
console.log(`Events: ${webhookConfig.enabledEvents.join(', ')}`);
console.log(`Has secret: ${webhookConfig.hasSecret}`);
Response:
{
url: 'https://example.com/webhooks/sirchargly',
enabled: true,
enabledEvents: ['charge.succeeded', 'charge.failed', 'subscription.created'],
hasSecret: true,
failedDeliveries: 0,
lastDeliveryAttempt: '2025-01-15T10:30:00Z',
lastSuccessfulDelivery: '2025-01-15T10:30:00Z',
availableEvents: [
'charge.succeeded',
'charge.failed',
'subscription.created',
'subscription.updated',
'subscription.canceled',
'invoice.finalized',
'invoice.paid'
]
}
`client.webhooksResource.configure(params)`
Configure webhook endpoint and event subscriptions.
Parameters:
url (string, required): Webhook endpoint URLenabledEvents (string[], optional): Array of event types to subscribe toenabled (boolean, optional): Enable or disable webhook deliveryReturns: Promise<WebhookConfig & { secret?: string }>
Note: The webhook signing secret is returned only on creation/update and should be stored securely.
Example:
const config = await client.webhooksResource.configure({
url: 'https://example.com/webhooks/sirchargly',
enabledEvents: ['charge.succeeded', 'charge.failed'],
enabled: true
});
console.log('Webhook configured');
console.log(`Secret: ${config.secret}`); // Save this securely!
`client.webhooksResource.delete()`
Remove webhook configuration and stop receiving events.
Returns: Promise<{ message: string }>
Example:
const result = await client.webhooksResource.delete();
console.log(result.message); // "Webhook configuration deleted"
Merchant Resource
Get merchant account information and status.
`client.merchant.profile()`
Retrieve merchant account profile information.
Returns: Promise<MerchantProfile>
Example:
const profile = await client.merchant.profile();
console.log(`Merchant ID: ${profile.id}`);
console.log(`Name: ${profile.name}`);
console.log(`Email: ${profile.email}`);
console.log(`Status: ${profile.status}`);
console.log(`Onboarding completed: ${profile.onboardingCompleted}`);
Response:
{
id: 'mch_abc123',
email: 'merchant@example.com',
name: 'My Business Inc.',
status: 'active',
onboardingCompleted: true
}
`client.merchant.stripeStatus()`
Check Stripe Connect account connection status.
Returns: Promise<StripeStatus>
Example:
const stripeStatus = await client.merchant.stripeStatus();
if (stripeStatus.connected) {
console.log(`Connected to Stripe: ${stripeStatus.accountId}`);
} else {
console.log('Not connected to Stripe Connect');
}
Response:
{
connected: true,
accountId: 'acct_1234567890'
}
API Keys Resource
Manage API authentication keys for your merchant account.
`client.apiKeys.create(params)`
Create a new API key pair (publishable and secret keys).
Parameters:
merchantId (string, required): Merchant IDname (string, required): Descriptive name for this API keyenvironment ('development' | 'production', required): Environment for this keyReturns: Promise<ApiKeyCreateResponse>
Important: The secret key is only returned once at creation. Store it securely!
Example:
const key = await client.apiKeys.create({
merchantId: 'mch_abc123',
name: 'Production Key',
environment: 'production'
});
console.log(`Key ID: ${key.keyId}`);
console.log(`Publishable Key: ${key.publishableKey}`);
console.log(`Secret Key: ${key.secretKey}`); // Store this securely!
console.log(`Environment: ${key.environment}`);
console.log(`Created: ${key.createdAt}`);
Response:
{
success: true,
keyId: 'key_xyz789',
name: 'Production Key',
environment: 'production',
publishableKey: 'pk_prod_sirchargly_abc123',
secretKey: 'sk_prod_sirchargly_secret456', // Only shown once!
createdAt: '2025-01-18T00:00:00.000Z'
}
`client.apiKeys.delete(params)`
Delete an API key. This will immediately revoke access for the key.
Parameters:
merchantId (string, required): Merchant IDkeyId (string, required): API key ID to deleteReturns: Promise<ApiKeyDeleteResponse>
Example:
const result = await client.apiKeys.delete({
merchantId: 'mch_abc123',
keyId: 'key_xyz789'
});
console.log(result.message); // "API key deleted successfully"
Response:
{
success: true,
message: 'API key deleted successfully'
}
Audit Logs Resource
Query and analyze API activity logs for security and debugging.
`client.auditLogs.list(params?)`
List audit logs with advanced filtering and pagination, or get aggregated statistics.
Parameters:
startDate (string, optional): Filter by start date (ISO 8601 format)endDate (string, optional): Filter by end date (ISO 8601 format)action (string, optional): Filter by action (e.g., 'charge.create', 'estimate.create')resource (string, optional): Filter by resource type (e.g., 'charge', 'subscription')environment ('development' | 'production', optional): Filter by environmentipAddress (string, optional): Filter by IP addressapiKeyId (string, optional): Filter by API key IDlimit (number, optional): Max results to return (1-100, default: 50)offset (number, optional): Number of records to skip for paginationstats (boolean, optional): Return statistics instead of log entriesReturns: Promise<AuditLogListResponse | AuditLogStats>
Example - List logs:
// Get recent audit logs
const logs = await client.auditLogs.list({
action: 'charge.create',
limit: 50,
startDate: '2025-01-01T00:00:00.000Z'
});
console.log(`Total logs: ${logs.total}`);
logs.logs.forEach(log => {
console.log(`${log.timestamp}: ${log.action} - Status ${log.responseStatus}`);
});
// Paginate through results
if (logs.hasMore) {
const nextPage = await client.auditLogs.list({
limit: 50,
offset: logs.offset + logs.limit
});
}
Example - Get statistics:
// Get aggregated statistics
const stats = await client.auditLogs.list({
stats: true,
startDate: '2025-01-01T00:00:00.000Z',
endDate: '2025-01-31T23:59:59.999Z'
});
console.log(`Total Requests: ${stats.totalRequests}`);
console.log(`Successful: ${stats.successfulRequests}`);
console.log(`Failed: ${stats.failedRequests}`);
console.log(`Average Response Time: ${stats.averageResponseTime}ms`);
// Breakdown by action
Object.entries(stats.requestsByAction).forEach(([action, count]) => {
console.log(`${action}: ${count} requests`);
});
// Daily breakdown
stats.requestsByDay.forEach(day => {
console.log(`${day.date}: ${day.count} requests`);
});
Response - List:
{
logs: [
{
id: 'log_123',
merchantId: 'mch_abc',
apiKeyId: 'key_xyz',
action: 'charge.create',
resource: 'charge',
resourceId: 'ch_123',
requestBody: {
amount: 10000,
currency: 'usd'
},
responseStatus: 200,
responseBody: {
id: 'ch_123',
status: 'succeeded'
},
ipAddress: '192.168.1.1',
userAgent: 'SirChargly SDK/1.0.0',
environment: 'production',
timestamp: '2025-01-18T00:00:00.000Z',
duration: 350
}
],
total: 1234,
limit: 50,
offset: 0,
hasMore: true
}
Response - Statistics:
{
totalRequests: 1000,
successfulRequests: 950,
failedRequests: 50,
averageResponseTime: 250,
requestsByAction: {
'charge.create': 500,
'estimate.create': 300,
'config.update': 200
},
requestsByResource: {
charge: 500,
estimate: 300,
config: 200
},
requestsByDay: [
{ date: '2025-01-01', count: 50 },
{ date: '2025-01-02', count: 75 },
{ date: '2025-01-03', count: 60 }
]
}
`client.auditLogs.retrieve(id)`
Retrieve a specific audit log entry by ID for detailed inspection.
Parameters:
id (string, required): Audit log IDReturns: Promise<AuditLog>
Example:
const log = await client.auditLogs.retrieve('log_abc123');
console.log(`Action: ${log.action}`);
console.log(`Resource: ${log.resource} (${log.resourceId})`);
console.log(`Status: ${log.responseStatus}`);
console.log(`Duration: ${log.duration}ms`);
console.log(`IP: ${log.ipAddress}`);
console.log(`User Agent: ${log.userAgent}`);
// Inspect request and response
console.log('Request:', JSON.stringify(log.requestBody, null, 2));
console.log('Response:', JSON.stringify(log.responseBody, null, 2));
Response:
{
id: 'log_abc123',
merchantId: 'mch_xyz',
apiKeyId: 'key_123',
action: 'charge.create',
resource: 'charge',
resourceId: 'ch_789',
requestBody: {
amount: 10000,
currency: 'usd',
customer: 'cus_123',
paymentMethod: 'pm_card_visa'
},
responseStatus: 200,
responseBody: {
id: 'ch_789',
status: 'succeeded',
total: 10320
},
ipAddress: '192.168.1.1',
userAgent: 'SirChargly SDK/1.0.0',
environment: 'production',
timestamp: '2025-01-18T00:00:00.000Z',
duration: 350
}
Reports Resource
Retrieve fee charge reports, analytics, and summaries with filtering and pagination.
`client.reports.listFeeCharges(params?)`
List fee charges with advanced filtering options.
Parameters:
limit (number, optional): Max results to return (1-100, default: 25)starting_after (string, optional): Cursor for pagination (fee charge ID)customer (string, optional): Filter by customer IDinvoice (string, optional): Filter by invoice IDstatus ('pending' | 'succeeded' | 'refunded' | 'failed', optional): Filter by statusstartDate (string, optional): Filter by start date (ISO 8601)endDate (string, optional): Filter by end date (ISO 8601)billingMode ('direct' | 'separate', optional): Filter by billing modeenvironment ('development' | 'production', optional): Filter by environmentReturns: Promise<List<FeeCharge> & { next_cursor: string | null }>
Example:
// Get recent fee charges
const feeCharges = await client.reports.listFeeCharges({
limit: 50,
status: 'succeeded',
startDate: '2025-01-01T00:00:00Z',
endDate: '2025-01-31T23:59:59Z'
});
console.log(`Found ${feeCharges.data.length} fee charges`);
// Paginate using cursor
if (feeCharges.next_cursor) {
const nextPage = await client.reports.listFeeCharges({
limit: 50,
starting_after: feeCharges.next_cursor
});
}
// Filter by customer
const customerFees = await client.reports.listFeeCharges({
customer: 'cus_123',
billingMode: 'direct'
});
Response:
{
object: 'list',
data: [
{
id: 'fc_123456',
object: 'fee_charge',
baseAmount: 10000,
currency: 'usd',
customer: 'cus_123',
invoice: null,
fee: {
amount: 320,
percentage: 2.9,
flatFee: 0.30,
calculation: '($100.00 × 2.9%) + $0.30',
region: 'US-CA',
cardType: 'credit',
cardBrand: 'visa',
cardLast4: '4242'
},
total: 10320,
sircharglyCut: 25,
merchantPortion: 295,
billingMode: 'direct',
separateChargeId: null,
stripeChargeId: 'ch_stripe_123',
status: 'succeeded',
compliance: {
passed: true,
checks: ['region_rules'],
warnings: []
},
created: '2025-01-15T10:30:00Z',
updated: '2025-01-15T10:30:05Z'
}
],
has_more: true,
url: '/v1/reports/fees',
next_cursor: 'fc_123456'
}
`client.reports.retrieveFeeCharge(id)`
Retrieve a specific fee charge by ID.
Parameters:
id (string, required): Fee charge IDReturns: Promise<FeeCharge>
Example:
const feeCharge = await client.reports.retrieveFeeCharge('fc_123456');
console.log(`Amount: $${feeCharge.baseAmount / 100}`);
console.log(`Fee: $${feeCharge.fee.amount / 100}`);
console.log(`Status: ${feeCharge.status}`);
`client.reports.summary(params?)`
Get aggregated fee collection summary with key metrics and motivational insights.
Parameters:
startDate (string, optional): Filter by start date (ISO 8601 format)endDate (string, optional): Filter by end date (ISO 8601 format)Returns: Promise<ReportsSummary>
Example:
// Get all-time summary
const summary = await client.reports.summary();
console.log(`Total Fees Collected: $${summary.totalFeesCollected / 100}`);
console.log(`Your Portion: $${summary.merchantPortion / 100}`);
console.log(`Sir Chargly Cut: $${summary.sircharglyCut / 100}`);
console.log(`Total Transactions: ${summary.transactionCount}`);
console.log(`Average Fee per Transaction: $${summary.averageFeePerTransaction / 100}`);
console.log('\nBilling Mode Breakdown:');
console.log(` Direct: ${summary.billingModeBreakdown.direct.count} charges, $${summary.billingModeBreakdown.direct.totalFees / 100}`);
console.log(` Separate: ${summary.billingModeBreakdown.separate.count} charges, $${summary.billingModeBreakdown.separate.totalFees / 100}`);
console.log(`\n${summary.message}`); // Motivational message!
// Get summary for specific date range
const monthlySummary = await client.reports.summary({
startDate: '2025-01-01T00:00:00.000Z',
endDate: '2025-01-31T23:59:59.999Z'
});
console.log(`January Fees: $${monthlySummary.totalFeesCollected / 100}`);
console.log(`January Transactions: ${monthlySummary.transactionCount}`);
Response:
{
totalFeesCollected: 100000, // Total fees collected (in cents)
sircharglyCut: 5000, // Sir Chargly's portion (in cents)
merchantPortion: 95000, // Merchant's portion (in cents)
transactionCount: 100, // Total number of transactions
averageFeePerTransaction: 1000, // Average fee per transaction (in cents)
billingModeBreakdown: {
direct: {
count: 60, // Number of direct billing charges
totalFees: 60000 // Total fees from direct billing
},
separate: {
count: 40, // Number of separate billing charges
totalFees: 40000 // Total fees from separate billing
}
},
message: "Great work! You've earned $950.00 in convenience fees in total across 100 transactions!"
}
Regional Compliance
Note: Regional compliance is handled automatically by the Sir Chargly API.
You don't need to manually check compliance rules - the API automatically:
All responses include a compliance object:
{
compliance: {
passed: true,
checks: ['region_rules', 'card_type_allowed'],
warnings: []
}
}
If compliance fails, the warnings array will contain human-readable messages explaining the issue.
Webhook Signature Verification
Verify webhook signatures to ensure events are from Sir Chargly.
`SirChargly.webhooks.constructEvent(body, signature, secret)`
Verify and parse a webhook event.
Parameters:
body (string, required): Raw request body (do not parse JSON first)signature (string, required): Value from Sir-Chargly-Signature headersecret (string, required): Your webhook signing secretReturns: WebhookEvent
Throws: InvalidRequestError if signature is invalid
Example with Express:
import express from 'express';
import { SirChargly } from '@sirchargly/sdk';
const app = express();
app.post('/webhooks/sirchargly',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['sir-chargly-signature'] as string;
const body = req.body.toString();
try {
const event = SirChargly.webhooks.constructEvent(
body,
signature,
process.env.SIRCHARGLY_WEBHOOK_SECRET!
);
// Handle the event
switch (event.type) {
case 'charge.succeeded':
console.log('Charge succeeded:', event.data.object.id);
break;
case 'charge.failed':
console.log('Charge failed:', event.data.object.id);
break;
case 'subscription.created':
console.log('Subscription created:', event.data.object.id);
break;
case 'subscription.canceled':
console.log('Subscription canceled:', event.data.object.id);
break;
}
res.json({ received: true });
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Invalid signature');
}
}
);
Example with Next.js:
import { NextRequest } from 'next/server';
import { SirChargly } from '@sirchargly/sdk';
export async function POST(req: NextRequest) {
const signature = req.headers.get('sir-chargly-signature');
const body = await req.text();
try {
const event = SirChargly.webhooks.constructEvent(
body,
signature!,
process.env.SIRCHARGLY_WEBHOOK_SECRET!
);
// Handle event
console.log('Event type:', event.type);
return Response.json({ received: true });
} catch (err) {
return Response.json(
{ error: 'Invalid signature' },
{ status: 400 }
);
}
}
Error Handling
The SDK throws typed errors for different scenarios.
Error Types
AuthenticationError: Invalid API key (401)InvalidRequestError: Invalid parameters (400)RateLimitError: Too many requests (429)APIError: Server errors (5xx)NetworkError: Network/timeout errorsExample
import {
SirChargly,
AuthenticationError,
InvalidRequestError,
RateLimitError,
APIError,
NetworkError
} from '@sirchargly/sdk';
try {
const charge = await client.charges.create({
amount: 10000,
currency: 'usd',
customer: 'cus_123',
paymentMethod: 'pm_card_visa'
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof InvalidRequestError) {
console.error('Invalid parameters:', error.message);
console.error('Parameter:', error.param);
} else if (error instanceof RateLimitError) {
console.error('Too many requests, please retry later');
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
} else if (error instanceof APIError) {
console.error('API error:', error.message);
console.error('Status code:', error.statusCode);
}
}
Error Properties
All errors extend SirCharglyError and include:
message (string): Error messagetype (string): Error type identifiercode (string): Error codestatusCode (number): HTTP status code (if applicable)TypeScript Support
The SDK is written in TypeScript with complete type definitions.
import SirChargly, {
// Core Resources
Estimate,
Charge,
Subscription,
Invoice,
Config,
FeeCharge,
// Merchant & Authentication
MerchantProfile,
StripeStatus,
ApiKeyCreateParams,
ApiKeyCreateResponse,
ApiKeyDeleteParams,
ApiKeyDeleteResponse,
// Audit Logs
AuditLog,
AuditLogListParams,
AuditLogListResponse,
AuditLogStats,
// Reports & Analytics
ReportsSummary,
ReportsSummaryParams,
// Webhooks
WebhookEvent,
WebhookConfig,
// Errors
AuthenticationError,
InvalidRequestError,
RateLimitError,
APIError,
NetworkError
} from '@sirchargly/sdk';
const client = new SirChargly('sk_dev_sirchargly_your_api_key');
// Full type inference
const estimate: Estimate = await client.estimates.create({
amount: 10000,
currency: 'usd',
regionCode: 'US-CA'
});
// Access nested properties with autocomplete
console.log(estimate.fee.appliedRules);
console.log(estimate.compliance.passed);
// Merchant profile with full type safety
const profile: MerchantProfile = await client.merchant.profile();
console.log(profile.name);
// Audit logs with union type
const logs: AuditLogListResponse = await client.auditLogs.list({ limit: 50 });
const stats: AuditLogStats = await client.auditLogs.list({ stats: true });
// Reports summary
const summary: ReportsSummary = await client.reports.summary();
console.log(summary.merchantPortion);