### Get products in JavaScript Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Fetches all available products. Returns an array of product objects with details like id, displayName, description, and metadata. ```javascript const products = await stiggClient.getProducts(); ``` -------------------------------- ### Estimate subscription JSON response example Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Example JSON response from subscription cost estimation including total amounts, subtotal values, billing period ranges, discount information, and proration details with credit and debit amounts. ```json { "total": { "amount": 10, "currency": "USD" }, "subTotal": { "amount": 10, "currency": "USD" }, "billingPeriodRange": { "start": "2022-10-26T00:00:00.000Z", "end": "2022-11-26T00:00:00.000Z" }, "discount": { "type": "PERCENTAGE", "value": 50, "durationType": "REPEATING", "durationInMonths": 3 }, "proration": { "credit": { "amount": 0, "currency": "USD" }, "debit": { "amount": 10, "currency": "USD" }, "netAmount": { "amount": 10, "currency": "USD" }, "prorationDate": "2022-10-26T00:00:00.000Z" }, "subscription": { "total": { "amount": 10, "currency": "USD" }, "subTotal": { "amount": 20, "currency": "USD" } } } ``` -------------------------------- ### Install Stigg Go SDK using go get Source: https://docs.stigg.io/api-and-sdks/integration/backend/go Installs the Stigg Go SDK as a dependency in your Go project using the go get command. No additional dependencies are required. Run this in your terminal before importing the SDK. ```shell go get github.com/stiggio/api-client-go/v3 ``` -------------------------------- ### Install Stigg Node.js SDK Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs This shell command installs the @stigg/node-server-sdk package as a dependency in your Node.js project using npm. It requires Node.js and npm to be installed on your system. After installation, the SDK can be imported and used in your application. ```shell npm install @stigg/node-server-sdk ``` -------------------------------- ### Customer Provisioning Response in JSON Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs This JSON example shows the response structure from the Stigg provisionCustomer operation. It includes customer details, experiment info, subscription decision strategy, and the created subscription object. The response indicates successful provisioning with optional subscription creation. ```json { "customer": { "id": "customer-test-id", "experimentInfo": { "name": "should we use freemium?", "id": "should-we-use-freemium", "groupName": "Variant group", "groupType": "VARIANT", } }, "subscriptionDecisionStrategy": "REQUESTED_PLAN", "subscription": { "id": "subscription-plan-basic-ed5dac", "planId": "plan-basic", "status": "ACTIVE", "addons": [], "addonIds": [], "customerId": "customer-test-id", "metadata": null, "price": null, "pricingType": "FREE", "resource": { "id": "resource-01", }, } } ``` -------------------------------- ### Initialize Stigg SDK and provision customer Source: https://docs.stigg.io/guides/quick-start-guides/provisioning-customers Demonstrates how to initialize the Stigg server SDK and provision customers with optional subscription parameters. Includes basic initialization and customer creation with plans, plus advanced usage for experiment exclusion. ```typescript import Stigg from '@stigg/node-server-sdk'; const stiggClient = await Stigg.initialize({ apiKey: 'YOUR_SERVER_API_KEY' }); export default stiggClient; ``` ```typescript const customer = await stiggClient.provisionCustomer({ customerId: 'test-customer-id', name: 'John Doe', email: 'john@example.com', subscriptionParams: { planId: 'plan-basic' } }); ``` ```typescript const customer = await stiggClient.provisionCustomer({ customerId: 'test-customer-id', name: 'John Doe', email: 'john@example.com', excludeFromExperiment: true, subscriptionParams: { planId: 'plan-basic' } }); ``` -------------------------------- ### Initialize Stigg client in Go Source: https://docs.stigg.io/api-and-sdks/integration/backend/go Imports the Stigg SDK, defines a helper Ptr function, reads the server API key from the environment, and creates a new Stigg client instance. The client is ready for subsequent API calls. ```go import ( "context" "github.com/stiggio/api-client-go/v3" "os" ) // Ptr is a helper function that returns a pointer to whatever // value we pass to it, will be widely used in the examples below func Ptr[T any](v T) *T { return &v } func main() { apiKey := os.Getenv("STIGG_SERVER_API_KEY") client := stigg.NewStiggClient(apiKey, nil, nil) // client is initialized } ``` -------------------------------- ### Get Customer Data via JavaScript Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs This snippet shows how to retrieve data for a specific customer using the Stigg JavaScript client. It requires a customer ID as input and returns customer details. ```javascript const customer = await stiggClient.getCustomer('customer-demo-01'); ``` -------------------------------- ### Handle payment required response with failed payment Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Example of a JSON response when a payment collection fails due to insufficient funds. This structure includes error details and a payment URL for retrying the payment. ```json { "status": "Success", "subscription": { "paymentCollection": "FAILED", "latestInvoice": { "paymentUrl": "https...", "errorMessage": "no sufficient funds" } } } ``` -------------------------------- ### GET /customers/{customerId} Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Retrieves detailed information about a specific customer, including ID, name, email, timestamps, payment status, entitlements, and metadata. No additional parameters are required beyond the customer ID. ```APIDOC ## GET /customers/{customerId} ### Description Fetches the full data for a customer by their ID, including demographic info, payment method status, promotional entitlements, and custom metadata. ### Method GET ### Endpoint /customers/{customerId} ### Parameters #### Path Parameters - **customerId** (string) - Required - The unique identifier of the customer. ### Request Example No request body required for GET. ### Response #### Success Response (200) - **id** (string) - The customer ID. - **name** (string) - The customer's name. - **email** (string) - The customer's email address. - **createdAt** (string) - ISO timestamp of creation. - **updatedAt** (string) - ISO timestamp of last update. - **hasPaymentMethod** (boolean) - Indicates if the customer has a payment method. - **promotionalEntitlements** (array) - List of promotional entitlements. - **metadata** (object) - Custom metadata key-value pairs. #### Response Example { "id": "customer-demo-01", "name": "Test Name", "email": "john@example.com", "createdAt": "2022-09-20T09:59:22.324Z", "updatedAt": "2022-09-20T10:00:32.750Z", "hasPaymentMethod": false, "promotionalEntitlements": [], "metadata": { "lorem": "ipsum" } } ``` -------------------------------- ### POST /preview-subscription Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Preview subscription pricing details including discounts, proration, and billing period information. Returns detailed breakdown of subscription costs before actual subscription creation. ```APIDOC ## POST /preview-subscription ### Description Preview subscription pricing details including discounts, proration, and billing period information. Returns detailed breakdown of subscription costs before actual subscription creation. ### Method POST ### Endpoint /preview-subscription ### Parameters #### Request Body - **discount** (object) - Optional - Discount configuration with type, value, duration and period details - **billingPeriodRange** (object) - Optional - Billing period start and end dates - **proration** (object) - Optional - Proration details including credit, debit and net amounts ### Request Example { "discount": { "type": "PERCENTAGE", "value": 50, "durationType": "REPEATING", "durationInMonths": 3 }, "billingPeriodRange": { "start": "2022-10-26T00:00:00.000Z", "end": "2022-11-26T00:00:00.000Z" } } ### Response #### Success Response (200) - **total** (object) - Total amount after discounts and taxes with currency - **subTotal** (object) - Total before any discount or exclusive tax with currency - **billingPeriodRange** (object) - Billing period start and end dates - **discount** (object) - Applied discount details - **proration** (object) - Proration details including credit, debit and net amounts #### Response Example { "total": { "amount": 2.5, "currency": "USD" }, "subTotal": { "amount": 5, "currency": "USD" }, "billingPeriodRange": { "start": "2022-10-26T00:00:00.000Z", "end": "2022-11-26T00:00:00.000Z" }, "discount": { "type": "PERCENTAGE", "value": 50, "durationType": "REPEATING", "durationInMonths": 3 }, "proration": { "credit": { "amount": -9.99, "currency": "USD" }, "debit": { "amount": 14.99, "currency": "USD" }, "netAmount": { "amount": 5, "currency": "USD" }, "prorationDate": "2022-10-26T00:00:00.000Z" } } ``` -------------------------------- ### Get Paywall Data - JavaScript Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Retrieves paywall data using the stiggClient.getPaywall() method. This is useful for rendering public pricing pages or customer paywalls. The expected output is a JSON object containing plan details. ```javascript const paywallData = await stiggClient.getPaywall(); ``` -------------------------------- ### Get Customer Entitlements (JavaScript) Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs This snippet illustrates how to retrieve all entitlements for a specified customer using the Stigg.io client. It iterates through the returned entitlements and logs each one to the console, providing a means to inspect the customer's access to various features. ```JavaScript const entitlements = await stiggClient.getEntitlements( 'customer-demo-01', 'resource-01', // optional, required for multiple subscription for same product ); // all the entitlements the customer is entitled to entitlements.forEach((entitlement) => { console.log(JSON.stringify(entitlement)); }); ``` -------------------------------- ### Initialize Stigg Server SDK (TypeScript) Source: https://docs.stigg.io/guides/quick-start-guides/creating-subscriptions Sets up the Stigg server SDK instance using your server API key. This instance should be initialized once per process and reused throughout your application. It provides the client used for subsequent subscription operations. ```TypeScript import Stigg from '@stigg/node-server-sdk'; const stiggClient = await Stigg.initialize({ apiKey: 'YOUR_SERVER_API_KEY' }); export default stiggClient; ``` -------------------------------- ### Provision Customer using Stigg SDK in JavaScript Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs This code snippet demonstrates provisioning a new customer in Stigg using the JavaScript SDK. It requires the stiggClient instance and accepts optional parameters for subscriptions, billing info, and metadata. The function returns a promise resolving to customer and subscription objects. ```javascript const customer = await stiggClient.provisionCustomer({ customerId: 'customer-test-id', name: 'My very first customer', // optional email: 'john@example.com', // optional - billing email address couponId: 'coupon-test-id', // optional subscriptionParams: { // optional - pass null to skip initial subscription planId: 'plan-basic', resourceId: 'resource-01', // optional, required for multiple subscription for same product billableFeatures: [{ // optional, required for subscriptions with per unit pricing featureId:'feature-01-templates', quantity: 2 }], billingPeriod: 'MONTHLY', // optional, relevant only for paid subscriptions addons: [{ // optional addonId: 'addon-extra-stuff', quantity: 1, }], promotionCode: 'STIGG30', // optional billingCountryCode:'DK', // optional, required for price localization, must be in the ISO-3166-1 format metadata: { // optional key: 'value', }, billingInformation: { taxPercentage: 17,// optional. taxRate will be created if not exists } }, billingInfo: { // optional language: 'en', timezone: 'America/New_York', customerName: "The name of the customer for the billing provider", billingAddress: { country: 'US', // must be in the ISO-3166-1 format city: 'New York', state: 'NY', addressLine1: '123 Main Street', addressLine2: 'Apt. 1', phoneNumber: '+1 212-499-5321', postalCode: '10164', }, shippingAddress: { country: 'US', // must be in the ISO-3166-1 format city: 'New York', state: 'NY', addressLine1: '123 Main Street', addressLine2: 'Apt. 1', phoneNumber: '+1 212-499-5321', postalCode: '10164', }, taxIds: [ { type: "au_abn", value: "12345678912" }, { type: "us_ein", value: "12-3456789" } ], invoiceCustomFields: { lorem: "ipsum", acme: "co" }, paymentMethodId: "pm_1LcBMDAnAO1PFouUusJSmaPu", currency: "usd", metadata: { // optional - metadata that will be stored in the billing solution hello: "world" } }, metadata: { // optional - metadata that will be stored in Stigg key: "value", } }); ``` -------------------------------- ### Implement Dual-Write for Customer and Subscription Provisioning in Node.js Source: https://docs.stigg.io/guides/i-want-to/migrate-from-legacy-systems This code snippet demonstrates how to register a new customer and subscribe them to a plan by performing operations in both the legacy system and Stigg. It uses async functions to create customers and subscriptions, ensuring the customer is provisioned before the subscription if needed. Dependencies include the Stigg SDK (stigg client); inputs are customer and plan objects; outputs are updated records in both systems; limitations include handling only creation, not updates or errors explicitly. ```javascript // e.g. billing-service.ts export async function registerCustomer(customer) { // Legacy system await createCustomerLegacy(customer); // New system await ensureCustomerInStigg(customer); } export async function subscribeToPlan(customer, plan) { // Legacy system await createSubscriptionLegacy(customer, plan); // New system await ensureSubscriptionInStigg(customer, plan); } async function ensureCustomerInStigg(customer) { await stigg.provisionCustomer({ customerId: customer.id, ...}); // Enrolled flag to keep track of which customers were already provisioned customer.enrolled = true; } async function ensureSubscriptionInStigg(customer, plan){ if (!customer.enrolled) { await ensureCustomerInStigg(customer); } await stigg.provisionSubscription({ customerId: customer.id, planId: plan.id, ...}); } ``` -------------------------------- ### Estimate subscription cost with JavaScript Source: https://docs.stigg.io/api-and-sdks/integration/backend/nodejs Estimates subscription costs before payment using the Stigg client. Requires customer ID, plan ID, and billing period. Optional parameters include billable features, addons, billing information, promotion codes, start date, billing country code, and resource ID for multi-subscription products. ```javascript // increment usage of a metered feature await stiggClient.estimateSubscription({ customerId: "customer-demo-01", billingPeriod: "MONTHLY", planId: "plan-revvenu-growth", billableFeatures: [{ // optional, required for plans with per unit pricing featureId:'feature-01-templates', quantity: 2 }], addons: [{ // optional addonId: 'addon-10-campaigns', quantity: 1 }], billingInformation: { // optional taxRateIds: [ "txr_1LcTSRE1gVT2zwZV07MIRKdf", "txr_1LcTSRE1gVT2zwZV07MIRKdf" ], taxPerentage: 17,// optional. taxRate will be created if not exists }, promotionCode: "STIGG50", // optional startDate: new Date(), // optional billingCountryCode: 'US' // optional, required for price localization, must be in the ISO-3166-1 format resourceId: 'resource-01', // optional, required for multiple subscription for same product }); ``` -------------------------------- ### Initialize Stigg SDK (Python) Source: https://docs.stigg.io/api-and-sdks/integration/backend/sidecar Demonstrates initializing the Stigg SDK in Python. The code shows how to configure the SDK with an API key, local sidecar settings (using Redis), and remote sidecar host and port. This setup is suitable for development and testing, with production relying on environment variables for remote sidecar configuration. ```Python from stigg_sidecar_sdk import Stigg, ApiConfig, LocalSidecarConfig, RedisOptions stigg = Stigg( ApiConfig( api_key="", ), # For development purposes, configure local sidecar to use redis: local_sidecar_config=LocalSidecarConfig( redis=RedisOptions( environment_prefix="development", host="localhost", port=6379, db=0 ) ), # For production use, provide remote sidecar with the REDIS_* env vars: remote_sidecar_host='localhost', remote_sidecar_port=80 ) ```