Skip to content

SDK Methods

Complete reference for all ExtensionLogin SDK methods.

Creating a Client

ExtensionLogin(apiKey, options?)

Create an ExtensionLogin client instance.

javascript
import ExtensionLogin from 'extensionlogin';

const extLogin = ExtensionLogin('el_live_xxxxxx');

// With options
const extLogin = ExtensionLogin('el_live_xxxxxx', {
  apiUrl: 'https://api.extensionlogin.com/v1',
  trialDays: 7
});

Parameters:

ParameterTypeDefaultDescription
apiKeystringRequiredYour ExtensionLogin API key
options.apiUrlstringProduction URLAPI endpoint (for self-hosted)
options.trialDaysnumber7Number of days for free trials

Returns: ExtensionLoginClient


Background Service

startBackground()

Initialize the SDK in a background service worker. Must be called once when the extension starts.

javascript
// background.js
import ExtensionLogin from 'extensionlogin';

const extLogin = ExtensionLogin('el_live_xxxxxx');
extLogin.startBackground();

Returns: Promise<void>

What it does:

  • Records installation date if not already set
  • Sets up storage change listeners for events
  • Sets up message handlers for cross-context communication

User Methods

getUser()

Get the current user's status.

javascript
const user = await extLogin.getUser();

Returns: Promise<ExtensionLoginUser | null>

typescript
interface ExtensionLoginUser {
  id: string;
  email: string;
  name: string | null;
  paid: boolean;
  paidAt: Date | null;
  subscriptionStatus: 'active' | 'past_due' | 'canceled' | 'none';
  subscriptionCancelAt: Date | null;
  plan: ExtensionLoginPlan | null;
  installedAt: Date;
  trialStartedAt: Date | null;
  trialActive: boolean;
  trialDaysRemaining: number;
}

Example:

javascript
const user = await extLogin.getUser();

if (user) {
  console.log(`Welcome, ${user.name || user.email}!`);
  console.log('Paid:', user.paid);
  console.log('Trial active:', user.trialActive);
} else {
  console.log('No user logged in');
}

isAuthenticated()

Check if a user is currently logged in.

javascript
const isLoggedIn = await extLogin.isAuthenticated();

Returns: Promise<boolean>

Example:

javascript
if (await extLogin.isAuthenticated()) {
  showDashboard();
} else {
  showLoginForm();
}

hasPaidAccess()

Check if user has paid access (either paid subscription or active trial).

javascript
const canAccessPremium = await extLogin.hasPaidAccess();

Returns: Promise<boolean>

Example:

javascript
if (await extLogin.hasPaidAccess()) {
  showPremiumFeatures();
} else {
  showUpgradePrompt();
}

identify(userData)

Identify a user and send their data to connected CRMs.

javascript
const result = await extLogin.identify({
  email: '[email protected]',
  name: 'John Doe',
  metadata: { plan: 'pro' }
});

Parameters:

FieldTypeRequiredDescription
emailstringYesUser's email address
namestringNoFull name
metadataobjectNoCustom key-value data

Returns: Promise<IdentifyResult>

typescript
interface IdentifyResult {
  success: boolean;
  error?: string;
}

Example:

javascript
const result = await extLogin.identify({
  email: '[email protected]',
  name: 'John Doe',
  metadata: {
    source: 'extension',
    version: '1.0.0'
  }
});

if (result.success) {
  console.log('User identified successfully');
} else {
  console.error('Error:', result.error);
}

login(email, password)

Log in with email and password.

javascript
const result = await extLogin.login('[email protected]', 'password123');

Parameters:

FieldTypeDescription
emailstringUser's email address
passwordstringUser's password

Returns: Promise<LoginResult>

typescript
interface LoginResult {
  success: boolean;
  user?: ExtensionLoginUser;
  error?: string;
}

Example:

javascript
const result = await extLogin.login(email, password);

if (result.success) {
  console.log('Logged in:', result.user.email);
} else {
  console.error('Login failed:', result.error);
}

