npm package: @fluid-commerce/fairshare
Description: FairShare attribution SDK
Latest version: 1.1.29

# FairShare SDK

> A powerful JavaScript SDK for seamlessly integrating FairShare e-commerce features into your website.

## Table of Contents
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Concepts](#core-concepts)
- [Configuration](#configuration)
- [Features](#features)
  - [Globals](#globals)
  - [Cart](#cart)
  - [Chat](#chat)
  - [Banner](#banner)
- [TypeScript Support](#typescript-support)
- [Troubleshooting](#troubleshooting)

## Installation

```bash
npm install @fluid-commerce/fairshare

> If you need widgets and ui, see the [Full Widgets Documentation](../packages/widgets).

```

## Quick Start

```javascript
import FluidSDK from '@fluid-commerce/fairshare';

// Initialize the SDK
FluidSDK.initialize({
  apiUrlHost: "https://api.yourcompany.com", // Your API endpoint URL
  fluid_shop: "yourcompany.fluid.app"        // Your shop identifier
});

// Access SDK features
const cart = FluidSDK.cart();
const chat = FluidSDK.chat();
```

## Core Concepts

The FairShare SDK provides four main components to enhance your e-commerce site:

1. **Cart** - Shopping cart functionality with multiple display options
2. **Chat** - Customer support chat integration
3. **Banner** - Promotional banners and notifications
4. **Globals** - Cross-cutting configurations like language, country, and affiliate tracking

## Configuration

The SDK requires two key parameters:

1. `fluid_shop` - Your Fluid shop identifier (always your Fluid subdomain, e.g., `yourcompany.fluid.app`)
2. `apiUrlHost` - Your API endpoint URL (can be your Fluid subdomain URL or a custom domain)

Example: A shop might have `fluid_shop` of `danphe.fluid.app` but use either `https://danphe.fluid.app` or `https://danphe.net` (custom domain) as the `apiUrlHost`.

## Configuration Options in Detail

You can customize the SDK behavior by providing a configuration object during initialization. Here's what each option controls:

```javascript
FluidSDK.initialize({
  // Required parameters
  apiUrlHost: "https://api.yourcompany.com", // API endpoint URL (can be custom domain)
  fluid_shop: "yourcompany.fluid.app",       // Shop identifier (always your Fluid subdomain)
  
  // Optional parameters
  debug: false,  // When true, logs detailed SDK operations to console for troubleshooting
  
  featureConfig: {
    // Cart configuration
    cart: {
      show: true,               // Controls whether cart functionality is enabled at all
      flavor: 'drawer',         // How the cart appears:
                                //   'drawer' - Slides in from side of screen
                                //   'icon' - Shows as an icon with count
                                //   'none' - No visual cart but API still available
      selector: '#cart-count'   // CSS selector for DOM element to update with cart count
    },
    
    // Customer support chat configuration
    chat: {
      show: true,               // Controls whether chat widget is enabled
      name: 'Support',          // Display name for the support agent in chat
      preview: 'Need help?',    // Text that appears in the collapsed chat bubble
      color: '#4A90E2'          // Primary color for chat interface (buttons, headers)
    },
    
    // Promotional banner configuration
    banner: {
      show: true,               // Controls whether banners can be displayed
      text: 'Special Offer!',   // Default banner text
      buttonText: 'Shop Now',   // Default call-to-action button text
      backgroundColor: '#ff0000' // Background color of the banner
                                // Banner can be updated later via banner.update()
    },
  },
  // Affiliate tracking configuration
  affiliate: {
    autodetect: 'bestmatch',  // How to detect affiliate referrals:
                              //   'subdomain' - Look for affiliate in subdomain (affiliate.yourshop.com)
                              //   'path' - Look in URL path (/affiliate/username)
                              //   'bestmatch' - Try subdomain first, then path
                              //   'none' - Disable automatic detection

    // Manual affiliate configuration (optional, overrides autodetect):
    // username: 'john.doe',  // Affiliate's username
    // id: '123'              // Affiliate's unique ID
    // share_guid: 'abc'      // Affiliate's shareable guid
  }
});
```

> **Note:** If you're migrating from an older version, `FluidSDK.getInstance().initialize()` is still supported for backward compatibility.

## Features

### Globals

The globals module provides access to company-wide settings and user context.

```javascript
const globals = FluidSDK.global();

// Available Properties
console.log(globals.company);      // Company information including name, logo URL, support contact
console.log(globals.country);      // Current country code (e.g., 'US') - affects shipping, pricing, taxes
console.log(globals.language);     // Current language code (e.g., 'en') - affects text localization
console.log(globals.affiliate);    // Current affiliate information if any affiliate is being tracked

// Update methods
globals.changeCountry('CA');       // Switch to Canadian storefront (affects pricing, shipping options, taxes)
globals.changeLanguage('fr');      // Switch to French language (changes UI text if translations available)
```

### Cart

The cart module handles shopping cart functionality.

```javascript
const cart = FluidSDK.cart();

// Check cart state
console.log(cart.config);          // Cart configuration object (same as passed during initialization)
console.log(cart.state);           // Current cart state - can be:
                                   //   'loading' - Cart is in process of updating
                                   //   'ready' - Cart is ready to use
                                   //   'error' - Cart encountered an error (check console for details)
console.log(cart.data);            // Complete cart data including:
                                   //   items - Array of items in cart
                                   //   totals - Price breakdowns (subtotal, tax, shipping, etc.)
                                   //   shipping - Selected shipping method
                                   //   discounts - Applied discount codes

// Create a new cart
await cart.new({
  items: [
    { variant_id: 123, quantity: 2 }
  ]
});

// Add items to cart
await cart.add([
  { variant_id: 456, quantity: 1 }
]);

// Update item quantity
await cart.updateQuantity({
  variant_id: 123,
  quantity: 3,
  item_id: 123 // item to remove
});

// Remove item from cart
await cart.removeItem(123); // Pass id of item to remove

// Subscription Management
await cart.enableSubscription(123);     // Enable subscription for product
await cart.disableSubscription(123);    // Disable subscription for product

// Apply discount code
await cart.addDiscount('SUMMER20');  // Returns error if code is invalid or expired

// Update shipping address
await cart.updateAddress({
  name: 'Jane Smith',
  address1: '123 Main St',
  city: 'Boston',
  state: 'MA',
  postal_code: '02108',
  country_code: 'US'
});

// Update language/country
await cart.updateLanguage('es');
await cart.updateCountry('US');

// Update payment method
await cart.updatePaymentMethod({
  token: 'payment_token',
  last_four: '1111',
  card_type: 'visa',
  exp_month: '12',
  exp_year: '27'
});

// Update shipping method
await cart.updateShippingMethod({ id: 'shipping_method_id' });

// Display cart count in DOM element
cart.renderCount('#cart-count');

// Enrollment in special programs
await cart.enrollment(123);  // Pass enrollment_pack_id - used for special offers, 
                             // memberships, bundles, or subscription packages

// Remove items from cart
await cart.removeItems([{ variant_id: 123},{ variant_id: 456}]);
```

## Binding Add to Cart to DOM Elements

The Cart SDK automatically binds to DOM elements with specific data attributes to enable add-to-cart functionality. 
No additional JavaScript is required - just add the appropriate HTML markup.

### Modern Usage (Recommended)
```html
<!-- Add to Cart Button -->
<div data-fluid-checkout-group data-variant="123">
  <button name="trigger">Add to Cart</button>
  <input name="quantity" type="number" value="1" />
</div>

<!-- Add to Cart Button (Multiple Items) -->
<div data-fluid-checkout-group data-variant="1,2,3,4">
  <button name="trigger">Add to Cart</button>
  <input name="quantity" type="number" value="1" />
</div>

<!-- Add to Cart With Enrollment -->
<div data-fluid-checkout-group data-enrollment-pack="789">
  <button name="trigger">Add to Cart</button>
</div>

<!-- Add to Cart With Subscription -->
<div data-fluid-checkout-group data-variant="123">
  <button name="trigger">Add to Cart</button>
  <input name="quantity" type="number" value="1" />
  <input name="subscription" type="radio" value="subscription" />
</div>
```

### Legacy Usage (Deprecated)
```html
<!-- Simple Add to Cart Button -->
<button 
  data-fluid-checkout-group-id="123"
  data-variant="123"
>Add to Cart</button>

<!--Add to Cart Button (Multiple Item) -->
<button 
  data-fluid-checkout-group-id="1,2,3"
  data-variant="1,2,3"
>Add to Cart</button>

<!-- Add to Cart with Enrollment -->
<button 
  data-fluid-checkout-group-id="123"
  data-enrollment-pack-id="789"
>Add to Cart</button>
```

Note: While legacy data-fluid-checkout-group-id is still supported, we recommend using the modern container-based approach with data-fluid-checkout-group for better organization and flexibility.

## TypeScript Support

The SDK includes TypeScript definitions for improved development experience:

```typescript
import FluidSDK from '@fluid-commerce/fairshare';
import type { FluidConfig, CartItem } from '@fluid-commerce/fairshare';

// Type-safe configuration
const config: FluidConfig = {
  apiUrlHost: 'https://api.yourcompany.com',
  fluid_shop: 'yourcompany.fluid.app',
  debug: true,
  config: {
    cart: {
      show: true,
      flavor: 'drawer'
    }
  }
};

FluidSDK.initialize(config);

// Type-safe cart operations
const items: CartItem[] = [
  { variant_id: 123, quantity: 1 }
];

const cart = FluidSDK.cart();
await cart.add(items);
```

## Troubleshooting

Common issues and solutions:

1. **Initialization Errors**
  - Ensure your `apiUrlHost` and `fluid_shop` are correctly configured
  - The `fluid_shop` must be your Fluid subdomain (e.g., `yourcompany.fluid.app`)
  - The `apiUrlHost` can be either your Fluid URL or a custom domain that points to your shop
  - Check browser console for detailed error messages when `debug: true`
  - Initialization must occur before any feature methods are called

2 **API Connection Issues**
  - Check your network tab for failed requests and error codes
  - Ensure CORS is properly configured on your API server
  - Verify your site is using HTTPS if your API requires secure connections
  - Check if there are any network firewalls blocking API calls
  - 
For additional help, contact our support team