### Install Dependencies with npm Source: https://github.com/hey-mantle/mantle-client/blob/main/TEST_README.md Run this command to install all necessary project dependencies before running tests. ```bash npm install ``` -------------------------------- ### Install Mantle API Client Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Install the Mantle App API library using npm. ```bash npm install @heymantle/client ``` -------------------------------- ### Retrieve App Installations with MantleClient Source: https://context7.com/hey-mantle/mantle-client/llms.txt Fetches a list of app installations for a customer. Initialize the client with appId and customerApiToken. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const { appInstallations } = await client.getAppInstallations(); appInstallations.forEach(install => { console.log({ appName: install.app?.name, status: install.installStatus, installedAt: install.installedAt, subscription: install.subscription?.planName }); }); ``` -------------------------------- ### Initiate Subscription Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Start the subscription process by creating a pending subscription in Mantle. Returns a confirmation URL to redirect the customer for authorization. ```javascript const { confirmationUrl } = await client.subscribe({ planId: "345", returnUrl: "https://myapp.com/charge_callback" }); ``` -------------------------------- ### getAppInstallations Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves the list of app installations for a customer across multiple apps in your Mantle account. ```APIDOC ## getAppInstallations ### Description Retrieves the list of app installations for a customer across multiple apps in your Mantle account. ### Method GET ### Endpoint /api/app-installations ### Parameters No specific parameters are required for this endpoint, it retrieves installations for the authenticated customer. ### Response #### Success Response (200) - **appInstallations** (array) - A list of app installation objects. - **app** (object) - Information about the app. - **name** (string) - The name of the app. - **installStatus** (string) - The status of the installation. - **installedAt** (Date) - The timestamp when the app was installed. - **subscription** (object) - Information about the subscription. - **planName** (string) - The name of the subscription plan. #### Response Example ```json { "appInstallations": [ { "app": { "name": "Example App" }, "installStatus": "active", "installedAt": "2024-01-10T09:00:00Z", "subscription": { "planName": "Pro Plan" } } ] } ``` ``` -------------------------------- ### GET /customer Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Fetches the details of the currently authenticated customer. ```APIDOC ## GET /customer ### Description Fetches the details of the currently authenticated customer. This endpoint requires authentication using a `customerApiToken`. ### Method GET ### Endpoint `/customer` ### Response #### Success Response (200) - **customer** (object) - An object containing the customer's details, including ID, installation status, trial information, plan, subscription, features, usage, and custom fields. ### Response Example ```json { "customer": { "id": "123", "test": false, "installedAt": "2023-10-25", "trialStartsAt": "2023-10-25", "trialExpiresAt": "2023-11-03", "plans": { "id": "345", "name": "Advanced" }, "subscription": { ... }, "features": { ... }, "usage": { ... }, "customFields": { ... } } } ``` ``` -------------------------------- ### Create a Stripe Subscription with Hosted Checkout Source: https://context7.com/hey-mantle/mantle-client/llms.txt Integrate with Stripe for subscriptions using their hosted checkout flow. This example includes options for trial periods, billing addresses, customer emails, and automatic tax calculation. ```typescript // Stripe subscription with hosted checkout const stripeSubscription = await client.subscribe({ planId: 'plan_abc123', returnUrl: 'https://myapp.com/subscription/success', billingProvider: 'stripe', hosted: true, trialDays: 14, requireBillingAddress: true, email: 'customer@example.com', automaticTax: true, metadata: { source: 'upgrade_modal', campaign: 'holiday_2024' } }); ``` -------------------------------- ### Get Checklists Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves all published checklists for the customer, useful for displaying onboarding or feature adoption progress. ```APIDOC ## getChecklists ### Description Retrieves all published checklists for the customer, useful for displaying onboarding or feature adoption progress. ### Method GET ### Endpoint /checklists ### Parameters #### Query Parameters - **handles** (array of strings) - Optional - A list of checklist handles to filter by. ### Request Example ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Get all checklists const checklists = await client.getChecklists(); checklists.forEach(checklist => { console.log(`${checklist.name}: ${checklist.completionPercentage}% complete`); console.log(`${checklist.completedSteps}/${checklist.totalSteps} steps done`); checklist.steps.forEach(step => { const status = step.completed ? 'completed' : step.skipped ? 'skipped' : 'pending'; console.log(` - ${step.name}: ${status}`); }); }); // Get specific checklists by handle const filteredChecklists = await client.getChecklists(['onboarding', 'setup-guide']); ``` ### Response #### Success Response (200) - **checklists** (array) - An array of checklist objects. - **id** (string) - The unique ID of the checklist. - **handle** (string) - The handle of the checklist. - **name** (string) - The name of the checklist. - **completionPercentage** (number) - The completion percentage of the checklist. - **completedSteps** (number) - The number of completed steps. - **totalSteps** (number) - The total number of steps. - **steps** (array) - An array of step objects. - **id** (string) - The ID of the step. - **name** (string) - The name of the step. - **completed** (boolean) - Whether the step is completed. - **skipped** (boolean) - Whether the step is skipped. - **ctaUrl** (string) - Optional - The call-to-action URL for the step. - **ctaLabel** (string) - Optional - The call-to-action label for the step. #### Response Example ```json [ { "id": "chk_123", "handle": "onboarding", "name": "Welcome Onboarding", "completionPercentage": 50, "completedSteps": 2, "totalSteps": 4, "steps": [ { "id": "step_1", "name": "Connect Store", "completed": true, "skipped": false }, { "id": "step_2", "name": "Set Up Payment", "completed": false, "skipped": false, "ctaUrl": "/payment", "ctaLabel": "Set Up" }, { "id": "step_3", "name": "Add Products", "completed": false, "skipped": true }, { "id": "step_4", "name": "Launch Store", "completed": false, "skipped": false } ] } ] ``` ``` -------------------------------- ### Get All Checklists Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves all published checklists for the customer. Can also filter by specific checklist handles. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Get all checklists const checklists = await client.getChecklists(); checklists.forEach(checklist => { console.log(`${checklist.name}: ${checklist.completionPercentage}% complete`); console.log(`${checklist.completedSteps}/${checklist.totalSteps} steps done`); checklist.steps.forEach(step => { const status = step.completed ? 'completed' : step.skipped ? 'skipped' : 'pending'; console.log(` - ${step.name}: ${status}`); }); }); // Get specific checklists by handle const filteredChecklists = await client.getChecklists(['onboarding', 'setup-guide']); ``` -------------------------------- ### Get Checklist Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves a specific checklist by ID or handle. ```APIDOC ## getChecklist ### Description Retrieves a specific checklist by ID or handle. ### Method GET ### Endpoint /checklists/{idOrHandle} ### Parameters #### Path Parameters - **idOrHandle** (string) - Required - The ID or handle of the checklist. ### Request Example ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const checklist = await client.getChecklist('onboarding'); if (checklist) { console.log(`Checklist: ${checklist.title || checklist.name}`); console.log(`Progress: ${checklist.completionPercentage}%`); const nextStep = checklist.steps.find(s => !s.completed && !s.skipped); if (nextStep) { console.log(`Next step: ${nextStep.name}`); if (nextStep.ctaUrl) { console.log(`Action: ${nextStep.ctaLabel} -> ${nextStep.ctaUrl}`); } } } ``` ### Response #### Success Response (200) - **checklist** (object) - The checklist object (structure is the same as in `getChecklists` response). #### Response Example ```json { "id": "chk_123", "handle": "onboarding", "name": "Welcome Onboarding", "completionPercentage": 50, "completedSteps": 2, "totalSteps": 4, "steps": [ { "id": "step_1", "name": "Connect Store", "completed": true, "skipped": false }, { "id": "step_2", "name": "Set Up Payment", "completed": false, "skipped": false, "ctaUrl": "/payment", "ctaLabel": "Set Up" }, { "id": "step_3", "name": "Add Products", "completed": false, "skipped": true }, { "id": "step_4", "name": "Launch Store", "completed": false, "skipped": false } ] } ``` ``` -------------------------------- ### GET /customer Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves the current customer's profile including subscription details, available plans, enabled features, usage metrics, and billing status. ```APIDOC ## GET /customer Retrieves the current customer's profile including subscription details, available plans, enabled features, usage metrics, and billing status. ### Method GET ### Endpoint /customer ### Parameters No parameters required for this endpoint. Authentication is handled via the `customerApiToken` provided during client initialization. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the customer. - **name** (string) - The name of the customer or store. - **billingStatus** (string) - The current billing status ('none' | 'active' | 'trialing' | 'canceled' | 'frozen'). - **installedAt** (string) - The timestamp when the customer was installed. - **trialExpiresAt** (string) - The timestamp when the customer's trial expires. - **platform** (string) - The customer's platform. - **myshopifyDomain** (string) - The myshopify domain for Shopify customers. - **plans** (array) - An array of available plans. - **name** (string) - The name of the plan. - **total** (number) - The total price of the plan. - **currencyCode** (string) - The currency code (e.g., 'USD'). - **trialDays** (number) - The number of trial days for the plan. - **subscription** (object) - Details about the customer's current subscription. - **plan** (object) - The plan details of the subscription. - **name** (string) - The name of the plan. - **active** (boolean) - Indicates if the subscription is active. - **currentPeriodEnd** (string) - The timestamp when the current billing period ends. - **features** (object) - An object detailing enabled features. - **name** (string) - The name of the feature. - **type** (string) - The type of the feature ('boolean' or 'limit'). - **value** (any) - The value of the feature (boolean or limit number). - **usage** (object) - An object detailing usage metrics. - **name** (string) - The name of the usage metric. - **currentValue** (number) - The current value of the metric. - **monthToDateValue** (number) - The month-to-date value of the metric. ### Request Example ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const customer = await client.getCustomer(); // Access customer properties console.log({ id: customer.id, name: customer.name, billingStatus: customer.billingStatus, // 'none' | 'active' | 'trialing' | 'canceled' | 'frozen' installedAt: customer.installedAt, trialExpiresAt: customer.trialExpiresAt, platform: customer.platform, myshopifyDomain: customer.myshopifyDomain }); // Check available plans customer.plans.forEach(plan => { console.log(`Plan: ${plan.name}, Price: ${plan.total} ${plan.currencyCode}, Trial: ${plan.trialDays} days`); }); // Check current subscription if (customer.subscription) { console.log(`Subscribed to: ${customer.subscription.plan.name}`); console.log(`Active: ${customer.subscription.active}`); console.log(`Current period ends: ${customer.subscription.currentPeriodEnd}`); } // Check enabled features Object.entries(customer.features).forEach(([key, feature]) => { console.log(`Feature ${feature.name}: ${feature.type === 'boolean' ? feature.value : `limit ${feature.value}`}`); }); // Check usage metrics Object.entries(customer.usage).forEach(([key, metric]) => { console.log(`${metric.name}: ${metric.currentValue} (MTD: ${metric.monthToDateValue})`); }); ``` ``` -------------------------------- ### Add Payment Method Source: https://context7.com/hey-mantle/mantle-client/llms.txt Starts the process for adding a new payment method for Stripe billing. Returns a SetupIntent with a client secret for Stripe.js integration. Can optionally update existing payment methods. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const setupIntent = await client.addPaymentMethod({ returnUrl: 'https://myapp.com/payment-method/success', updateExistingPaymentMethods: true // Update payment method on existing subscriptions }); // Use with Stripe.js const stripe = Stripe('pk_live_xxx'); const { error } = await stripe.confirmSetup({ clientSecret: setupIntent.clientSecret, confirmParams: { return_url: 'https://myapp.com/payment-method/success' } }); if (error) { console.error('Payment method setup failed:', error.message); } ``` -------------------------------- ### Run Tests in Watch Mode with npm Source: https://github.com/hey-mantle/mantle-client/blob/main/TEST_README.md Starts the test runner in watch mode, automatically re-running tests when file changes are detected. Ideal for active development. ```bash npm run test:watch ``` -------------------------------- ### Get Customer Profile Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieve the current customer's profile, including subscription details, available plans, enabled features, usage metrics, and billing status. Initialize the client with `customerApiToken` for browser-based requests. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const customer = await client.getCustomer(); // Access customer properties console.log({ id: customer.id, name: customer.name, billingStatus: customer.billingStatus, // 'none' | 'active' | 'trialing' | 'canceled' | 'frozen' installedAt: customer.installedAt, trialExpiresAt: customer.trialExpiresAt, platform: customer.platform, myshopifyDomain: customer.myshopifyDomain }); // Check available plans customer.plans.forEach(plan => { console.log(`Plan: ${plan.name}, Price: ${plan.total} ${plan.currencyCode}, Trial: ${plan.trialDays} days`); }); // Check current subscription if (customer.subscription) { console.log(`Subscribed to: ${customer.subscription.plan.name}`); console.log(`Active: ${customer.subscription.active}`); console.log(`Current period ends: ${customer.subscription.currentPeriodEnd}`); } // Check enabled features Object.entries(customer.features).forEach(([key, feature]) => { console.log(`Feature ${feature.name}: ${feature.type === 'boolean' ? feature.value : `limit ${feature.value}`}`); }); // Check usage metrics Object.entries(customer.usage).forEach(([key, metric]) => { console.log(`${metric.name}: ${metric.currentValue} (MTD: ${metric.monthToDateValue})`); }); ``` -------------------------------- ### Get Specific Checklist Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves a single checklist by its ID or handle. Useful for displaying progress or details of a particular checklist. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const checklist = await client.getChecklist('onboarding'); if (checklist) { console.log(`Checklist: ${checklist.title || checklist.name}`); console.log(`Progress: ${checklist.completionPercentage}%`); const nextStep = checklist.steps.find(s => !s.completed && !s.skipped); if (nextStep) { console.log(`Next step: ${nextStep.name}`); if (nextStep.ctaUrl) { console.log(`Action: ${nextStep.ctaLabel} -> ${nextStep.ctaUrl}`); } } } ``` -------------------------------- ### Get Usage Metric Report Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves a usage metric report showing values over time intervals for analytics and reporting purposes. ```APIDOC ## getUsageMetricReport ### Description Retrieves a usage metric report showing values over time intervals for analytics and reporting purposes. ### Method GET ### Endpoint /usage/metrics/{metricId} ### Parameters #### Path Parameters - **metricId** (string) - Required - The ID of the metric to retrieve (e.g., 'metric_orders'). #### Query Parameters - **period** (string) - Required - The time period for the report ('daily', 'weekly', or 'monthly'). ### Request Example ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const { report } = await client.getUsageMetricReport({ id: 'metric_orders', period: 'daily' // 'daily' | 'weekly' | 'monthly' }); console.log(`Report: ${report.startDate} to ${report.endDate}`); report.data.forEach(point => { console.log(`${point.date}: ${point.value}`); }); ``` ### Response #### Success Response (200) - **report** (object) - The usage metric report. - **startDate** (string) - The start date of the report period. - **endDate** (string) - The end date of the report period. - **data** (array) - An array of data points. - **date** (string) - The date of the data point. - **value** (number) - The value for the given date. #### Response Example ```json { "report": { "startDate": "2023-01-01", "endDate": "2023-01-31", "data": [ { "date": "2023-01-01", "value": 10 }, { "date": "2023-01-02", "value": 15 } ] } } ``` ``` -------------------------------- ### Get Invoice URL Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves the hosted invoice URL for a specific invoice, allowing customers to view and pay invoices. ```APIDOC ## getInvoiceUrl ### Description Retrieves the hosted invoice URL for a specific invoice, allowing customers to view and pay invoices. ### Method GET ### Endpoint /invoices/{invoiceId}/url ### Parameters #### Path Parameters - **invoiceId** (string) - Required - The ID of the invoice. ### Request Example ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const { url } = await client.getInvoiceUrl('inv_abc123'); // Open invoice in new tab window.open(url, '_blank'); ``` ### Response #### Success Response (200) - **url** (string) - The hosted URL for the invoice. #### Response Example ```json { "url": "https://hosted.mantle.com/invoices/inv_abc123/view?token=..." } ``` ``` -------------------------------- ### Get Usage Metric Report Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves a usage metric report for analytics. Specify the metric ID and the desired time period (daily, weekly, or monthly). ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const { report } = await client.getUsageMetricReport({ id: 'metric_orders', period: 'daily' // 'daily' | 'weekly' | 'monthly' }); console.log(`Report: ${report.startDate} to ${report.endDate}`); report.data.forEach(point => { console.log(`${point.date}: ${point.value}`); }); ``` -------------------------------- ### Get Invoice URL Source: https://context7.com/hey-mantle/mantle-client/llms.txt Retrieves the hosted invoice URL for a specific invoice. Use this to allow customers to view and pay invoices directly. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const { url } = await client.getInvoiceUrl('inv_abc123'); // Open invoice in new tab window.open(url, '_blank'); ``` -------------------------------- ### Identify Customer Source: https://context7.com/hey-mantle/mantle-client/llms.txt Register a customer with Mantle, typically the first call upon app installation. Returns an `apiToken` for subsequent authenticated requests. Supports various authentication methods including Shopify expiring access tokens and Stripe integration. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, apiKey: process.env.MANTLE_API_KEY }); // Basic Shopify customer identification const { apiToken } = await client.identify({ platform: 'shopify', platformId: shop.id, myshopifyDomain: 'example-store.myshopify.com', accessToken: shop.accessToken, name: 'Example Store', email: 'owner@example.com', customFields: { 'store_type': 'retail', 'employee_count': 50 } }); ``` ```typescript // With Shopify expiring access tokens (December 2025+) const { apiToken: customerToken } = await client.identify({ platform: 'shopify', platformId: shop.id, myshopifyDomain: shop.myshopifyDomain, accessToken: tokenResponse.access_token, refreshToken: tokenResponse.refresh_token, accessTokenExpiresAt: tokenResponse.expires_at, name: shop.name, email: shop.email }); ``` ```typescript // With Stripe as the billing provider const result = await client.identify({ platform: 'shopify', platformId: shop.id, myshopifyDomain: shop.myshopifyDomain, accessToken: shop.accessToken, name: shop.name, email: shop.email, defaultBillingProvider: 'stripe', stripeId: 'cus_existing_stripe_id', // optional, link existing Stripe customer address: { addressLine1: '123 Main St', city: 'San Francisco', state: 'CA', postalCode: '94102', country: 'US' }, contacts: [ { label: 'billing', name: 'John Doe', email: 'billing@example.com' } ] }); ``` -------------------------------- ### Create a Basic Subscription Source: https://context7.com/hey-mantle/mantle-client/llms.txt Use this to create a basic subscription for a customer to a single plan. Redirect the customer to the returned confirmation URL to authorize the charge. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Basic Shopify subscription const subscription = await client.subscribe({ planId: 'plan_abc123', returnUrl: 'https://myapp.com/subscription/callback' }); // Redirect customer to confirm if (subscription.confirmationUrl) { window.location.href = subscription.confirmationUrl; } ``` -------------------------------- ### Send Usage Event for Onboarding Step Completion Source: https://context7.com/hey-mantle/mantle-client/llms.txt Track the completion of onboarding steps to monitor user progress and identify potential drop-off points in the user journey. ```typescript // Track onboarding step completion await client.sendUsageEvent({ eventName: 'onboarding_step_completed', properties: { step: 'connect_store', time_taken_seconds: 45 } }); ``` -------------------------------- ### Initialize MantleClient Source: https://context7.com/hey-mantle/mantle-client/llms.txt Create a new MantleClient instance. Use an API key for server-side operations and a customer API token for browser-based requests. The `apiUrl` is optional and defaults to 'https://appapi.heymantle.com/v1'. ```typescript import { MantleClient } from '@heymantle/client'; // Server-side initialization with API key (never use in browser) const serverClient = new MantleClient({ appId: process.env.MANTLE_APP_ID, apiKey: process.env.MANTLE_API_KEY, apiUrl: 'https://appapi.heymantle.com/v1' // optional, defaults to this }); // Client-side initialization with customer API token const browserClient = new MantleClient({ appId: 'your-app-id', customerApiToken: 'customer-api-token-from-identify' }); ``` -------------------------------- ### Manage Affiliate Program with MantleClient Source: https://context7.com/hey-mantle/mantle-client/llms.txt APIs for managing affiliate programs, enrollments, and referrals. Initialize client with appId and customerApiToken. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Get affiliate program details const program = await client.getAffiliateProgram(); console.log(`Program: ${program.name}`); console.log(`Commission: ${program.rules.percentCommission}%`); console.log(`Duration: ${program.rules.durationMonths} months`); // Check if customer is enrolled as affiliate const affiliate = await client.getAffiliate(); if (!affiliate) { // Enroll customer as affiliate const newAffiliate = await client.enrollAffiliate({ name: 'John Doe', email: 'john@example.com', agreedToTerms: true }); console.log(`Referral link: ${newAffiliate.membership?.affiliateLink}`); console.log(`Referral code: ${newAffiliate.membership?.handle}`); } // Submit a referral request const referralRequest = await client.submitReferralRequest({ shopDomain: 'referred-shop.myshopify.com', notes: 'Met at conference', date: '2024-01-15' }); // Get affiliate referrals const { referrals, total } = await client.getAffiliateReferrals({ page: 0, limit: 25, sort: 'createdAt', sortDirection: 'desc' }); referrals.forEach(ref => { console.log(`Referral: ${ref.customerName} on ${ref.date}`); }); // Get affiliate metrics const metrics = await client.getAffiliateMetrics(); console.log({ referrals: metrics.referralCount, totalCommissions: metrics.totalCommissions, paid: metrics.commissionsPaid, outstanding: metrics.outstandingCommissions, totalSales: metrics.totalSales }); ``` -------------------------------- ### Mantle Client Initialization Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Initialize the MantleClient with your application's appId and apiKey for server-side authentication, or with a customerApiToken for client-side authentication. ```APIDOC ## Mantle Client Initialization ### Description Initialize the MantleClient with your application's `appId` and `apiKey` for server-side authentication, or with a `customerApiToken` for client-side authentication. ### Request Example ```javascript // Server-side authentication const { MantleClient } = require('@heymantle/client'); const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, apiKey: process.env.MANTLE_API_KEY, }); // Client-side authentication (using customer API token) const client = new MantleClient({ customerApiToken: shop.mantleApiToken, }); ``` ``` -------------------------------- ### POST /subscribe Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Initiates the subscription process for a customer, creating a pending subscription and returning a confirmation URL. ```APIDOC ## POST /subscribe ### Description Initiates the subscription process for a customer. This endpoint creates a pending subscription in Mantle and returns a `confirmationUrl` that the customer should be redirected to in order to authorize the charge. ### Method POST ### Endpoint `/subscribe` ### Parameters #### Request Body - **planId** (string) - Required - The ID of the plan to subscribe to. - **returnUrl** (string) - Required - The URL to redirect the customer to after subscription authorization. ### Request Example ```json { "planId": "345", "returnUrl": "https://myapp.com/charge_callback" } ``` ### Response #### Success Response (200) - **confirmationUrl** (string) - The URL for the customer to confirm the subscription charge. ``` -------------------------------- ### Retrieve Feature Limit Source: https://context7.com/hey-mantle/mantle-client/llms.txt Gets the limit for a specific feature. Returns -1 if the feature is not found, not a limit type, or unlimited. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); const productLimit = await client.limitForFeature({ featureKey: 'product_limit' }); if (productLimit === -1) { console.log('Unlimited products allowed'); } else { console.log(`Can create up to ${productLimit} products`); const remaining = productLimit - currentProductCount; console.log(`${remaining} products remaining`); } ``` -------------------------------- ### Run All Tests Once with npm Source: https://github.com/hey-mantle/mantle-client/blob/main/TEST_README.md Executes the entire test suite once. This is useful for a quick check of the codebase's current state. ```bash npm test ``` -------------------------------- ### Run Tests with UI Enabled using npm Source: https://github.com/hey-mantle/mantle-client/blob/main/TEST_README.md Launches the test runner with a graphical user interface, providing a visual way to interact with and monitor tests. ```bash npm run test:ui ``` -------------------------------- ### Run Tests with Coverage Report using npm Source: https://github.com/hey-mantle/mantle-client/blob/main/TEST_README.md Executes all tests and generates a code coverage report, detailing which parts of the codebase are exercised by the tests. ```bash npm run test:coverage ``` -------------------------------- ### MantleClient Constructor Source: https://context7.com/hey-mantle/mantle-client/llms.txt Initializes a new MantleClient instance for interacting with the Mantle API. Supports server-side initialization with an API key and client-side initialization with a customer API token. ```APIDOC ## MantleClient Constructor Creates a new MantleClient instance for interacting with the Mantle API. Use the API key for server-side operations and the customer API token for browser-based requests. ### Request Body - **appId** (string) - Required - Your Mantle application ID. - **apiKey** (string) - Optional - Your Mantle API key (for server-side use). - **customerApiToken** (string) - Optional - Customer API token obtained from the `identify` method (for client-side use). - **apiUrl** (string) - Optional - The base URL for the Mantle API. Defaults to 'https://appapi.heymantle.com/v1'. ### Request Example ```typescript import { MantleClient } from '@heymantle/client'; // Server-side initialization with API key (never use in browser) const serverClient = new MantleClient({ appId: process.env.MANTLE_APP_ID, apiKey: process.env.MANTLE_API_KEY, apiUrl: 'https://appapi.heymantle.com/v1' // optional, defaults to this }); // Client-side initialization with customer API token const browserClient = new MantleClient({ appId: 'your-app-id', customerApiToken: 'customer-api-token-from-identify' }); ``` ``` -------------------------------- ### Identify Customer with MantleClient Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Initialize the MantleClient and identify a customer using platform details and access tokens. Ensure environment variables for appId and apiKey are set. ```javascript const { MantleClient } = require('@heymantle/client'); const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, apiKey: process.env.MANTLE_API_KEY, }); const { apiToken: customerApiToken } = await client.identify({ platform: 'shopify', platformId: shop.id, myshopifyDomain: shop.myshopifyDomain, accessToken: shop.accessToken, name: shop.name, email: shop.email, customFields: { 'Custom 1': 1234, 'Custom 2': 'abc', }, }); ``` -------------------------------- ### Create a Multi-Plan Subscription Source: https://context7.com/hey-mantle/mantle-client/llms.txt Subscribe a customer to multiple plans simultaneously, such as a base plan and add-ons. An optional discount can be applied. ```typescript // Subscribe to multiple plans (base + add-ons) const multiPlanSub = await client.subscribe({ planIds: ['plan_base_123', 'plan_addon_456'], returnUrl: 'https://myapp.com/subscription/callback', discountId: 'discount_xyz' // optional discount }); ``` -------------------------------- ### Create Hosted Session Source: https://context7.com/hey-mantle/mantle-client/llms.txt Creates a hosted session URL for managing subscriptions or account settings. Supports 'plans' for plan selection and 'account' for general management. ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Create a plans selection page session const plansSession = await client.createHostedSession({ type: 'plans', config: { returnUrl: 'https://myapp.com/settings', showCurrentPlan: true } }); // Create an account management session const accountSession = await client.createHostedSession({ type: 'account', config: { returnUrl: 'https://myapp.com/settings', sections: ['billing', 'invoices', 'payment_methods'] } }); // Redirect customer to hosted page window.location.href = plansSession.url; ``` -------------------------------- ### POST /usage-event Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Pushes a usage event to Mantle for the customer. Used for usage-based billing and general event tracking. ```APIDOC ## POST /usage-event ### Description Pushes a usage event to Mantle for the customer. This can be used for usage-based billing or as a general-purpose event stream for analytics. ### Method POST ### Endpoint `/usage-event` ### Parameters #### Request Body - **eventId** (string) - Optional - An idempotency key for the event. If not provided, Mantle will generate one. - **eventName** (string) - Required - The name of the event (e.g., 'order_created', 'page_view'). - **customerId** (string) - Optional - The customer ID. Only needed if not using `customerApiToken` authentication. - **properties** (object) - Required - An object containing event-specific properties. ### Request Example ```json // Example 1: Usage-based billing event { "eventId": "unique-order-123", "eventName": "order_created", "properties": { "order_value": 150, "processed_at": "2023-10-26T10:00:00Z", "customer_name": "Peter Parker" } } // Example 2: General event tracking { "eventName": "page_view", "properties": { "path": "/products/cool-widget" } } ``` ``` -------------------------------- ### addPaymentMethod Source: https://context7.com/hey-mantle/mantle-client/llms.txt Initiates the process of adding a new payment method for Stripe billing. Returns a SetupIntent with a client secret for use with Stripe Elements. ```APIDOC ## addPaymentMethod ### Description Initiates the process of adding a new payment method for Stripe billing. Returns a SetupIntent with a client secret for use with Stripe Elements. ### Method POST ### Endpoint /payment-methods/setup ### Parameters #### Request Body - **returnUrl** (string) - Required - The URL to redirect the customer to after payment method setup. - **updateExistingPaymentMethods** (boolean) - Optional - If true, updates payment methods for existing subscriptions. ### Request Example ```json { "returnUrl": "https://myapp.com/payment-method/success", "updateExistingPaymentMethods": true } ``` ### Response #### Success Response (200) - **clientSecret** (string) - The client secret for the Stripe SetupIntent. #### Response Example ```json { "clientSecret": "seti_123abc_secret_xyz" } ``` ``` -------------------------------- ### Affiliate Program APIs Source: https://context7.com/hey-mantle/mantle-client/llms.txt APIs for managing affiliate programs, enrollments, and referral tracking. ```APIDOC ## Affiliate Program APIs ### Description Manage affiliate programs, enrollments, and referral tracking for customers who want to earn commissions by referring others. ### Endpoints #### getAffiliateProgram ##### Description Retrieves details about the affiliate program. ##### Method GET ##### Endpoint /api/affiliate/program ##### Response - **name** (string) - The name of the affiliate program. - **rules** (object) - The rules of the program. - **percentCommission** (number) - The percentage commission earned. - **durationMonths** (integer) - The duration of the commission in months. #### getAffiliate ##### Description Checks if the current customer is enrolled as an affiliate. ##### Method GET ##### Endpoint /api/affiliate ##### Response - **membership** (object) - Affiliate membership details, or null if not enrolled. - **affiliateLink** (string) - The unique referral link for the affiliate. - **handle** (string) - The unique referral code for the affiliate. #### enrollAffiliate ##### Description Enrolls the customer as an affiliate. ##### Method POST ##### Endpoint /api/affiliate/enroll ##### Parameters - **name** (string) - Required - The name of the affiliate. - **email** (string) - Required - The email address of the affiliate. - **agreedToTerms** (boolean) - Required - Indicates if the terms and conditions were agreed to. ##### Response - **membership** (object) - Affiliate membership details. - **affiliateLink** (string) - The unique referral link for the affiliate. - **handle** (string) - The unique referral code for the affiliate. #### submitReferralRequest ##### Description Submits a referral request for a new customer. ##### Method POST ##### Endpoint /api/affiliate/referrals ##### Parameters - **shopDomain** (string) - Required - The domain of the referred shop. - **notes** (string) - Optional - Additional notes about the referral. - **date** (string) - Optional - The date of the referral (YYYY-MM-DD). #### getAffiliateReferrals ##### Description Retrieves a list of affiliate referrals. ##### Method GET ##### Endpoint /api/affiliate/referrals ##### Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of referrals per page. - **sort** (string) - Optional - The field to sort by (e.g., 'createdAt'). - **sortDirection** (string) - Optional - The direction of sorting ('asc' or 'desc'). ##### Response - **referrals** (array) - A list of referral objects. - **customerName** (string) - The name of the referred customer. - **date** (string) - The date of the referral. - **total** (integer) - The total number of referrals. #### getAffiliateMetrics ##### Description Retrieves key metrics for the affiliate program. ##### Method GET ##### Endpoint /api/affiliate/metrics ##### Response - **referralCount** (integer) - The total number of referrals. - **totalCommissions** (number) - The total commissions earned. - **commissionsPaid** (number) - The total commissions paid out. - **outstandingCommissions** (number) - The amount of outstanding commissions. - **totalSales** (number) - The total sales generated through referrals. ### Example Usage (TypeScript) ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Get affiliate program details const program = await client.getAffiliateProgram(); console.log(`Program: ${program.name}`); console.log(`Commission: ${program.rules.percentCommission}%`); console.log(`Duration: ${program.rules.durationMonths} months`); // Check if customer is enrolled as affiliate const affiliate = await client.getAffiliate(); if (!affiliate) { // Enroll customer as affiliate const newAffiliate = await client.enrollAffiliate({ name: 'John Doe', email: 'john@example.com', agreedToTerms: true }); console.log(`Referral link: ${newAffiliate.membership?.affiliateLink}`); console.log(`Referral code: ${newAffiliate.membership?.handle}`); } // Submit a referral request const referralRequest = await client.submitReferralRequest({ shopDomain: 'referred-shop.myshopify.com', notes: 'Met at conference', date: '2024-01-15' }); // Get affiliate referrals const { referrals, total } = await client.getAffiliateReferrals({ page: 0, limit: 25, sort: 'createdAt', sortDirection: 'desc' }); referrals.forEach(ref => { console.log(`Referral: ${ref.customerName} on ${ref.date}`); }); // Get affiliate metrics const metrics = await client.getAffiliateMetrics(); console.log({ referrals: metrics.referralCount, totalCommissions: metrics.totalCommissions, paid: metrics.commissionsPaid, outstanding: metrics.outstandingCommissions, totalSales: metrics.totalSales }); ``` ``` -------------------------------- ### Initialize MantleClient with Customer API Token Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Initialize the MantleClient using a customer API token, typically obtained from an identify request. This method is suitable for frontend requests authenticated to a specific customer. ```javascript const client = require('@heymantle/client'); const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken, }); ``` -------------------------------- ### Fetch Customer Data Source: https://github.com/hey-mantle/mantle-client/blob/main/README.md Retrieve the current authenticated customer's details, including subscription, plan, features, usage, and custom fields. ```javascript const { customer } = await client.getCustomer(); console.log(customer) ``` -------------------------------- ### Create Hosted Session Source: https://context7.com/hey-mantle/mantle-client/llms.txt Creates a hosted session URL that redirects customers to a Mantle-hosted page for managing their subscription or account settings. ```APIDOC ## createHostedSession ### Description Creates a hosted session URL that redirects customers to a Mantle-hosted page for managing their subscription or account settings. ### Method POST ### Endpoint /hosted-sessions ### Parameters #### Request Body - **type** (string) - Required - The type of session to create ('plans' or 'account'). - **config** (object) - Required - Configuration for the hosted session. - **returnUrl** (string) - Required - The URL to redirect the customer to after the session. - **showCurrentPlan** (boolean) - Optional - Whether to show the current plan in the 'plans' session. - **sections** (array of strings) - Optional - The sections to display in the 'account' session (e.g., ['billing', 'invoices', 'payment_methods']). ### Request Example ```typescript const client = new MantleClient({ appId: process.env.MANTLE_APP_ID, customerApiToken: shop.mantleApiToken }); // Create a plans selection page session const plansSession = await client.createHostedSession({ type: 'plans', config: { returnUrl: 'https://myapp.com/settings', showCurrentPlan: true } }); // Create an account management session const accountSession = await client.createHostedSession({ type: 'account', config: { returnUrl: 'https://myapp.com/settings', sections: ['billing', 'invoices', 'payment_methods'] } }); // Redirect customer to hosted page window.location.href = plansSession.url; ``` ### Response #### Success Response (200) - **url** (string) - The URL for the hosted session. #### Response Example ```json { "url": "https://hosted.mantle.com/sessions/sess_xyz789?token=..." } ``` ```