register(email, password, name?)

Register a new account.

javascript
const result = await extLogin.register('[email protected]', 'password123', 'John Doe');

Parameters:

FieldTypeRequiredDescription
emailstringYesUser's email address
passwordstringYesUser's password
namestringNoUser's display name

Returns: Promise<RegisterResult>

typescript
interface RegisterResult {
  success: boolean;
  user?: ExtensionLoginUser;
  error?: string;
}

logout()

Log out the current user.

javascript
await extLogin.logout();

Returns: Promise<void>

Example:

javascript
document.getElementById('logout-btn').addEventListener('click', async () => {
  await extLogin.logout();
  showLoginForm();
});

validateToken()

Validate the current token with the server and refresh user data.

javascript
const isValid = await extLogin.validateToken();

Returns: Promise<boolean>

Example:

javascript
// Check if token is still valid on extension startup
const isValid = await extLogin.validateToken();
if (!isValid) {
  // Token expired or invalid, show login
  showLoginForm();
}

getToken()

Get the current authentication token.

javascript
const token = await extLogin.getToken();

Returns: Promise<string | null>


Trial Methods

startTrial()

Start a free trial for the current user.

javascript
const result = await extLogin.startTrial();

Returns: Promise<TrialResult>

typescript
interface TrialResult {
  success: boolean;
  user?: ExtensionLoginUser;
  error?: string;
}

Example:

javascript
const result = await extLogin.startTrial();

if (result.success) {
  console.log('Trial started!');
  console.log('Days remaining:', result.user.trialDaysRemaining);
} else {
  console.error('Error:', result.error);
}

Google OAuth Methods

initGoogleAuth(redirectUrl)

Initialize the Google OAuth flow. Returns an auth URL to open.

javascript
const result = await extLogin.initGoogleAuth('https://yourextension.com/callback');

Parameters:

FieldTypeDescription
redirectUrlstringURL to redirect after OAuth

Returns: Promise<InitGoogleAuthResult>

typescript
interface InitGoogleAuthResult {
  success: boolean;
  authUrl?: string;
  state?: string;
  error?: string;
}

completeGoogleAuth(code, state, redirectUrl)

Complete the Google OAuth flow by exchanging the authorization code.

javascript
const result = await extLogin.completeGoogleAuth(code, state, redirectUrl);

Parameters:

FieldTypeDescription
codestringAuthorization code from Google
statestringState parameter from initGoogleAuth
redirectUrlstringSame redirect URL used in initGoogleAuth

Returns: Promise<LoginResult>


Payment Methods

Methods for handling subscriptions and payments with Stripe.

getPlans()

Get available subscription plans configured in the dashboard.

javascript
const result = await extLogin.getPlans();
if (result.success) {
  console.log('Available plans:', result.plans);
}

Returns: Promise<GetPlansResult>

typescript
interface GetPlansResult {
  success: boolean;
  plans?: ExtensionLoginPlan[];
  error?: string;
}

interface ExtensionLoginPlan {
  id: string;
  name: string;
  priceInCents: number;
  currency: string;
  interval: 'month' | 'year' | 'once';
  intervalCount: number;
  features?: string[];
  stripePriceId?: string;
}

openPaymentPage(planId, options?)

Create a Stripe checkout session and get the URL to open.

javascript
const result = await extLogin.openPaymentPage('plan_monthly', {
  successUrl: chrome.runtime.getURL('success.html'),
  cancelUrl: chrome.runtime.getURL('popup.html')
});

if (result.success) {
  // Open checkout in new tab
  chrome.tabs.create({ url: result.checkoutUrl });
}

Parameters:

FieldTypeRequiredDescription
planIdstringYesPlan ID from getPlans()
options.successUrlstringNoRedirect URL after successful payment
options.cancelUrlstringNoRedirect URL if user cancels

Returns: Promise<CheckoutResult>

