Overview
The Kelviq Node SDK provides a convenient way to interact with the Kelviq REST APIs from your Node application.Installation
Install the Kelviq SDK using npm or yarn:Prerequisites
Before you can initialize the client and use the SDK methods, you need a Server API Key. You can obtain this key from the Kelviq application:- Navigate to Settings.
- Go to the API keys section.
- Copy the Server API Key.
Configuring the Client
The SDK provides a mainKelviq client class. You instantiate it directly with your configuration options.
How to Create a Client
Caching and offline resilience
Entitlement caching is enabled by default. The SDK keeps a per-process in-memory cache with a 60-second freshness window. Reads follow this order: fresh memory cache, optional distributed cache, then the Entitlement API. A successful API response refreshes both cache levels. If the API is unreachable or returns a server error, the SDK returns the last known cached entitlement response when one exists. If the customer or feature has never been cached, the original request error is thrown.enableCache: false to disable caching.
Share the cache across instances
The in-memory cache and offline reporting queue belong to one Node process and disappear when it restarts. Use the optional Redis store when multiple processes or containers need one shared, durable cache and queue.Replay queued usage
When a usage or event report fails because of a network problem, the SDK queues it and retries automatically on the next report call. You can also flush the queue explicitly:remaining is the number of reports still queued. Without Redis, the queue exists only in the current process.
See When the Entitlement API is unavailable for access-control fallback guidance.
Supported Functionalities
The SDK currently supports the following operations:- Customers
- Checkout
- Entitlements
- Reporting
- Subscriptions
- Charges
- License
- Portal
- Refunds
- Payment Methods
- Transactions
Customers
Thecustomers module allows you to manage customer records within Kelviq. You can access these operations via the customers attribute on an initialized Kelviq client instance.
Creates a new customer
Response
Response
customerId: A unique identifier for the customer that you define. This ID will be used to reference the customer in subsequent API calls.
email: The email address of the customer. Must be a valid email format.name: The name of the customer.metadata: An object of custom key-value pairs to store additional information about the customer.
CustomerResponse (TypeScript Interface), representing the newly created customer record. Key attributes include:
id: The server-generated unique UUID for the customer record.customerId: The client-provided customer identifier.name: The customer’s name.email: The customer’s email.details: Any server-added details about the customer (typically read-only).metadata: The metadata associated with the customer.createdOn: ISO 8601 timestamp of when the customer was created.modifiedOn: ISO 8601 timestamp of when the customer was last modified.
Updates an existing customer
This operation performs a partial update (PATCH), so you only need to provide the fields you want to change.Response
Response
customerId: A unique identifier for the customer that you define. This ID will be used to reference the customer in subsequent API calls.
email: The email address of the customer. Must be a valid email format.name: The name of the customer.metadata: An object of custom key-value pairs to store additional information about the customer.
CustomerResponse (TypeScript Interface), representing the updated customer record. Key attributes include:
id: The server-generated unique UUID for the customer record.customerId: The client-provided customer identifier.name: The customer’s name.email: The customer’s email.details: Any server-added details about the customer (typically read-only).metadata: The metadata associated with the customer.createdOn: ISO 8601 timestamp of when the customer was created.modifiedOn: ISO 8601 timestamp of when the customer was last modified.
Checkout
The checkout module provides functionalities for creating and managing checkout sessions. You can access these operations via the checkout attribute on an initialized Kelviq client instance. This operation creates a new checkout session for a customer, allowing them to proceed with a purchase or subscription.Response
Response
-
planIdentifier: The identifier of the specific plan the customer is checking out with. planIdentifier is mandatory. -
successUrl: The URL to which the user will be redirected after a successful checkout. -
chargePeriod: The billing cycle for the subscription. Must be one of:-
"ONE_TIME" -
"MONTHLY" -
"YEARLY" -
"WEEKLY" -
"DAILY" -
"TWENTY_EIGHT_DAYS" -
"THREE_MONTHS" -
"SIX_MONTHS"
-
-
offeringId: The ID (uuid) of the offering the customer is checking out with. -
pricingTableId: The id (uuid) of the pricing table being used for this checkout. (Considered only ifofferingIdis not provided) -
ruleId: The id (uuid) of the pricing rule being applied. (Considered only ifofferingIdis not provided) -
customerId: The ID of the customer initiating the checkout. (If not provided, a new customer will be created) -
features: A list of objects, where each object represents a feature and its desired quantity. Each object must have two keys:"identifier": The unique identifier for the feature."quantity": The desired quantity for this feature.- Example:
[{"identifier": "seats", "quantity": 10}, {"identifier": "api-calls-tier1", "quantity": 5000}]
- Example:
-
ipAddress: The IP Address of the customer, used for location based pricing. -
trialPeriod: Number of trial days to apply. Must be an integer greater than or equal to1and overrides the selected plan’s configured trial period. -
currencyCode: The currency code for the checkout session (e.g."USD"). Required whencustomAmountis provided. -
customAmount: A custom amount to charge for this checkout session. When provided,taxBehaviorandcurrencyCodeare also required. -
taxBehavior: Specifies how taxes are applied to thecustomAmount. Required whencustomAmountis provided. Must be one of:"INCLUSIVE"— Tax is included in the custom amount."EXCLUSIVE"— Tax is added on top of the custom amount.
-
discountsEnabled: Whether the discount/coupon code field is shown on the checkout page. Defaults totrue. -
lockEmail: Whentrue, the email field is pre-filled and locked so the customer cannot change it. Defaults tofalse. -
defaultBillingCountry: ISO 3166-1 alpha-2 country code (e.g."US","GB") used to pre-fill the billing address country on the checkout page. -
metadata: An object of arbitrary key-value pairs to attach to the checkout session. The keys are preserved exactly as supplied and the object is returned unchanged on thecheckout.completedwebhook’smetadatafield. Example:{ "order_ref": "ABC-123", "source": "pricing_page" }.
-
checkoutSessionId: The unique ID for the created checkout session. -
checkoutUrl: The URL that the customer should be redirected to in order to complete the payment and activate the subscription/purchase.
Entitlements
The entitlements module allows you to check and retrieve customer entitlements for various features. These operations target a specific edge API endpoint (https://edge.api.kelviq.com by default) and use the GET HTTP method with query parameters.
Checks if a specific customer has access to a particular feature.
This method directly returns a boolean indicating access status.Response
Response
-
customerId: The unique identifier for the customer. -
featureId: The unique identifier for the feature whose access is being checked.
boolean:trueif the customer has access to the specified feature (considering feature type, limits, etc.),falseotherwise or if the feature is not found in their entitlements.
Retrieves the aggregated entitlement for a specific feature for a given customer.
Response
Response
-
customerId: The unique identifier for the customer. -
featureId: The unique identifier for the feature whose access is being checked.
Entitlement object, or null if the feature is not found. If the customer has multiple subscriptions, there can be multiple raw entries for the same featureId. The SDK aggregates them and keeps raw entries in the items array. Note: resetAt is only available on individual items (not at the top level) because it can differ across subscriptions. The structure includes:
-
featureId: string -
hasAccess: boolean — For METER features, computed asremaining === null || remaining > 0. For BOOLEAN and CUSTOMIZABLE features,trueif at least one item grants access. -
featureType: string —"METER","BOOLEAN", or"CUSTOMIZABLE". -
hardLimit: boolean | null — For METER,trueif any item has a hard limit. For BOOLEAN, alwaysfalse. -
usageLimit: number | null — For METER, summed across all items. For CUSTOMIZABLE, taken from the first item. For BOOLEAN, alwaysnull. -
currentUsage: number | null — For METER, summed across all items. For CUSTOMIZABLE, taken from the first item. For BOOLEAN, always0. -
remaining: number | null — For METER, computed asusageLimit - currentUsage. For CUSTOMIZABLE, taken from the first item. For BOOLEAN, alwaysnull. -
items(EntitlementDetail[]): An array containing all raw entitlement entries for this featureId. Each item includesresetAt.
Retrieves all aggregated entitlements for a given customer.
Response
Response
customerId: The unique identifier for the customer.
Record<string, Entitlement> keyed by featureId. If the customer has multiple subscriptions, there can be multiple raw entries for the same featureId. The SDK aggregates them and keeps raw entries in the items array. Note: resetAt is only available on individual items (not at the top level) because it can differ across subscriptions. Each Entitlement value has the same structure as described in getEntitlement above.
Retrieves the raw entitlement from the API for a specific feature.
Response
Response
-
customerId: The unique identifier for the customer. -
featureId: The unique identifier for the feature.
CheckEntitlementsResponse (Object). This returns the raw API response without aggregation. The structure includes:
-
customerId: The customer’s ID. -
entitlements(EntitlementDetail[]): A list containing raw entitlement details. EachEntitlementDetailhas fields like:-
featureId: string -
hasAccess: boolean -
featureType: string -
resetAt: string -
hardLimit: boolean | null -
usageLimit: number | null -
currentUsage: number | null -
remaining: number | null
-
Retrieves all raw entitlements from the API without aggregation.
Response
Response
customerId: The unique identifier for the customer.
CheckEntitlementsResponse (Object). This returns the raw API response without aggregation. The structure includes:
-
customerId: The customer’s ID. -
entitlements(EntitlementDetail[]): A list containing raw entitlement details. EachEntitlementDetailhas fields like:-
featureId: string -
hasAccess: boolean -
featureType: string -
resetAt: string -
hardLimit: boolean | null -
usageLimit: number | null -
currentUsage: number | null -
remaining: number | null
-
Reporting
Reporting pre-aggregated usages for customer
This endpoint is used for reporting the pre-aggregated feature usage from your application (client-level) to the Kelviq application. It allows you to update the usage count for a specific feature associated with a customer.Response
Response
-
value: The usage value being reported. -
customerId: The unique identifier for the customer associated with this usage. -
featureId: The unique identifier for the feature for which usage is being reported. -
behaviourparameter dictates how the usage is updated:-
SET: This will replace the current usage value for the feature with the newvalueprovided. -
DELTA: This will increment the existing usage value for the feature by the amount specified in thevalueparameter
-
-
value: The usage value that was recorded. -
customerId: The customer ID associated with the usage. -
featureId: The feature Identifier for which usage was recorded. -
behaviour: The behaviour type (“SET” or “DELTA”) that was processed. -
orgId: The organization ID associated with this record, as determined by the server. -
eventName: An internal event name generated by the server for this usage report (e.g., “aggregated.usage”). -
idempotencyKey: A unique idempotency key generated by the server for this specific usage report instance. -
timestamp: The server-generated UTC timestamp (string format) indicating when the usage report was processed.
Subscriptions
The subscriptions module allows you to list, retrieve, create, preview updates, update, and cancel customer subscriptions. You can access these operations via thesubscriptions attribute on an initialized Kelviq client instance.
List subscriptions
Retrieves a paginated list of subscriptions for a customer.Response
Response
customerId(string): The client-defined identifier of the customer whose subscriptions will be returned.
page(number): Page number to retrieve.pageSize(number): Number of subscriptions to return per page.modifiedOnAfter(string): Only return subscriptions modified on or after this ISO 8601 timestamp.modifiedOnBefore(string): Only return subscriptions modified on or before this ISO 8601 timestamp.
PaginatedSubscriptionResponse containing count, next, previous, and a results array of SubscriptionData objects.
Retrieve a subscription
Retrieves one subscription using its Kelviq subscription ID.Response
Response
subscriptionId(string): The Kelviq UUID of the subscription.
SubscriptionData object. A missing subscription throws NotFoundError.
Create a subscription
Creates a subscription directly for a customer without requiring a checkout session.planIdentifier(string): Identifier of the plan to subscribe to.chargePeriod(ChargePeriod): By default, organizations can useMONTHLY,THREE_MONTHS,SIX_MONTHS,YEARLY, andONE_TIME. To enableDAILY,WEEKLY, orTWENTY_EIGHT_DAYS, contact hi@kelviq.com.customerId(string): Client-defined identifier of the customer.
successUrl(string): URL to redirect to after successful subscription creation.features(FeatureListItem[]): Feature identifiers and requested quantities.ipAddress(string): Customer IP address used for location-based pricing.
CreateSubscriptionResponse containing the created subscription, including its plan files, links, and issued licenses when available.
Updates an existing subscription to a new plan
Response
Response
subscriptionId: The unique identifier of the subscription to be updated.planIdentifier: The identifier of the new plan.chargePeriod: The new charging period for the subscription. Must be one of:"ONE_TIME""MONTHLY""YEARLY""WEEKLY""DAILY""TWENTY_EIGHT_DAYS""THREE_MONTHS""SIX_MONTHS"
offeringId: The ID of the new offering, if applicable.pricingTableId: The ID of the new pricing table, if applicable.ruleId: The ID of the new pricing rule, if applicable.ipAddress: The IP Address of the customer, used for location based pricing.features: An array of objects, where each object represents a feature and its desired quantity to update for the subscription. Each object must have two keys:"identifier": The unique identifier for the feature."quantity": The desired quantity for this feature.- Example:
[{"identifier": "seats", "quantity": 10}, {"identifier": "projects", "quantity": 5}]
- Example:
trialEnd(string): Controls the trial period for the updated subscription. Accepts either:- The literal string
"now"to end any active trial immediately. - An ISO 8601 datetime string (e.g.
"2027-12-31T23:59:59Z") to set a new trial end date. The datetime must be in the future. Naive datetimes (no timezone designator) are interpreted as UTC. - If omitted, the existing trial behavior on the subscription is preserved.
- The literal string
paymentBehavior(PaymentBehavior): Set toPAYMENT_BEHAVIORS.ACTIVATE_ON_PAYMENT(the value"activate_on_payment") to keep the current subscription active while payment is pending. The new plan and features are applied only after payment succeeds. If the pending update expires, the current subscription remains unchanged. Omit this field to use the default immediate-update behavior.prorationBehavior(ProrationBehavior): Controls how a mid-period change is billed. UsePRORATION_BEHAVIORS.IMMEDIATE_CHARGE,PRORATION_BEHAVIORS.PRORATE_NEXT_INVOICE, orPRORATION_BEHAVIORS.NO_PRORATION. When omitted, the organization’s default is used.
trialEnd client-side — invalid datetime strings or past datetimes throw InvalidRequestError before the request is sent.
Returns:
An instance of UpdateSubscriptionResponse, which includes:
subscriptionId(string): UUID of the updated subscription.
Preview a subscription update
Calculates the financial effect of an update without changing the subscription, creating an invoice, or charging the customer.subscriptionId, planIdentifier, and chargePeriod. Optional parameters are prorationBehavior, features, ipAddress, and trialEnd.
Returns: A SubscriptionUpdatePreviewResponse with recurring and immediate amounts in major and minor units, plus an optional next invoice and its line items.
Cancel an active subscription for a customer.
Response
Response
-
subscriptionId: The unique identifier of the subscription to be cancelled. -
cancellationType: The type of cancellation to perform. Must be one of:"IMMEDIATE": The subscription is cancelled immediately."CURRENT_PERIOD_ENDS": The subscription will remain active until the end of the current billing period and then cancel."SPECIFIC_DATE": The subscription will be cancelled on the specifiedcancellationDate.
-
cancellationDate: The specific date for cancellation ifcancellationTypeis"SPECIFIC_DATE". Must be inYYYY-MM-DDformat. This parameter is required ifcancellationTypeis"SPECIFIC_DATE".
CancelSubscriptionResponse, which includes:
message: A confirmation message indicating the result of the cancellation request.
Charges
Thecharges module immediately charges a customer’s saved payment method for a one-time plan. Use sandbox mode when testing this operation.
planIdentifier, chargePeriod: "ONE_TIME", and customerId are required. customAmount must be positive and requires currencyCode. taxBehavior accepts INCLUSIVE or EXCLUSIVE and defaults to EXCLUSIVE on the API. Optional fields also include features and ipAddress.
Returns: A CreateChargeResponse containing the charge record, amount, currency, status, product, plan, features, and customer details.
Refunds
Therefunds module allows you to list, create, and retrieve refunds for orders owned by your organization. You can access these operations via the refunds attribute on an initialized Kelviq client instance.
List refunds
Response
Response
search: Search by refund ID, order ID, customer name, email, or ID.status: Filter by refund status. One of"PENDING","PROCESSING","SUCCEEDED","FAILED","CANCELED".startDate: Include refunds created on or after this date (YYYY-MM-DD).endDate: Include refunds created on or before this date (YYYY-MM-DD).page: Page number to return.pageSize: Number of results per page. Defaults to 10, maximum 100.
RefundListResponse (TypeScript Interface) with count, next, previous, and results: RefundResponse[].
Create a refund
Response
Response
orderId: The ID of an order owned by your organization.
amountUnits: Amount to refund in the currency’s minor unit (e.g. cents for USD). Takes precedence overamountwhen both are provided.amount: Amount to refund in the currency’s major unit (e.g. dollars for USD). Used only whenamountUnitsis omitted.reason: One of"DUPLICATE","FRAUDULENT","REQUESTED_BY_CUSTOMER","OTHER". Defaults to"REQUESTED_BY_CUSTOMER".internalNote: An internal note associated with the refund.
amountUnits and amount to refund the order’s entire remaining refundable balance. The amount must be positive and cannot exceed the order’s remaining refundable balance — the SDK throws InvalidRequestError if orderId is missing, and the API rejects invalid amounts.
Returns: A RefundResponse (TypeScript Interface) with id, reason, amountUnits, amount, internalNote, failureReason, status, and the complete serialized order.
Retrieve a refund
refundId: The UUID of the refund.
RefundResponse (TypeScript Interface), as above.
Payment Methods
ThepaymentMethods module lists saved payment methods for your organization. You can access this operation via the paymentMethods attribute on an initialized Kelviq client instance.
List payment methods
Response
Response
customerId: Filter to payment methods belonging to the customer with this client-providedcustomerId.customerEmail: Filter to payment methods belonging to the customer with this email address.page: Page number to return.pageSize: Number of results per page. Defaults to 10, maximum 100.
"succeeded" are included in results.
Returns: A PaymentMethodListResponse (TypeScript Interface) with count, next, previous, and results: PaymentMethodResponse[]. Each methodData object is payment-provider-specific; for card it includes brand, last4, expMonth, expYear, funding, and country.
Transactions
Thetransactions module lists financial transactions for your organization, ordered newest first. You can access this operation via the transactions attribute on an initialized Kelviq client instance.
List transactions
Response
Response
search: Search by payment-provider IDs, customer name, email or ID, product name, or payment method type.status: Filter by transaction status. One of"success","failure","pending".startDate: Include transactions created on or after this date (YYYY-MM-DD).endDate: Include transactions created on or before this date (YYYY-MM-DD).page: Page number to return.pageSize: Number of results per page. Defaults to 10, maximum 100.
TransactionListResponse (TypeScript Interface) with count, next, previous, and results: TransactionResponse[]. Each transaction includes an itemized morFeeBreakdown (Merchant of Record fee components) when applicable — empty when no such fee applies.
License
Thelicense module allows you to activate, deactivate, and validate software licenses. You can access these operations via the license attribute on an initialized Kelviq client instance.
Activate a license key
Creates a new license instance for a given license key, optionally associating it with a customer.Response
Response
licenseKey: The license key string to activate.
customerId: The ID of the customer this instance is associated with.instanceName: A human-readable name for this instance (e.g. device name).metadata: An object of custom key-value pairs to attach to the instance.
LicenseActivateResponse, which includes:
instanceId(string): The unique ID of the newly created license instance.activatedAt(string): ISO 8601 timestamp of when the instance was activated.expiresOn(string | null): ISO 8601 timestamp of when the instance expires, if applicable.license(LicenseDetails): The full license object. Key fields:id: Server-generated UUID for the license.licenseKey: The license key string.activatedOn(string | null): ISO 8601 timestamp of when the license was first activated.expiresOn(string | null): ISO 8601 timestamp of when the license expires.activationUsage: Number of currently active instances.activationLimit: Maximum number of allowed concurrent activations.enabled: Whether the license is active.customer(object | null): The associated customer, if any. Fields:customerId,name,email.plan(object | null): The plan associated with this license, if any. Fields:identifier,name,description,version,isLatest, andproduct(object withid,identifier,name,taxCode,createdOn,modifiedOn).subscription(object | null): Subscription details, if any. Fields:id,recurrence,billingPeriodStartTime,billingPeriodEndTime,startDate,endDate,status,amount,currency,trialDaysRemaining,billingType,recurrenceUnit,recurrenceType.
Deactivate a license instance
Deactivates a specific license instance by its instance ID.Response
Response
licenseKey: The license key string.instanceId: The unique ID of the instance to deactivate.
LicenseDeactivateResponse, which includes:
message(string): Confirmation message.deactivatedAt(string): ISO 8601 timestamp of when the instance was deactivated.
Validate a license key
Checks whether a license key (and optionally a specific instance) is valid.Response
Response
licenseKey: The license key string to validate.
instanceId: If provided, also validates that this specific instance is active for the given license key.
LicenseValidateResponse, which includes:
valid(boolean): Whether the license (and instance, if provided) is valid.code(string): A short status code (e.g."VALID","INVALID","EXPIRED").detail(string): A human-readable description of the validation result.metadata(object | null): Any metadata attached to the instance, if applicable.license(LicenseDetails | null): The full license object (same structure as inactivate), ornullif not found.
Portal
The portal module allows you to create authenticated customer portal sessions. Once a session is created, you can redirect your customer directly to their self-serve customer portal without requiring them to log in manually. You can access these operations via theportal attribute on an initialized Kelviq client instance.
Creates a new customer portal session
Response
Response
customerId: The unique identifier of the customer for whom the portal session is being created.
CreatePortalSessionResponse (TypeScript Interface), which includes:
token: The session token that authenticates the customer portal session.email: The email address of the customer.customerPortalUrl: The customer’s billing portal base URL. This URL alone does not authenticate the session — append thetokenas a query parameter (${customerPortalUrl}?token=${token}) to produce the signed link you share with the customer. The token expires, so create a fresh session per visit.
Deep-linking to add a payment method
You can send a customer directly to the add payment method form and have them redirected back to your application when they’re done. Append these query parameters to the signed portal link, targeting thebilling page:
https://your-app.com/billing/done?kelviq_setup=success.
Webhooks
Kelviq can send real-time webhook notifications to your server when events occur in your account — for example, when a subscription is created or an invoice is paid.Verifying webhook signatures
Every webhook request includes three headers that you must use to verify the request is genuinely from Kelviq:
Use the
validateEvent helper to verify the signature and parse the event in one step. It throws WebhookVerificationError if the signature is invalid.
request.headers is a Headers object, not a plain object. Convert it with Object.fromEntries, and read the body with request.text() so it stays unparsed:
Webhook event types
See Webhook event types for the complete list of supported events and their descriptions.Best practices
- Return quickly — respond with a
2xxstatus before doing any heavy processing. Kelviq retries up to 3 times at 60-second intervals if it does not receive a2xx. - Use idempotency — use the
webhook-idheader (or the eventidfield) to detect and skip duplicate deliveries. - Validate every request — always verify the signature before trusting the payload.
Using the Sandbox Environment
For testing and development, you can configure the client to use the sandbox environment. This ensures that no production data is affected. To do this, set the environment option to ‘sandbox’ during client initialization.KELVIQ_ENV variable that the Kelviq CLI and MCP server also read, use environmentFromEnv(): it returns 'sandbox' when KELVIQ_ENV is unset or empty, 'production' or 'sandbox' when it is set to one of those, and throws on any other value.
The sandbox environment is completely separate from production. You will need to use a different set of API keys, and any data created (customers, subscriptions, etc.) will only exist in the sandbox.