JavaScript SDK

Lightweight client library for the Salesbooth REST API. Manage deals, customers, products, contracts, and more from any JavaScript environment.

Installation

Load the SDK via a script tag. The SDK is served from your Salesbooth instance with proper CORS and caching headers.

Script Tag
<script src="https://salesbooth.com/sdk/v1/salesbooth.js"></script>

The SDK uses a UMD wrapper and works in browsers, Node.js, and AMD environments. In a browser, it exposes a global Salesbooth object. In Node.js:

Node.js / CommonJS
const Salesbooth = require('./salesbooth.js');

Quick Start

Initialize the SDK with your API key, then start making API calls. All resource methods return Promises.

Create a deal in 3 steps
const sb = Salesbooth.init({ apiKey: 'sb_live_xxxxx' }); // 1. Create a customer const customer = await sb.customers.create({ name: 'Jane Smith', email: 'jane@example.com' }); // 2. Create a deal const deal = await sb.deals.create({ title: 'Jane Smith — Enterprise Plan', customer_id: customer.customer_id }); // 3. Add a line item await sb.deals.addItem(deal.deal_id, { product_id: 'prod_abc123', name: 'Enterprise Plan', unit_price: 499.00, quantity: 1 });

Initialization

Create a client instance with Salesbooth.init(config). The API key is required.