typescript
interface CheckoutResult {
  success: boolean;
  checkoutUrl?: string;
  sessionId?: string;
  error?: string;
}

getSubscriptionStatus()

Get detailed subscription status for the current user.

javascript
const result = await extLogin.getSubscriptionStatus();

if (result.success) {
  const sub = result.subscription;
  console.log('Status:', sub.status);
  console.log('Plan:', sub.plan?.name);
  console.log('Renews:', sub.currentPeriodEnd);
}

Returns: Promise<SubscriptionResult>

typescript
interface SubscriptionResult {
  success: boolean;
  subscription?: SubscriptionDetails;
  error?: string;
}

interface SubscriptionDetails {
  active: boolean;
  status: 'active' | 'past_due' | 'canceled' | 'trialing' | 'none';
  plan: ExtensionLoginPlan | null;
  currentPeriodStart: Date | null;
  currentPeriodEnd: Date | null;
  cancelAt: Date | null;
  cancelAtPeriodEnd: boolean;
  trialEnd: Date | null;
}

openBillingPortal(returnUrl?)

Open the Stripe billing portal for subscription management.

javascript
const result = await extLogin.openBillingPortal(
  chrome.runtime.getURL('popup.html')
);

if (result.success) {
  chrome.tabs.create({ url: result.portalUrl });
}

Parameters:

FieldTypeRequiredDescription
returnUrlstringNoURL to return to after portal

Returns: Promise<BillingPortalResult>

typescript
interface BillingPortalResult {
  success: boolean;
  portalUrl?: string;
  error?: string;
}

cancelSubscription()

Cancel the current subscription at the end of the billing period.

javascript
const result = await extLogin.cancelSubscription();

if (result.success) {
  console.log('Subscription will end on:', result.cancelAt);
}

Returns: Promise<CancelResult>

typescript
interface CancelResult {
  success: boolean;
  cancelAt?: Date;
  error?: string;
}

refreshSubscription()

Manually refresh subscription status and emit events if changed.

javascript
// Call after successful checkout to update local state
await extLogin.refreshSubscription();

Returns: Promise<void>


Events

The SDK provides event emitters for reacting to auth state changes.

onLogin

Fires when a user logs in.

javascript
extLogin.onLogin.addListener((user) => {
  console.log('User logged in:', user.email);
});

onLogout

Fires when a user logs out.

javascript
extLogin.onLogout.addListener(() => {
  console.log('User logged out');
});

onPaid

Fires when a user's paid status changes to true.

javascript
extLogin.onPaid.addListener((user) => {
  console.log('User paid:', user.email);
  unlockPremiumFeatures();
});

onTrialStarted

Fires when a user starts a trial.

javascript
extLogin.onTrialStarted.addListener((user) => {
  console.log('Trial started for:', user.email);
  console.log('Days remaining:', user.trialDaysRemaining);
});

onSubscriptionChange

Fires when subscription status changes (after payment, cancellation, etc.).

javascript
extLogin.onSubscriptionChange.addListener((subscription) => {
  console.log('Subscription status:', subscription.status);
  if (subscription.active) {
    unlockPremiumFeatures();
  } else {
    lockPremiumFeatures();
  }
});

Removing Listeners

javascript
const handler = (user) => console.log(user);

// Add listener
extLogin.onLogin.addListener(handler);

// Remove listener
extLogin.onLogin.removeListener(handler);

TypeScript Types

Full TypeScript definitions:

typescript
import ExtensionLogin from 'extensionlogin';
import type {
  ExtensionLoginUser,
  ExtensionLoginPlan
} from 'extensionlogin';

// Create client
const extLogin = ExtensionLogin('el_live_xxx');

// User type
interface ExtensionLoginUser {
  id: string;
  email: string;
  name: string | null;
  paid: boolean;
  paidAt: Date | null;
  subscriptionStatus: 'active' | 'past_due' | 'canceled' | 'none';
  subscriptionCancelAt: Date | null;
  plan: ExtensionLoginPlan | null;
  installedAt: Date;
  trialStartedAt: Date | null;
  trialActive: boolean;
  trialDaysRemaining: number;
}

