bitsnap-react
v1.4.6
Published
This is Bitsnap React library for easy integration with any website which is using React framework
Readme
Bitsnap Checkout
The library is designed to provide a complete e-commerce checkout solution that can be easily integrated into web applications, with focus on:
- User experience
- Payment processing
- Cart management
- Product management
- Webhook support
It uses modern React patterns and libraries like:
- React Query for data fetching
- Zod for schema validation
- Protocol Buffers for data serialization
- Tailwind CSS for styling
Capabilities
Cart Management:
- Allows adding products to cart
- Manages cart state (show/hide)
- Handles cart items quantity updates
- Provides cart total calculations
- Supports removing items from cart
Checkout Flow:
- Handles checkout process
- Supports different payment gateways
- Manages shipping/billing addresses
- Handles coupon codes
- Supports different delivery methods
Product Management:
- Fetches product details from Bitsnap
- Handles product variants
- Manages product inventory/stock
- Supports product metadata
Features:
- Supports multiple currencies
- Internationalization support
- Webhook handling
- Error handling
- Loading states
- Responsive design
- Protocol buffer integration
Integration:
- Can be integrated into existing websites
- Configurable project ID
- Customizable host URL
- Supports test/production environments
Examples
BitsnapCheckoutComponent:
import { BitsnapCheckout } from "bitsnap-react";
function MyComponent() {
return (
<BitsnapCheckout
projectID="your-project-id"
onVisibleChange={(isVisible) =>
console.log("Cart visibility:", isVisible)
}
className="custom-class"
>
{/* Optional custom cart trigger button content */}
<span>My Custom Cart Button</span>
</BitsnapCheckout>
);
}setProjectID:
import { setProjectID } from "bitsnap-react";
// Set the project ID globally
setProjectID("your-project-id");- Cart Methods:
import { Bitsnap } from "bitsnap-react";
// Modern approach using namespace
async function handleCart() {
// Add product to cart
await Bitsnap.addProductToCart("product-id", 2, {
customField: "value",
});
// Show cart
Bitsnap.showCart();
// Hide cart
Bitsnap.hideCart();
}
// Legacy approach (deprecated)
async function legacyHandleCart() {
await addProductToCart("product-id", 1);
showCart();
hideCart();
}- Creating Checkout/Payment:
import { createCheckout, LinkRequest } from "bitsnap-react";
async function handleCheckout() {
const request: LinkRequest = {
items: [
{
id: "product-id",
quantity: 1,
},
],
details: {
email: "[email protected]",
name: "John Doe",
address: {
name: "John Doe",
line1: "123 Street",
city: "City",
country: "US",
},
},
askForAddress: true,
askForPhone: true,
};
const result = await createCheckout({
...request,
apiKey: "your-api-key",
testMode: true,
});
if (result.status === "ok") {
window.location.href = result.redirectURL;
}
}- Webhook Handler:
import { handleWebhook } from "bitsnap-react";
async function processWebhook(req: Request) {
const payload = await req.text();
const url = req.url;
const headers = Object.fromEntries(req.headers);
const webhookSecret = "your-webhook-secret";
const result = await handleWebhook(payload, url, headers, webhookSecret);
if (result.isErr) {
console.error("Webhook error:", result.error);
return;
}
// Process the webhook event
const { projectId, environment, eventData } = result;
switch (eventData?.event) {
case "TRANSACTION_SUCCESS":
// Handle successful transaction
break;
case "TRANSACTION_FAILURE":
// Handle failed transaction
break;
// Handle other events...
}
}Complete Example:
import {
BitsnapCheckout,
setProjectID,
setCustomHost,
Bitsnap,
createCheckout,
handleWebhook,
type LinkRequest,
} from "bitsnap-react";
// Configure globally
setProjectID("your-project-id");
setCustomHost("https://your-custom-host.com");
function Store() {
async function handleBuyNow(productId: string) {
// Add to cart
await Bitsnap.addProductToCart(productId, 1);
// Show cart
Bitsnap.showCart();
}
async function processCheckout(
items: Array<{ id: string; quantity: number }>,
) {
const checkoutRequest: LinkRequest = {
items,
askForAddress: true,
askForPhone: true,
details: {
email: "[email protected]",
},
redirect: {
successURL: "/success",
cancelURL: "/cancel",
},
};
const result = await createCheckout({
...checkoutRequest,
testMode: true,
});
if (result.status === "ok") {
window.location.href = result.redirectURL;
}
}
return (
<div>
<button onClick={() => handleBuyNow("product-123")}>Buy Now</button>
<BitsnapCheckout
projectID="your-project-id"
onVisibleChange={(isVisible) => {
console.log("Cart visibility changed:", isVisible);
}}
/>
</div>
);
}Capabilities
Authentication:
- Email-based login with OTP verification
- Session management
- Logout functionality
Product Management:
- Browse purchased products
- View product details
- Audio playback with chapter navigation
- File downloads
- Progress tracking
User Features:
- Profile management
- Order history viewing
- Subscription plan management
- Notification preferences
Configuration
Before using the Panel components, configure the library globally:
import {
setProjectID,
setTheme,
setLoginURL,
setHost,
PanelProvider,
} from "bitsnap-react";
// Configure globally - call once at app initialization
setProjectID("your-project-id");
setLoginURL("/panel/login");
setHost("https://api.bitsnap.pl");
// Optional: Set theme
setTheme({
logoURL: "https://yourdomain.com/logo.png",
logoDarkURL: "https://yourdomain.com/logo-dark.png",
colors: {
brand: "#ff0000",
brandDark: "#cc0000",
},
});Configuration Options
| Function | Type | Description |
| -------------- | ---------------- | -------------------------------------------- |
| setProjectID | string | Your Bitsnap project ID |
| setLoginURL | string | URL for login page (default: /panel/login) |
| setHost | string | Custom API host URL |
| setTheme | GetThemeOutput | Theme configuration (logo, colors) |
Theme Type
interface GetThemeOutput {
logoURL?: string;
logoDarkURL?: string;
colors?: {
brand?: string;
brandDark?: string;
};
}Usage
Wrap your application with PanelProvider:
import { PanelProvider } from "bitsnap-react";
function App() {
return (
<PanelProvider>
<YourApp />
</PanelProvider>
);
}Panel Component
The main panel component displays the authenticated user panel with products, orders, and profile.
import { Panel } from "bitsnap-react";
function MyPage() {
return <Panel />;
}PanelLogin Component
The login component handles email-based authentication with OTP verification.
import { PanelLogin } from "bitsnap-react";
function LoginPage() {
return <PanelLogin />;
}Complete Example
App Entry Point
import {
setProjectID,
setTheme,
setLoginURL,
setHost,
PanelProvider,
Panel,
PanelLogin,
} from "bitsnap-react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
// Configure at app startup
setProjectID("your-project-id");
setLoginURL("/panel/login");
setHost("https://api.bitsnap.pl");
setTheme({
logoURL: "https://yourdomain.com/logo.png",
colors: {
brand: "#4F46E5",
brandDark: "#3730A3",
},
});
export default function App() {
return (
<PanelProvider>
<BrowserRouter>
<Routes>
<Route path="/panel" element={<Panel />} />
<Route path="/panel/login" element={<PanelLogin />} />
</Routes>
</BrowserRouter>
</PanelProvider>
);
}Login Page
import { PanelLogin } from "bitsnap-react";
export default function LoginPage() {
return (
<div className="min-h-screen flex items-center justify-center">
<PanelLogin />
</div>
);
}Panel Page (Authenticated)
import { Panel } from "bitsnap-react";
export default function DashboardPage() {
return <Panel />;
}Panel Screens
The panel provides the following screens:
| Screen | Path | Description |
| ------------- | ---------------------------- | ---------------------------------- |
| Products | /panel | Browse and view purchased products |
| Orders | /panel?state=orders | View order history and invoices |
| Profile | /panel?state=profile | User profile and settings |
| Notifications | /panel?state=notifications | Notification preferences |
| Plans | /panel?state=plans | Subscription management |
Features Detail
Products Screen
- Displays all purchased products
- Shows product cards with image, name, and description
- Click to view product details
- Supports audio, file, and ticket products
Product Details
- Full product information display
- Audio player with chapter navigation
- File download links
- Progress tracking
Audio Player
- Chapter selection
- Play/pause controls
- Seek functionality
- Media session integration (lock screen controls)
- Progress persistence
Order History
- List of all invoices
- Invoice status (paid, unpaid, overdue)
- Download PDF invoices
Profile
- View email address
- Logout functionality
Notifications
- Toggle all notifications
- Notification preferences