Full configuration
const sb = Salesbooth.init({ apiKey: 'sb_live_xxxxx', // Required. sb_live_* or sb_test_* timeout: 30000, // Request timeout in ms (default: 30000) maxRetries: 3 // Retry count for failures & rate limits (default: 3) });
OptionTypeDescription
apiKey required string Your API key. Format: sb_live_* (production) or sb_test_* (testing)
timeout number Request timeout in milliseconds. Default: 30000
maxRetries number Max retries for network errors and 429 rate limits. Uses exponential backoff. Default: 3

Available Resources

Once initialized, the client exposes the following resource objects:

PropertyDescription
sb.dealsCreate, update, and manage deals and line items
sb.customersCreate and manage customer records
sb.productsManage products and pricing
sb.contractsCreate, sign, and manage contracts
sb.webhooksSubscribe to and manage webhooks
sb.auditQuery audit trails and verify integrity
sb.discoveryDeal discovery for agent-to-agent commerce
sb.negotiationsPropose, counter, accept, and reject deal negotiations
sb.templatesManage and instantiate deal templates
sb.configurationCPQ configuration: schema, validation, pricing, and product families
sb.widgetsManage embedded deal widgets, create from templates, and get embed code

Events

The SDK emits events when resources are created or updated. Subscribe with sb.on(event, handler) and unsubscribe with sb.off(event, handler).

Listening for events
sb.on('deal.created', function(deal) { console.log('New deal:', deal.deal_id); }); // Wildcard listener — receives all events sb.on('*', function(eventName, data) { console.log(eventName, data); });
EventTrigger
deal.createdA new deal is created via sb.deals.create()
deal.updatedA deal is updated, or items are added/removed
deal.status_changedA deal transitions to a new status
deal.cancelledA deal is cancelled
deal.negotiation_proposedA negotiation proposal is submitted
deal.negotiation_counter_proposedA counter-proposal is submitted
deal.negotiation_acceptedA negotiation is accepted
deal.negotiation_rejectedA negotiation is rejected
customer.createdA new customer is created
customer.updatedA customer record is updated
contract.createdA new contract is created
contract.updatedA contract is updated
contract.signedA contract is signed
contract.activatedA contract is activated
contract.terminatedA contract is terminated
rateLimitRate limit headers received (limit, remaining, resetAt)
retryA request is being retried (attempt, retryAfter, status)

Error Handling

API errors throw a SalesboothError with structured properties. Network failures and timeouts are automatically retried up to maxRetries times with exponential backoff.

Catching errors
try { const deal = await sb.deals.get('deal_nonexistent'); } catch (err) { console.log(err.name); // 'SalesboothError' console.log(err.message); // 'Deal not found' console.log(err.code); // 'NOT_FOUND' console.log(err.status); // 404 console.log(err.details); // null or additional context }
PropertyTypeDescription
namestringAlways 'SalesboothError'
messagestringHuman-readable error message
codestringMachine-readable error code (e.g. VALIDATION_ERROR, NOT_FOUND, TIMEOUT, NETWORK_ERROR)
statusnumberHTTP status code (0 for network/timeout errors)
detailsanyAdditional error context from the API, or null

Deals

Create, update, and manage deals and their line items. Deals are the core unit of commerce — a structured deal object (SDO) containing customer, line items, pricing, and status.

sb.deals.list(options?)
List deals with optional filters.
OptionTypeDescription
limitnumberMax results to return
offsetnumberPagination offset
statusstringFilter by status: draft, in_progress, pending_signature, pending_payment, awaiting_signatures, partially_accepted, closed, cancelled, expired
customerIdstringFilter by customer ID
createdAfterstringISO date filter
createdBeforestringISO date filter
Returns Promise<{ deals, pagination }>
sb.deals.get(dealId)
Retrieve a single deal by ID.
Returns Promise<Deal>
sb.deals.create(data)
Create a new deal. Emits deal.created.
FieldTypeDescription
title requiredstringHuman-readable deal name
customer_idstringThe customer this deal belongs to (omit for widget negotiations or draft deals)
statusstringInitial status (default: draft)
metadataobjectArbitrary key-value metadata
Returns Promise<Deal>
sb.deals.update(dealId, data)
Update a deal. Emits deal.updated.
Returns Promise<Deal>
sb.deals.addItem(dealId, itemData)
Add a line item to a deal. Emits deal.updated.
FieldTypeDescription
product_id requiredstringProduct to add
name requiredstringLine item display name
unit_price requirednumberPrice per unit
quantitynumberQuantity (default: 1)
descriptionstringItem description
configurationobjectProduct-specific configuration
Returns Promise<Deal>
sb.deals.removeItem(dealId, itemId)
Remove a line item from a deal. Emits deal.updated.
Returns Promise<Deal>
sb.deals.applyDiscount(dealId, discountData)
Apply a discount to a deal. Emits deal.updated.
Returns Promise<Deal>
sb.deals.transition(dealId, status)
Transition a deal to a new status. Emits deal.status_changed.
Returns Promise<Deal>
sb.deals.close(dealId)
Shorthand for transition(dealId, 'closed').
Returns Promise<Deal>
sb.deals.cancel(dealId)
Cancel a deal. Emits deal.cancelled.
Returns Promise<Deal>
sb.deals.sign(dealId, signerInfo)
Digitally sign a deal. Emits deal.signed.
ParamTypeDescription
dealId requiredstringDeal ID to sign
signerInfoobjectSigner details (name, email, role)
Returns Promise<Deal>
sb.deals.setTerms(dealId, terms)
Set or replace the deal's terms. Emits deal.updated.
ParamTypeDescription
dealId requiredstringDeal ID
terms requiredobjectTerms object matching the deal terms schema
Returns Promise<Deal>
sb.deals.updateItem(dealId, itemId, data)
Update an existing line item on a deal. Emits deal.updated.
ParamTypeDescription
dealId requiredstringDeal ID
itemId requiredstringLine item ID to update
dataobjectFields to update: quantity, unit_price, configuration
Returns Promise<Deal>
sb.deals.partialAccept(dealId, data)
Partially accept a deal — accept specific line items while leaving others pending. Emits deal.partially_accepted.
Returns Promise<Deal>
sb.deals.createConfigured(spec, options?)
Create a fully configured deal in a single atomic call. Validates products, creates or finds a customer, adds line items, and applies discounts. Emits deal.created.
FieldTypeDescription
spec.customerobjectCustomer details { name, email, phone?, company? } — creates or finds a customer
spec.customer_idstringExisting customer ID (alternative to spec.customer)
spec.items requiredarrayLine items: [{ product_id, quantity?, configuration?, unit_price? }]
spec.discountsarrayDiscounts: [{ type, value, code? }]
spec.template_idstringTemplate ID for defaults
spec.currencystringISO 4217 currency code
spec.notesstringDeal notes
spec.metadataobjectCustom key-value metadata
options.validateOnlybooleanValidate without persisting (dry run)
Returns Promise<Deal>
sb.deals.getSettlements(dealId)
Get the revenue settlement breakdown for a closed deal. Returns all settlement records showing how the deal total was distributed among participants, including Stripe transfer IDs and USDC transaction IDs.
Returns Promise<{ settlements }>
sb.deals.verify(dealId)
Verify a deal's integrity and status — confirms the cryptographic signature chain and that all deal data is internally consistent.
Returns Promise<{ valid, checks }>
sb.deals.validTransitions(dealId)
Get the valid state transitions available for a deal given its current status. Useful before calling transition() to check which statuses are reachable.
Returns Promise<{ transitions }>

Example: Full deal lifecycle

const deal = await sb.deals.create({ customer_id: 'cust_123' }); const dealId = deal.deal_id; // Add line items await sb.deals.addItem(dealId, { product_id: 'prod_abc', quantity: 2 }); await sb.deals.addItem(dealId, { product_id: 'prod_xyz', quantity: 1 }); // Apply a discount await sb.deals.applyDiscount(dealId, { type: 'percent', value: 10 }); // Move through the pipeline await sb.deals.transition(dealId, 'in_progress'); await sb.deals.transition(dealId, 'pending_payment'); await sb.deals.close(dealId);

Customers

Create and manage customer records. Customers are linked to deals and contracts.

sb.customers.list(options?)
List customers with optional filters.
OptionTypeDescription
limitnumberMax results
offsetnumberPagination offset
statusstringFilter by status
searchstringSearch by name or email
Returns Promise<{ customers, pagination }>
sb.customers.get(customerId)
Retrieve a single customer by ID.
Returns Promise<Customer>
sb.customers.create(data)
Create a new customer. Emits customer.created.
FieldTypeDescription
name requiredstringCustomer full name
email requiredstringCustomer email
phonestringPhone number
companystringCompany name
Returns Promise<Customer>
sb.customers.update(customerId, data)
Update a customer record. Emits customer.updated.
Returns Promise<Customer>
sb.customers.delete(customerId)
Delete a customer record.
Returns Promise<void>

Products

Manage your product catalog. Products are added to deals as line items.

sb.products.list(options?)
List products with optional filters.
OptionTypeDescription
limitnumberMax results
offsetnumberPagination offset
statusstringFilter by status
typestringFilter by product type
categorystringFilter by category
searchstringSearch by product name
Returns Promise<{ products, pagination }>
sb.products.get(productId)
Retrieve a single product by ID.
Returns Promise<Product>
sb.products.create(data)
Create a new product.
Returns Promise<Product>
sb.products.update(productId, data)
Update a product.
Returns Promise<Product>
sb.products.delete(productId)
Delete a product.
Returns Promise<void>

Contracts

Create and manage contracts with e-signature support. Contracts can be generated from deals or created independently.

sb.contracts.list(options?)
List contracts with optional filters.
OptionTypeDescription
limitnumberMax results
offsetnumberPagination offset
statusstringFilter by status
customerIdstringFilter by customer
renewalTypestringFilter by renewal type
expiringSoonbooleanShow expiring contracts
Returns Promise<{ contracts, pagination }>
sb.contracts.get(contractId)
Retrieve a single contract by ID.
Returns Promise<Contract>
sb.contracts.create(data)
Create a new contract. Emits contract.created.
FieldTypeDescription
deal_idstringCreate from a deal — auto-populates customer_id, title, value, start_date, end_date
customer_id required*stringCustomer the contract belongs to
title required*stringContract title
value required*numberContract value
currencystringCurrency code (default: USD)
start_date required*stringStart date (YYYY-MM-DD)
end_date required*stringEnd date (YYYY-MM-DD)
metadataobjectArbitrary metadata
* Required unless deal_id is provided.
Returns Promise<Contract>
sb.contracts.update(contractId, data)
Update a contract. Emits contract.updated.
Returns Promise<Contract>
sb.contracts.sign(contractId, signerInfo?)
Sign a draft contract. Creates a cryptographic signature. Emits contract.signed.
Returns Promise<Contract>
sb.contracts.activate(contractId)
Activate a signed contract. Emits contract.activated.
Returns Promise<Contract>
sb.contracts.terminate(contractId)
Terminate an active contract. Emits contract.terminated.
Returns Promise<Contract>
sb.contracts.delete(contractId)
Delete a contract.
Returns Promise<void>
sb.contracts.fromDeal(dealId)
Create a contract from an existing deal. Copies the customer, value, and currency from the deal and sets a 1-year term.
Returns Promise<Contract>

Example: Deal to contract

// Create a contract directly from a closed deal const contract = await sb.contracts.fromDeal('deal_abc123'); // Sign and activate await sb.contracts.sign(contract.contract_id); await sb.contracts.activate(contract.contract_id);

Webhooks

Subscribe to real-time events. Manage webhook endpoints and view delivery history.

sb.webhooks.list(options?)
List all registered webhooks.
Returns Promise<{ webhooks, pagination }>
sb.webhooks.get(webhookId)
Retrieve a single webhook by ID.
Returns Promise<Webhook>
sb.webhooks.subscribe(data)
Register a new webhook endpoint.
FieldTypeDescription
url requiredstringEndpoint URL to receive events
events requiredarrayArray of events to subscribe to (e.g. ["deal.created"])
activebooleanWhether the webhook is active (default: true)
Returns Promise<Webhook>
sb.webhooks.update(webhookId, data)
Update a webhook.
Returns Promise<Webhook>
sb.webhooks.unsubscribe(webhookId)
Delete a webhook.
Returns Promise<void>
sb.webhooks.rotateSecret(webhookId)
Rotate the signing secret for a webhook. Returns the new secret.
Returns Promise<{ secret }>
sb.webhooks.deliveries(webhookId, options?)
View delivery history for a webhook, including HTTP status codes and response times.
OptionTypeDescription
limitnumberMax results
offsetnumberPagination offset
statusstringFilter by delivery status
eventTypestringFilter by event type
Returns Promise<{ deliveries, pagination }>
sb.webhooks.create(data)
Create a new webhook subscription.
FieldTypeDescription
url requiredstringEndpoint URL to receive events
events requiredarrayArray of event types to subscribe to
descriptionstringHuman-readable description
activebooleanWhether active on creation (default: true)
Returns Promise<Webhook>
sb.webhooks.delete(webhookId, options?)
Delete a webhook subscription. Sends If-Match header automatically from the cached ETag.
OptionTypeDescription
versionnumberOverride the ETag version
Returns Promise<void>
sb.webhooks.test(webhookId, eventType)
Send a test event to the webhook URL to verify the endpoint is reachable and handling events correctly.
ParamTypeDescription
webhookId requiredstringWebhook ID
eventType requiredstringEvent type to simulate, e.g. deal.created
Returns Promise<{ delivery_id, status, response_code }>
sb.webhooks.getDeliveries(webhookId, options?)
Return paginated delivery history for a webhook. Equivalent to deliveries() with camelCase naming.
OptionTypeDescription
limitnumberMax results
offsetnumberPagination offset
statusstringFilter by delivery status
eventTypestringFilter by event type
Returns Promise<{ deliveries, pagination }>
sb.webhooks.verifySignature(payload, signature, secret, timestamp?, options?)
Verify a webhook payload signature (HMAC-SHA256). Convenience instance method — delegates to the module-level Salesbooth.verifyWebhookSignature().
ParamTypeDescription
payload requiredstringRaw request body as a string
signature requiredstringX-Salesbooth-Signature header value
secret requiredstringWebhook signing secret
timestampstring | numberX-Salesbooth-Timestamp header value
options.tolerancenumberMax age in seconds (default: 300)
Returns boolean
sb.webhooks.getDeadLetter(params?)
List dead-letter queue entries — failed deliveries that exceeded the retry limit and were not successfully delivered.
OptionTypeDescription
event_typestringFilter by event type
webhook_idstringFilter by webhook
limitnumberMax results
offsetnumberPagination offset
Returns Promise<{ entries, pagination }>
sb.webhooks.getEvents(params?)
List webhook event records with optional filters. Useful for auditing which events have been dispatched.
OptionTypeDescription
since_sequencenumberReturn events after this sequence number
since_timestampstringReturn events after this ISO timestamp
event_typestringFilter by event type
statusstringFilter by status
limitnumberMax results
Returns Promise<{ events, pagination }>
sb.webhooks.replay(data)
Replay webhook events — re-dispatch matching events to all active subscriptions. Use to recover from missed deliveries.
FieldTypeDescription
webhook_idstringReplay only to this webhook
since_sequencenumberReplay events from this sequence number
since_timestampstringReplay events since this ISO timestamp
event_typestringReplay only this event type
Returns Promise<{ queued }>
sb.webhooks.retry(deliveryId)
Retry a specific failed webhook delivery by its delivery ID.
Returns Promise<{ delivery_id, status }>
sb.webhooks.cleanup(options?)
Clean up stale webhook data — removes processed events and old delivery records beyond the retention window.
OptionTypeDescription
retention_daysnumberKeep records newer than this many days
batch_sizenumberMax records to delete per call
Returns Promise<{ deleted }>

Audit

Every entity has an immutable, cryptographically chained audit trail. Query and verify the integrity of audit logs.

sb.audit.list(entityType, entityId, options?)
Retrieve the audit trail for an entity.
ParamTypeDescription
entityType requiredstringdeal, contract, customer, or product
entityId requiredstringThe entity identifier
options.limitnumberMax results
options.offsetnumberPagination offset
Returns Promise<{ entries, pagination }>
sb.audit.verify(entityType, entityId)
Verify the cryptographic hash chain integrity of an entity's audit trail. Returns whether all entries are intact and untampered.
Returns Promise<{ valid, entries_checked }>

Example

// Get audit trail for a deal const trail = await sb.audit.list('deal', 'deal_abc123'); // Verify the chain hasn't been tampered with const result = await sb.audit.verify('deal', 'deal_abc123'); console.log(result.valid); // true

Discovery

Deal discovery for agent-to-agent commerce. Browse available deals and products by category, price range, and payment terms.

sb.discovery.discover(options?)
Browse discoverable deals.
OptionTypeDescription
categorystringFilter by category
minPricenumberMinimum price
maxPricenumberMaximum price
currencystringCurrency code
pricingModelstringFilter by pricing model
paymentTermsstringFilter by payment terms
limitnumberMax results
offsetnumberPagination offset
Returns Promise<{ deals, pagination }>
sb.discovery.schema()
Get the discovery schema — available categories, pricing models, and filter options.
Returns Promise<DiscoverySchema>

Negotiations

Propose, counter, accept, or reject deal negotiations. Includes AI-powered negotiation intelligence.

sb.negotiations.history(dealId)
Get the full negotiation history for a deal.
Returns Promise<{ negotiations }>
sb.negotiations.propose(dealId, data)
Submit a negotiation proposal. Emits deal.negotiation_proposed.
Returns Promise<Negotiation>
sb.negotiations.counter(dealId, data)
Submit a counter-proposal. Emits deal.negotiation_counter_proposed.
Returns Promise<Negotiation>
sb.negotiations.accept(dealId)
Accept the current negotiation. Emits deal.negotiation_accepted.
Returns Promise<Negotiation>
sb.negotiations.reject(dealId, reason?)
Reject the current negotiation with an optional reason. Emits deal.negotiation_rejected.
Returns Promise<Negotiation>
sb.negotiations.intelligence(dealId)
Get AI-powered negotiation intelligence for a deal — suggested strategies, BATNA analysis, and optimal pricing.
Returns Promise<NegotiationIntelligence>
sb.negotiations.suggest(dealId, currentTerms?)
Request an AI-generated negotiation suggestion based on current terms. Returns proposed counter-terms with reasoning. Emits negotiation.suggestion_generated.
ParamTypeDescription
dealId requiredstringDeal ID
currentTermsobjectCurrent terms snapshot. If omitted, terms are pulled from the deal.
Returns Promise<NegotiationSuggestion>

Example: Agent-to-agent negotiation

// Buyer agent discovers available deals const available = await sb.discovery.discover({ category: 'consulting', maxPrice: 5000 }); // Get intelligence before negotiating const intel = await sb.negotiations.intelligence(dealId); // Submit a proposal await sb.negotiations.propose(dealId, { proposed_value: 3500, message: 'Proposing volume discount for recurring engagement.' }); // Seller agent counters await sb.negotiations.counter(dealId, { proposed_value: 4200, message: 'Can do 4200 with 30-day payment terms.' }); // Accept the terms await sb.negotiations.accept(dealId);

Templates

Create reusable deal templates to standardize your sales process. Instantiate templates to create pre-configured deals.

sb.templates.list(options?)
List deal templates.
OptionTypeDescription
statusstringFilter by status
categorystringFilter by category
searchstringSearch templates
limitnumberMax results
offsetnumberPagination offset
Returns Promise<{ templates, pagination }>
sb.templates.get(templateId)
Retrieve a single template by ID.
Returns Promise<Template>
sb.templates.create(data)
Create a new deal template.
Returns Promise<Template>
sb.templates.update(templateId, data)
Update a template.
Returns Promise<Template>
sb.templates.delete(templateId)
Delete a template.
Returns Promise<void>
sb.templates.instantiate(templateId, data)
Create a new deal from a template. Pass customer-specific overrides.
Returns Promise<Deal>
sb.templates.versions(templateId)
List all versions of a template. Every update creates a new immutable version.
Returns Promise<{ versions }>
sb.templates.getVersion(templateId, versionNumber)
Retrieve the full content of a specific template version.
Returns Promise<TemplateVersion>
sb.templates.rollback(templateId, versionNumber)
Roll a template back to a specific previous version. Creates a new version with the rolled-back content.
Returns Promise<Template>
sb.templates.diff(templateId, fromVersion, toVersion)
Return a structured diff between two template versions.
ParamTypeDescription
templateId requiredstringTemplate ID
fromVersion requirednumberOlder version number
toVersion requirednumberNewer version number
Returns Promise<{ from, to, diff }>

Example

// Create a deal from a template const deal = await sb.templates.instantiate('tmpl_abc123', { customer_id: 'cust_xyz', metadata: { source: 'ai_agent' } });

Configuration (CPQ)

Programmatic product configuration for AI agent deal building. Get product schemas, validate configurations, calculate pricing with bundle discounts, and browse product families.

sb.configuration.getSchema(productId)
Get the full configuration schema for a product — option groups, compatibility rules, and bundle pricing rules in one call.
Returns Promise<{ product_id, options, compatibility_rules, bundle_rules }>
sb.configuration.validate(productId, optionIds)
Validate a set of selected option IDs against compatibility and bundle rules. Returns validation result with errors, warnings, and qualifying bundles.
ParamTypeDescription
productId requiredstringProduct ID
optionIds requiredstring[]Array of selected option IDs
Returns Promise<{ valid, errors, warnings, qualifying_bundles, price_adjustments }>
sb.configuration.price(productId, optionIds)
Calculate the full price breakdown for a configuration, including base price, option modifiers, and bundle discounts.
Returns Promise<{ product_id, valid, errors, warnings, pricing }>
sb.configuration.families(options?)
List product families.
OptionTypeDescription
statusstringFilter by status
searchstringSearch families
limitnumberMax results
offsetnumberPagination offset
Returns Promise<{ families, pagination }>
sb.configuration.family(familyId)
Retrieve a single product family by ID.
Returns Promise<{ family }>
sb.configuration.familyProducts(familyId, options?)
Get all products in a product family.
Returns Promise<{ family_id, products, pagination }>

Example: Agent-Driven Product Configuration

// 1. Get the schema to understand available options const schema = await sb.configuration.getSchema('prod_abc123'); // 2. Select options and validate the configuration const optionIds = ['opt_walnut', 'opt_large', 'opt_led']; const validation = await sb.configuration.validate('prod_abc123', optionIds); if (!validation.valid) { console.log('Errors:', validation.errors); } // 3. Get the price breakdown const pricing = await sb.configuration.price('prod_abc123', optionIds); console.log('Total:', pricing.pricing.total);

Widgets

Manage embeddable widget configurations. Widgets power the client-facing deal checkout flow and can be auto-configured from products or created from templates.

sb.widgets.list(options?)
List widget configurations for the tenant.
OptionTypeDescription
limitnumberMax results
offsetnumberPagination offset
Returns Promise<{ widgets, pagination }>
sb.widgets.get(widgetId)
Retrieve a single widget configuration by ID.
Returns Promise<Widget>
sb.widgets.create(data)
Create a new widget configuration.
Returns Promise<Widget>
sb.widgets.update(widgetId, data)
Update a widget configuration.
Returns Promise<Widget>
sb.widgets.delete(widgetId)
Delete a widget configuration.
Returns Promise<void>
sb.widgets.autoConfigure(productIds)
Automatically generate a widget configuration optimised for the given products. The service inspects product schemas, pricing, and option groups to produce a ready-to-embed config.
ParamTypeDescription
productIds requiredstring[]Array of product IDs to configure the widget for
Returns Promise<Widget>
sb.widgets.createFromTemplate(templateId, siteId, overrides?)
Create a widget by cloning a saved widget template and attaching it to a site.
ParamTypeDescription
templateId requiredstringWidget template ID to clone
siteId requiredstringSite ID to attach the widget to
overridesobjectConfig overrides applied on top of the template defaults
Returns Promise<Widget>
sb.widgets.getEmbedCode(widgetId)
Get the ready-to-paste HTML embed code snippet for a widget.
Returns Promise<{ embed_code, widget_id }>
sb.widgets.validateDiscount(widgetId, code, subtotal)
Validate a promo code before deal creation. Requires a publishable key (sb_pub_...) — safe to call from the browser. Returns discount details if valid.
ParamTypeDescription
widgetId requiredstringWidget identifier
code requiredstringPromo code to validate
subtotal requirednumberCurrent order subtotal (used to calculate discount amount)
Returns Promise<{ valid, discount: { type, value, code, description, amount } }>
sb.widgets.generateContract(widgetId, data)
Generate contract HTML from the widget's contract template. Substitutes deal data into the template and creates a draft contract record. Requires a publishable key.
FieldTypeDescription
data.deal_id requiredstringDeal ID to generate the contract for
data.customer_namestringCustomer name for template substitution
data.customer_emailstringCustomer email for template substitution
Returns Promise<{ contract_id, content_html, template_name, key_terms }>
sb.widgets.signContract(widgetId, contractId, data)
Record a digital signature for a widget-generated contract. Transitions the contract to signed status and records a deal signature. Requires a publishable key.
Param / FieldTypeDescription
contractId requiredstringContract ID to sign
data.deal_id requiredstringDeal ID associated with this contract
data.signer_name requiredstringFull name of the signing party
data.signer_emailstringEmail of the signing party
Returns Promise<{ contract_id, contract_status, signature_id, signed_at, verification_hash }>
sb.widgets.getIntelligence(widgetId, options?)
Get aggregated widget intelligence data for product ordering and social proof. Returns privacy-safe metadata used by the widget to show popular badges, most-chosen option defaults, and price anchoring. Results are cached with a 15-minute TTL. Requires a publishable key.
OptionTypeDescription
productsstringComma-separated product IDs to get intelligence for
Returns Promise<{ products, option_defaults, price_context, score_context, thresholds }>

Example: Auto-configure and embed a widget

// 1. Auto-configure a widget for your products const widget = await sb.widgets.autoConfigure(['prod_abc', 'prod_xyz']); // 2. Get the embed code const { embed_code } = await sb.widgets.getEmbedCode(widget.widget_id); // 3. Inject into your page document.getElementById('checkout').innerHTML = embed_code;

Batch Operations

Execute up to 25 operations in a single request. Batch operations are transactional — all succeed or all fail.

Example: Create customer + deal + line item in one request
const result = await sb.batch([ { method: 'POST', resource: 'customers', body: { name: 'Acme Corp', email: 'billing@acme.com' } }, { method: 'POST', resource: 'deals', body: { customer_id: '$batch.0.customer_id' } }, { method: 'POST', resource: 'deals', id: '$batch.1.deal_id', action: 'add_item', body: { product_id: 'prod_abc', quantity: 1 } } ]);
FieldTypeDescription
method requiredstringGET, POST, PATCH, or DELETE
resource requiredstringResource name: deals, customers, products, etc.
idstringResource ID (for operations on existing entities)
actionstringAction to perform (e.g. add_item, sign)
bodyobjectRequest body

Webhook Verification

Verify incoming webhook signatures to ensure requests are authentic. Salesbooth signs webhook payloads with HMAC-SHA256 and includes a timestamp to prevent replay attacks.

Headers sent with each webhook

X-Salesbooth-SignatureHMAC-SHA256 signature in format v1=hexdigest
X-Salesbooth-TimestampUnix timestamp (seconds) when the webhook was sent

Synchronous (Node.js)

const isValid = Salesbooth.verifyWebhookSignature( rawBody, // Request body as string signature, // X-Salesbooth-Signature header webhookSecret, // Your webhook secret (whsec_...) timestamp, // X-Salesbooth-Timestamp header { tolerance: 300 } // Optional: max age in seconds (default: 300) );

Async (Node.js + Browsers)

const isValid = await Salesbooth.verifyWebhookSignatureAsync( rawBody, signature, webhookSecret, timestamp, { tolerance: 300 } );

Express.js example

const express = require('express'); const Salesbooth = require('./salesbooth.js'); const app = express(); app.post('/webhooks/salesbooth', express.raw({ type: 'application/json' }), function(req, res) { const sig = req.headers['x-salesbooth-signature']; const ts = req.headers['x-salesbooth-timestamp']; if (!Salesbooth.verifyWebhookSignature(req.body, sig, process.env.WEBHOOK_SECRET, ts)) { return res.status(401).json({ error: 'Invalid signature' }); } const event = JSON.parse(req.body); console.log('Received:', event.type); res.status(200).json({ received: true }); } );

TypeScript

The SDK ships with full TypeScript definitions. Load the type definitions from the same path as the SDK.

Available at
https://salesbooth.com/sdk/v1/salesbooth.d.ts
Usage with reference directive
/// <reference path="./salesbooth.d.ts" /> const sb = Salesbooth.init({ apiKey: 'sb_test_xxxxx' }); // Full type safety on all resources const deals: Salesbooth.DealListResult = await sb.deals.list({ status: 'in_progress', limit: 10 });

The type definitions include interfaces for all resources, options, and response types: Deal, Customer, Product, Contract, DealListOptions, SalesboothConfig, SalesboothEvent, and more.

Deal Widget

A drop-in web component that embeds a deal creation form on any page. Uses Shadow DOM for style isolation. No build step required.

Basic usage
<!-- Load the SDK first, then the widget --> <script src="https://salesbooth.com/sdk/v1/salesbooth.js"></script> <script src="https://salesbooth.com/sdk/v1/salesbooth-widget.js"></script> <!-- Place the widget anywhere on your page --> <salesbooth-deal api-key="sb_live_xxxxx" ></salesbooth-deal>

The widget renders a 2-step wizard: customer information, then product selection. When the form is submitted, it creates a customer, creates a deal, and adds the selected line items automatically.

Widget Attributes

Configure the widget with HTML attributes.

AttributeTypeDescription
api-key required string Your Salesbooth API key
products string Comma-separated product IDs to display. If omitted, shows all active products.
title string Widget title. Default: "Create a Deal"
theme-color string Primary color for buttons and accents. Any valid CSS color. Default: #2563eb
currency string Currency code for price formatting. Default: USD
Showing specific products with custom title
<salesbooth-deal api-key="sb_live_xxxxx" products="prod_abc, prod_xyz" title="Get a Quote" currency="EUR" ></salesbooth-deal>

Widget Theming

Customize the widget appearance with the theme-color attribute. The widget uses Shadow DOM, so your page styles won't interfere with it.

Custom theme color
<salesbooth-deal api-key="sb_live_xxxxx" theme-color="#059669" ></salesbooth-deal>

Default theme values

PropertyDefault
primaryColor#2563eb
backgroundColor#ffffff
textColor#1f2937
borderColor#e5e7eb
borderRadius8px
fontSize14px

Widget Events

Listen for events on the widget element to react to deal creation.

Handling the deal-created event
const widget = document.querySelector('salesbooth-deal'); widget.addEventListener('deal-created', function(e) { console.log('Deal ID:', e.detail.dealId); console.log('Customer ID:', e.detail.customerId); // Redirect, show confirmation, etc. window.location.href = '/thank-you?deal=' + e.detail.dealId; });
EventDetailDescription
deal-created { dealId, customerId } Fires when the deal is successfully created with all line items added.

© 2026 Salesbooth. REST API Docs · OpenAPI Spec