// Plan type
interface ExtensionLoginPlan {
  id: string;
  name: string;
  priceInCents: number;
  currency: string;
  interval: 'month' | 'year' | 'once';
  intervalCount: number;
  features?: string[];
  stripePriceId?: string;
}

// Subscription details type
interface SubscriptionDetails {
  active: boolean;
  status: 'active' | 'past_due' | 'canceled' | 'trialing' | 'none';
  plan: ExtensionLoginPlan | null;
  currentPeriodStart: Date | null;
  currentPeriodEnd: Date | null;
  cancelAt: Date | null;
  cancelAtPeriodEnd: boolean;
  trialEnd: Date | null;
}

// Checkout options type
interface CheckoutOptions {
  successUrl?: string;
  cancelUrl?: string;
}

Usage Patterns

Basic Popup Usage

javascript
import ExtensionLogin from 'extensionlogin';

const extLogin = ExtensionLogin('el_live_xxx');

// Check user on popup open
async function init() {
  const user = await extLogin.getUser();
  if (user) {
    showDashboard(user);
  } else {
    showLogin();
  }
}

// Handle login
async function handleLogin(email, name) {
  const result = await extLogin.identify({ email, name });
  if (result.success) {
    const user = await extLogin.getUser();
    showDashboard(user);
  }
}

init();

Background Script Usage

javascript
import ExtensionLogin from 'extensionlogin';

const extLogin = ExtensionLogin('el_live_xxx');
extLogin.startBackground();

// Listen for auth events
extLogin.onLogin.addListener((user) => {
  // Notify other parts of extension
  chrome.runtime.sendMessage({ type: 'USER_LOGGED_IN', user });
});

extLogin.onLogout.addListener(() => {
  chrome.runtime.sendMessage({ type: 'USER_LOGGED_OUT' });
});

Checking Premium Access

javascript
async function checkAccess() {
  const user = await extLogin.getUser();

  if (!user) {
    return { access: false, reason: 'not_logged_in' };
  }

  if (user.paid) {
    return { access: true, reason: 'paid' };
  }

  if (user.trialActive) {
    return {
      access: true,
      reason: 'trial',
      daysRemaining: user.trialDaysRemaining
    };
  }

  return { access: false, reason: 'no_subscription' };
}

Payment Flow

javascript
import ExtensionLogin from 'extensionlogin';

const extLogin = ExtensionLogin('el_live_xxx');

// Display available plans
async function showPlans() {
  const result = await extLogin.getPlans();
  if (result.success) {
    result.plans.forEach(plan => {
      const price = (plan.priceInCents / 100).toFixed(2);
      console.log(`${plan.name}: $${price}/${plan.interval}`);
    });
  }
}

// Handle plan selection
async function selectPlan(planId) {
  const result = await extLogin.openPaymentPage(planId, {
    successUrl: chrome.runtime.getURL('success.html'),
    cancelUrl: chrome.runtime.getURL('popup.html')
  });

  if (result.success) {
    // Open Stripe checkout in new tab
    chrome.tabs.create({ url: result.checkoutUrl });
  }
}

// Listen for subscription changes
extLogin.onSubscriptionChange.addListener((subscription) => {
  if (subscription.active) {
    showPremiumFeatures();
  }
});

// On success page, refresh subscription status
async function handlePaymentSuccess() {
  await extLogin.refreshSubscription();
  const user = await extLogin.getUser();
  if (user?.paid) {
    showThankYouMessage();
  }
}

// Allow user to manage billing
async function openBilling() {
  const result = await extLogin.openBillingPortal(
    chrome.runtime.getURL('popup.html')
  );
  if (result.success) {
    chrome.tabs.create({ url: result.portalUrl });
  }
}

Next Steps

Built for Chrome Extension Developers