@kolaylogin/auth-sdk
v1.0.1
Published
Enterprise SSO authentication SDK for mobile and web applications
Downloads
63
Readme
@kolaylogin/auth-sdk
Enterprise-grade authentication SDK for mobile and web applications. Powered by modern, secure infrastructure with support for OAuth, SAML SSO, and multi-tenant applications.
Features
Authentication
- ✅ Multiple Auth Methods: Email/password, OAuth (Google, Apple, Microsoft), Enterprise SSO
- ✅ Multi-Tenant Ready: Support for 100+ apps with per-app branding
- ✅ Cross-Platform: Web, React, React Native, Node.js
- ✅ TypeScript First: Full type safety and IntelliSense
- ✅ Secure by Default: Industry-standard security practices
- ✅ Zero Configuration: Works out of the box with sensible defaults
- ✅ White-Label Ready: Complete branding customization
Merchant Management (NEW)
- ✅ Automatic Merchant Creation: Create merchants with auto-generated merchant IDs
- ✅ Merchant Profile Management: Update merchant information and settings
- ✅ Wallet Address Management: Store and manage Ethereum wallet addresses
- ✅ Merchant Status Tracking: Track merchant status (active, inactive, suspended)
X402 Payment Integration (NEW)
- ✅ X402 Facilitator Client: Complete X402 protocol integration
- ✅ Payment Verification: Verify X402 payments before settlement
- ✅ Payment Settlement: Settle verified payments
- ✅ Multi-Network Support: Support for BSC and Base networks
- ✅ Supported Payment Kinds: Query supported payment methods
Next.js Templates (NEW)
- ✅ Merchant Dashboard Template: Ready-to-use merchant management dashboard
- ✅ Payment Checkout Template: Pre-built payment checkout page
- ✅ Webhook Handler Template: X402 webhook handler implementation
Installation
npm install @kolaylogin/auth-sdk
# or
yarn add @kolaylogin/auth-sdk
# or
pnpm add @kolaylogin/auth-sdkQuick Start
Web / Node.js
import { KolayLoginClient } from '@kolaylogin/auth-sdk';
const client = new KolayLoginClient({
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
redirectUri: 'https://yourapp.com/auth/callback',
});
// Sign in with email/password
const session = await client.signInWithEmail('[email protected]', 'password');
// Sign in with OAuth
const { url } = await client.signInWithOAuth({ provider: 'google' });
window.location.href = url;
// Sign in with enterprise SSO
const { url } = await client.signInWithSSO({ domain: 'company.com' });
window.location.href = url;
// Get current user
const user = await client.getUser();
// Sign out
await client.signOut();React
import { KolayLoginProvider, useKolayLogin } from '@kolaylogin/auth-sdk/react';
function App() {
return (
<KolayLoginProvider
config={{
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
redirectUri: 'https://yourapp.com/auth/callback',
}}
>
<YourApp />
</KolayLoginProvider>
);
}
function YourApp() {
const { user, signIn, signOut, loading } = useKolayLogin();
if (loading) return <div>Loading...</div>;
if (!user) {
return (
<button onClick={() => signIn('[email protected]', 'password')}>
Sign In
</button>
);
}
return (
<div>
<p>Welcome, {user.email}!</p>
<button onClick={signOut}>Sign Out</button>
</div>
);
}Merchant Management
Create Merchant
import { createMerchant } from '@kolaylogin/auth-sdk';
const merchant = await createMerchant(
{
userId: user.id,
name: 'My Shop',
email: '[email protected]',
walletAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827', // Optional
metadata: {
businessType: 'e-commerce',
website: 'https://myshop.com',
},
},
{
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
}
);
console.log('Merchant ID:', merchant.merchantId); // merchant_abc123Get Merchant
import { getMerchant } from '@kolaylogin/auth-sdk';
// By merchant ID
const merchant = await getMerchant(
{ merchantId: 'merchant_abc123' },
{ supabaseUrl: '...', supabaseKey: '...' }
);
// By user ID
const merchant = await getMerchant(
{ userId: user.id },
{ supabaseUrl: '...', supabaseKey: '...' }
);Using MerchantManager Class
import { MerchantManager } from '@kolaylogin/auth-sdk';
const manager = new MerchantManager({
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
});
// Create merchant
const merchant = await manager.create({
userId: user.id,
name: 'My Shop',
email: '[email protected]',
});
// Get merchant
const merchantInfo = await manager.get({ merchantId: merchant.merchantId });
// Update merchant
await manager.update(merchant.merchantId, {
name: 'Updated Shop Name',
status: 'active',
});X402 Payment Integration
X402 Facilitator
import { X402Facilitator } from '@kolaylogin/auth-sdk';
const facilitator = new X402Facilitator({
merchantId: 'merchant_abc123',
facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
network: 'bsc', // 'bsc' | 'base'
apiUrl: 'https://api.paykly.com', // Optional
apiKey: 'YOUR_API_KEY', // Optional
});
// Get supported payment kinds
const supported = await facilitator.getSupported();
// Verify payment
const verification = await facilitator.verify({
x402Version: 1,
paymentPayload: {
transactionHash: '0x...',
},
paymentRequirements: {
scheme: 'exact',
network: 'bsc',
maxAmountRequired: '1000000',
resource: 'https://api.paykly.com/resource',
},
});
if (verification.isValid) {
// Settle payment
const settlement = await facilitator.settle({
x402Version: 1,
paymentPayload: {
transactionHash: '0x...',
},
paymentRequirements: {
scheme: 'exact',
network: 'bsc',
maxAmountRequired: '1000000',
resource: 'https://api.paykly.com/resource',
},
});
}Standalone Functions
import { verifyPayment, settlePayment } from '@kolaylogin/auth-sdk';
// Verify payment
const isValid = await verifyPayment(
{
x402Version: 1,
paymentPayload: { transactionHash: '0x...' },
paymentRequirements: { /* ... */ },
},
{
merchantId: 'merchant_abc123',
facilitatorAddress: '0x...',
network: 'bsc',
}
);
// Settle payment
const success = await settlePayment(
{
x402Version: 1,
paymentPayload: { transactionHash: '0x...' },
paymentRequirements: { /* ... */ },
},
{
merchantId: 'merchant_abc123',
facilitatorAddress: '0x...',
network: 'bsc',
}
);React Hooks
useMerchant Hook
import { useMerchant } from '@kolaylogin/auth-sdk/react';
function MerchantDashboard() {
const { user } = useKolayLogin();
const { merchant, loading, createMerchant, updateMerchant } = useMerchant();
useEffect(() => {
if (user && !merchant) {
createMerchant({
name: 'My Shop',
email: '[email protected]',
});
}
}, [user, merchant, createMerchant]);
if (loading) return <div>Loading...</div>;
return (
<div>
<h1>Merchant: {merchant?.name}</h1>
<p>Merchant ID: {merchant?.merchantId}</p>
</div>
);
}useX402 Hook
import { useX402 } from '@kolaylogin/auth-sdk/react';
function PaymentHandler() {
const { merchant } = useMerchant();
const { verifyPayment, settlePayment, loading } = useX402({
merchantId: merchant?.merchantId || '',
facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
network: 'bsc',
});
const handlePayment = async (paymentData) => {
const verification = await verifyPayment({
x402Version: 1,
paymentPayload: paymentData.payload,
paymentRequirements: paymentData.requirements,
});
if (verification.isValid) {
await settlePayment({
x402Version: 1,
paymentPayload: paymentData.payload,
paymentRequirements: paymentData.requirements,
});
}
};
return (
<button onClick={handlePayment} disabled={loading}>
Process Payment
</button>
);
}Complete Integration Example
import {
KolayLoginClient,
createMerchant,
X402Facilitator,
initMerchantApp,
} from '@kolaylogin/auth-sdk';
// 1. User authentication
const client = new KolayLoginClient({
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
});
const { user } = await client.signUp('[email protected]', 'password');
// 2. Create merchant (automatic merchant ID)
const merchant = await createMerchant(
{
userId: user.id,
name: 'My Shop',
email: '[email protected]',
},
{
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
}
);
console.log('Merchant ID:', merchant.merchantId);
// 3. Initialize X402 facilitator
const facilitator = new X402Facilitator({
merchantId: merchant.merchantId,
facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
network: 'bsc',
});
// 4. Get supported payment methods
const supported = await facilitator.getSupported();
// 5. Generate merchant dashboard
await initMerchantApp({
outputDir: './my-shop-dashboard',
merchantId: merchant.merchantId,
templates: ['merchant-dashboard', 'payment-checkout'],
config: {
facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
network: 'bsc',
},
});Database Setup
Before using merchant features, you need to create the merchants table in your Supabase database:
-- Run the migration file
-- See: lib/database/merchants_schema.sqlOr run the SQL directly:
CREATE TABLE IF NOT EXISTS merchants (
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
merchant_id TEXT UNIQUE NOT NULL DEFAULT 'merchant_' || gen_random_uuid()::text,
name TEXT NOT NULL,
email TEXT NOT NULL,
wallet_address TEXT,
status TEXT DEFAULT 'active' CHECK (status IN ('active', 'inactive', 'suspended')),
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_merchants_user_id ON merchants(user_id);
CREATE INDEX IF NOT EXISTS idx_merchants_merchant_id ON merchants(merchant_id);Next.js Templates
Coming soon: Ready-to-use Next.js templates for merchant dashboard, payment checkout, and webhook handlers.
import { initMerchantApp } from '@kolaylogin/auth-sdk';
await initMerchantApp({
outputDir: './my-merchant-app',
merchantId: 'merchant_abc123',
templates: ['merchant-dashboard', 'payment-checkout', 'webhook-handler'],
config: {
facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
network: 'bsc',
},
});React Native
import { KolayLoginReactNativeClient } from '@kolaylogin/auth-sdk/react-native';
const client = new KolayLoginReactNativeClient({
supabaseUrl: 'YOUR_SUPABASE_URL',
supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
redirectUri: 'yourapp://auth/callback',
});
// Usage same as web client
// Note: Requires expo-secure-store and expo-linkingAPI Reference
KolayLoginClient
Methods
signInWithEmail(email, password): Sign in with email and passwordsignInWithOAuth(options): Sign in with OAuth providersignInWithSSO(options): Sign in with enterprise SSOsignUp(email, password, metadata?): Create new accountsignOut(): Sign out current usergetUser(): Get current usergetSession(): Get current sessionrefreshSession(): Refresh access tokenupdateUser(updates): Update user profileresetPassword(email): Send password reset emailverifyOTP(params): Verify OTP codeexchangeCodeForSession(code): Exchange OAuth code for sessiononAuthStateChange(callback): Subscribe to auth state changes
React Hooks
useKolayLogin(): Main hook for authenticationuseUser(): Get current useruseSession(): Get current sessionuseAuth(): Get auth methodsuseAuthState(): Check authentication state
React Components
<LoginButton />: Pre-built login button<UserProfile />: User profile display<SSOForm />: SSO login form
Documentation
Error Handling
All errors are thrown as KolayLoginError instances:
import { KolayLoginError } from '@kolaylogin/auth-sdk';
try {
await client.signInWithEmail('[email protected]', 'password');
} catch (error) {
if (error instanceof KolayLoginError) {
console.error('Error code:', error.code);
console.error('Error message:', error.message);
}
}Multi-Tenant Support
import { TenantManager } from '@kolaylogin/auth-sdk';
const tenantManager = new TenantManager();
await tenantManager.registerApp({
appId: 'my-app',
appName: 'My App',
bundleId: 'com.example.app',
platform: 'ios',
redirectUri: 'myapp://auth/callback',
ssoEnabled: true,
});TypeScript Support
Full TypeScript definitions are included. All types are exported:
import type {
KolayLoginConfig,
KolayLoginUser,
AuthSession,
OAuthOptions,
SSOOptions,
} from '@kolaylogin/auth-sdk';License
MIT
Support
For issues and questions, please visit our GitHub repository.
