UNPKG

@shop-moso/whitelabel-extension-sdk

Version:
381 lines (286 loc) • 8.86 kB
# Moso SDK Integration Guide for Chrome Extensions ## šŸ“‹ Table of Contents 1. [Overview](#overview) 2. [Quick Start](#quick-start) 3. [Installation](#installation) 4. [Configuration](#configuration) 5. [Implementation](#implementation) 6. [API Reference](#api-reference) 7. [Advanced Features](#advanced-features) 8. [Troubleshooting](#troubleshooting) 9. [Examples](#examples) ## šŸŽÆ Overview The Moso SDK provides a complete solution for integrating crypto rewards and merchant checkout functionality into Chrome extensions. The SDK is built with a modular architecture that separates background and content script functionality to ensure optimal performance and compatibility. ### Key Features - **Authentication & User Management**: Secure wallet-based authentication - **Merchant Checkout Popup**: Automatic popup on supported merchant pages - **Google Search Enhancement**: Merchant rewards display on search results - **Background Services**: Token management and message handling - **Floating Popup UI**: Customizable extension popup interface - **Analytics**: Built-in event tracking and user identification ## šŸš€ Quick Start ### Prerequisites - Chrome Extension Manifest V3 - Valid Moso API credentials - Webpack or similar bundler for building ### šŸ“¦ Install The NPM Package ```bash npm install @shop-moso/whitelabel-extension-sdk # or yarn add @shop-moso/whitelabel-extension-sdk # or pnpm add @shop-moso/whitelabel-extension-sdk ``` ### SDK Structure This SDK is structured to separate background functionality from content scripts, allowing for efficient loading and execution in Chrome extensions. ``` sdk/ ā”œā”€ā”€ background/ │ └── index.js # Background-only functionality └── scripts/ └── index.js # Content script functionality ``` ## āš™ļø Configuration ### MosoConfig ```typescript interface MosoConfig { mosoApiUrl: string; // Moso GraphQL API URL walletAddress: string; // User's wallet address encryptionKey: string; // 32-byte encryption key encryptionIv: string; // 16-byte initialization vector referralCode?: string; // Optional Moso referral code whitelabelName: string; // Moso whitelabel name mosoTokenId: number; // Moso token ID mosoTokenName: string; // Moso token name } ``` ### MosoSDKOptions ```typescript interface ImageConfig { url: string; width?: CSSProperties["width"]; height?: CSSProperties["height"]; } interface MosoSDKOptions { enableGoogleSearch?: boolean; // Enable Google search enhancement enableMerchantCheckout?: boolean; // Enable merchant checkout popup customStyles?: { primaryColor?: string; secondaryColor?: string; backgroundColor?: string; }; images?: { checkoutBackgroundImage?: ImageConfig; // Background image for checkout popup checkoutLogoImage?: ImageConfig; // Logo image for checkout popup sideBtnExtensionImageUrl?: string; // Side button extension image URL searchBrowserImage?: ImageConfig; // Search browser image }; } ``` ## šŸ”§ Implementation ### Extension example #### 1. Manifest Configuration ```json { "manifest_version": 3, "name": "Your Extension", "version": "1.0.0", "permissions": ["storage", "tabs", "activeTab"], "host_permissions": ["<all_urls>"], "background": { "service_worker": "dist/background.js" // Reference to the }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["dist/content.js"] // Reference to the content script } ], "action": { "default_popup": "popup/index.html" }, "web_accessible_resources": [ { "resources": ["assets/*.png", "assets/*.svg"], // List of images used in the extension "matches": ["<all_urls>"] } ] } ``` #### 2. Background Script ```javascript // in your background.js import { initMosoBackground } from "@shop-moso/whitelabel-extension-sdk/sdk/background"; initMosoBackground(); ``` #### 3. Content Script ```javascript // in your content.js import { initMoso } from "@shop-moso/whitelabel-extension-sdk/sdk/scripts"; const config = { mosoApiUrl: "https://api-stg.shopmoso.com/graphql", walletAddress: "0x...", encryptionKey: "your-key", encryptionIv: "your-iv", referralCode: "YOUR_REFERRAL_CODE", // optional whitelabelName: "WhiteLabel Name", mosoTokenId: 12345, // Your Moso token ID mosoTokenName: "Your Token Name", }; const options = { enableMerchantCheckout: true, enableGoogleSearch: true, images: { checkoutBackgroundImage: { url: chrome.runtime.getURL("./assets/checkout-bg.png"), }, checkoutLogoImage: { url: chrome.runtime.getURL("./assets/checkout-logo.svg"), width: "125px", }, searchBrowserImage: { url: chrome.runtime.getURL("./assets/google-search-icon.png"), }, sideBtnExtensionImageUrl: chrome.runtime.getURL( "./assets/extension-tab.png" ), }, }; initMoso(config, options); ``` ### Custom Implementation ```javascript // Custom content script with conditional loading import { initMoso, initCheckoutOnMerchantPage, } from "@shop-moso/whitelabel-extension-sdk/sdk/scripts"; // Only initialize on merchant pages if (window.location.hostname.includes("amazon.com")) { const config = { /* ... */ }; const options = { enableMerchantCheckout: true }; initMoso(config, options); } ``` ### React Integration ```jsx import { useAuth, useSettingsManager, } from "@shop-moso/whitelabel-extension-sdk/sdk/scripts"; function MyComponent() { const { isAuthenticated, login } = useAuth(); const settingsManager = useSettingsManager(); const handleSettingsUpdate = async () => { await settingsManager.updateEmailActivations(true); }; return ( <div> {!isAuthenticated ? ( <button onClick={login}>Login</button> ) : ( <button onClick={handleSettingsUpdate}>Update Settings</button> )} </div> ); } ``` ## šŸ“š API Reference ### Core Functions #### `initMoso(config?, options?)` Main SDK initialization function. ```typescript await initMoso(config, options); ``` #### `initMosoBackground()` Initialize background services. ```typescript initMosoBackground(); ``` #### `useAuth()` React hook for authentication state. ```typescript const { isAuthenticated, login, logout, address } = useAuth(); ``` ### Content Script Functions #### `initCheckoutOnMerchantPage()` Initialize merchant checkout popup. ```typescript initCheckoutOnMerchantPage(); ``` #### `initMerchantIconOnGoogleSearch()` Initialize Google search enhancement. ```typescript initMerchantIconOnGoogleSearch(); ``` ### Conditional Feature Loading ```typescript const options = { enableMerchantCheckout: true, // Enable merchant checkout popup enableGoogleSearch: false, // Disable Google search }; ``` ### Background Message Handling The background script automatically handles these messages: - `setDeprecatedMerchant` - `getDeprecatedMerchants` - `deleteDeprecatedMerchant` - `setActivatedMerchant` - `getActivatedMerchants` - `deleteActivatedMerchant` - `setTokens` - `getTokens` ### Storage Management The SDK automatically manages: - Access tokens (chrome.storage.local) - User settings (chrome.storage.local) - Session data (chrome.storage.session) - Country detection (chrome.storage.local) ## šŸ› Troubleshooting ### Common Issues #### 1. "Service worker registration failed" **Cause**: Background script contains DOM-dependent code **Solution**: Ensure background script only imports from `@shop-moso/whitelabel-extension-sdk/sdk/background` #### 2. "document is not defined" **Cause**: Content script code running in background context **Solution**: Verify proper SDK separation and imports #### 3. Popup not appearing on merchant pages **Cause**: `enableMerchantCheckout` disabled or merchant not supported **Solution**: Check options and verify merchant is in supported list #### 4. GraphQL errors **Cause**: Invalid API endpoint or authentication **Solution**: Verify `GRAPHQL_API_URL` and access token #### 5. Build errors **Cause**: Missing dependencies or configuration **Solution**: Run `npm install` and check webpack configuration ### Debug Mode Enable debug logging: ```typescript const options = { debug: true, // ... other options }; ``` ### Console Logs The SDK provides detailed console logging: - Authentication status - Token management - Merchant detection - API calls - Error messages ### Network Tab Monitor these requests: - GraphQL API calls - Token storage operations - Analytics events ## šŸ“ž Support ### Getting Help - **Documentation**: This guide and SDK README - **Issues**: Check existing GitHub issues - **Contact**: Reach out to the Moso team ### Version Compatibility - **Chrome**: 88+ (Manifest V3) - **Node.js**: 16+ - **React**: 18+ (if using React components)