PayBito Cart SDK

Drop-in JavaScript library for a fully functional shopping cart & checkout experience on any website

Overview

The PayBito Cart SDK (v4.4) is a drop-in JavaScript library that adds a fully functional shopping cart and payment checkout experience to any website. It requires a single <script> tag with your merchant credentials — no build tools, no frameworks, no backend changes needed.

Key Capabilities

One-Line Integration

Single <script> tag — no npm, no bundler required. Works on any website stack.

Server-Synced Cart

Cart state preserved across tabs and page refreshes using browser localStorage and a server-side session.

Mobile Responsive

Full-screen drawer on mobile, 480px panel on desktop, with complete touch support.

Offline Fallback

Local mode when API is unavailable; checkout remains disabled until connectivity is restored.

Flexible Product Model

Simple flat objects; supports attributes like color, size, and other variants.

Automatic UI Injection

FAB button + side drawer are rendered automatically by the SDK — no manual HTML needed.

Event Hooks

React to cart changes, item additions, and checkout starts with a simple event API.

Credential Caching

API credentials cached in localStorage with a 24-hour TTL for optimal performance.

Prerequisites

Before integrating the SDK, complete the following setup steps in the PayBito Payments Portal.

2.1 How to Get Your API Key

1
Log in to the Payments Portal

Sign in with your merchant account credentials at portal.paybito.com.

2
Navigate to the Developers Section

Find the Developers menu item in the left-hand sidebar.

3
Open API Keys

Click on API Keys under the Developers section.

4
Create a New API Key

Click the Create API Key button and follow the on-screen prompts.

5
Copy Your Public Key

Copy the key that begins with pk_ — this is your data-public-key value. You will also find your Merchant ID and Broker ID on this page.

2.2 Whitelist Your Domain

Required: The API only accepts requests from explicitly whitelisted domains. Without this step, all API calls will be rejected with an authentication error.

1
Log in to the Payments Portal

Sign in with your merchant account credentials.

2
Navigate to Developers → Domain Whitelisting

Click Domain Whitelisting under the Developers section.

3
Add Your Domain

Enter your website domain (e.g. https://www.yourstore.com) and click Add. Include all subdomains in use. For local dev, add http://localhost:PORT.

2.3 Merchant Account Credentials

  • Merchant ID — from your PayBito account profile
  • Public Key — from Developers → API Keys (begins with pk_)
  • Broker ID — from Developers → API Keys or your account manager

2.4 Website Requirements

  • Any website stack — static HTML, WordPress, Shopify, React, Vue, etc.
  • Ability to add a <script> tag to your HTML pages
  • HTTPS strongly recommended (required in production)
  • No specific framework version required

Quick Start

Follow these steps to add PayBito Cart to your website in minutes.

Step 1 — Add the SDK Script Tag

Add the following <script> tag to every page where you want the cart to appear. Place it just before the closing </body> tag:

<script src="https://your-cdn.com/PayBitoCart.js" data-merchant-id="YOUR_MERCHANT_ID" data-public-key="YOUR_PUBLIC_KEY" data-broker-id="YOUR_BROKER_ID"></script>

Step 2 — Add to Cart Button

<button onclick="PayBito.addToCart({ product_id: 'SKU-001', name: 'My Product', price: 49.99, quantity: 1, image_url: 'https://your-site.com/images/product.jpg' }, event)"> Add to Cart </button> <!-- Cart drawer open button --> <button data-pb-open-cart> Cart <span data-pb-count></span> </button>

Step 3 — Button Customization

var CART_BUTTON_CONFIG = { color: null, // background color code, null = default textColor: null, // text & icon color, null = default hoverColor: null, // background on hover, null = default size: 'default', // 'small' | 'default' | 'large' | 'very large' borderRadius: null, // 'rounded' | 'pill' | 'square' | null text: null, // button label, null = 'Add to Cart' icon: null, // 'cart' | 'bag' | 'none' | null };

Step 4 — Create Payment Result Pages

success.html

Displayed after a successful payment. Can read the paymentId from the URL query string to display order details.

failure.html

Displayed after a failed or cancelled payment. Offer a clear return-to-store link.

Script Tag Attributes

Configure the SDK by setting data-* attributes on the <script> tag.

Attribute Required Type Description
data-merchant-id Yes String Your unique PayBito merchant identifier
data-public-key Yes String Public API key beginning with pk_
data-broker-id Recommended String Broker ID used to resolve the checkout portal URL
data-checkout-url Optional URL Override the checkout portal base URL (skips broker lookup)
data-api-key Legacy String Deprecated alias for data-public-key — use public-key instead

Always use data-public-key instead of data-api-key. The latter is maintained for backward compatibility only.

JavaScript API Reference

All SDK functions are available through the global window.PayBito namespace once the script has loaded.

5.1 PayBito.addToCart(product, event)

Adds a product to the cart. This is the primary method you will call from your product pages.

Parameter Type Required Description
product.product_id String Yes Unique SKU or product identifier
product.name String Yes Human-readable product name
product.price Number Yes Unit price (e.g. 49.99)
product.quantity Number No Quantity to add; defaults to 1
product.currency String No ISO currency code; defaults to "USD"
product.image_url String No Full URL of the product image
product.attributes Object No Key-value pairs for variants (color, size, etc.)
product.available_quantity Number No Max orderable quantity; defaults to 999
event Event No DOM click event — enables button state animation
PayBito.addToCart({ product_id: 'HDPHN-001', name: 'Wireless Headphones', price: 89.99, quantity: 1, currency: 'USD', image_url: 'https://example.com/headphones.jpg', attributes: { color: 'Black', connectivity: 'Bluetooth 5.0' }, available_quantity: 50 }, event);

5.2 Cart State Methods

Method Returns Description
PayBito.getCount() Number Total number of items in the cart
PayBito.getTotal() Number Total cart value formatted to 2 decimal places
PayBito.getToken() String Current server-side cart session token
PayBito.syncCart() Promise Fetch latest cart state from the server
PayBito.clearCart() void Remove all items; clear localStorage and server cart

5.3 Cart UI Methods

Method Description
PayBito.openInternalCart() Programmatically open the side drawer cart panel
PayBito.closeInternalCart() Programmatically close the side drawer cart panel

Add-to-Cart Button States

State Button Text Clickable? When
Idle Your original HTML Yes Before user clicks
Loading "Adding..." + spinner No API call in progress
Success "Added ✓" No (brief) Item added successfully
Qty Control − qty + Yes Item already in cart
Error "Retry" Yes API call failed

Event System

The SDK emits events you can subscribe to with PayBito.on(). This allows you to react to cart changes, integrate with analytics, or implement custom checkout flows.

Subscribing to Events

PayBito.on('eventName', function(payload) { /* ... */ }); // Chaining is supported: PayBito .on('update', function(cart) { /* ... */ }) .on('itemAdded', function(data) { /* ... */ });

Available Events

"update" — Cart State Changed

Fired whenever the cart changes (item added, quantity updated, item removed).

{ count: 3, total: 219.97, items: [ /* cart items */ ], token: "token_xyz" }
"itemAdded" — Single Item Added
{ item: { product_id, name, unit_price, quantity }, count: 3, total: 219.97 }
"checkout" — Checkout Interceptor

If registered, the SDK's default checkout flow is bypassed entirely. Use for custom payment handling.

{ token: "token_xyz", total: 219.97, items: [ /* ... */ ] }

Practical Examples

GA4 Tracking

PayBito.on('itemAdded', function(data) { gtag('event', 'add_to_cart', { currency: 'USD', value: data.total, items: [{ item_id: data.item.product_id, price: data.item.unit_price }] }); });

Custom Checkout Override

PayBito.on('checkout', function(cart) { fetch('/api/create-order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: cart.token, total: cart.total }) }) .then(r => r.json()) .then(res => window.location.href = res.paymentUrl); });

Product Variants & Attributes

Passing Attributes

PayBito.addToCart({ product_id: 'SHIRT-001', name: 'T-Shirt', price: 29.99, attributes: { color: 'Navy Blue', size: 'Large' } }, event);

Reading User Selections

<select id="color-select"> <option>Black</option> <option>White</option> </select> function addShirt(evt) { PayBito.addToCart({ product_id: 'SHIRT-001', name: 'T-Shirt', price: 29.99, attributes: { color: document.getElementById('color-select').value, size: document.getElementById('size-select').value } }, evt); }

How Attributes Are Used

  • Displayed as chips in the cart drawer (e.g. "Color: Black", "Size: M")
  • Items with the same product_id but different attributes are treated as separate cart entries
  • Sent to the PayBito API in array format: { color: ["Black"], size: ["M"] }

Cart UI Components

Floating Action Button

Shows a badge with the current item count; hidden when cart is empty. DOM ID: #pb-cart-float

Side Drawer

480px wide on desktop, full-screen on mobile (< 520px). DOM ID: #pb-drawer

CSS Override Selectors

CSS Selector Element
#pb-cart-float Floating cart button
#pb-drawer-overlay Dark backdrop overlay behind the drawer
#pb-drawer The main drawer container
.pb-item-row A single cart item row
.pb-btn-checkout The "Proceed to Checkout" button
.pb-spinner Loading spinner
.pb-attr-chip Attribute tag chip (e.g. "Color: Black")

Add !important to your overrides or ensure your stylesheet loads after PayBitoCart.js.

Authentication & Credential Flow

Validation Flow

1
SDK reads credentials

Page loads → SDK reads data-public-key from the <script> tag.

2
Check localStorage cache

SDK checks localStorage for cached credentials (pb_api_creds).

3
Cache hit or miss

Cache valid (< 24h) → uses cached { clientId, clientSecret, domain }. Cache missing/expired → GET /api/v1/validate with publicKey and Origin headers → stores result in localStorage with timestamp.

4
SDK is ready

All cart operations are now available.

Security Notes

  • Your public key is visible in HTML — this is intentional; it is a public-facing key, not a secret
  • The server validates the Origin header — only whitelisted domains are accepted
  • Cart tokens are generated server-side and are unpredictable
  • Never include private/secret keys in your frontend code
  • Always serve pages over HTTPS in production

Checkout & Payment Flow

Standard Checkout Flow

1
User clicks "Proceed to Checkout"

SDK calls POST /shopping/payment/create

2
Receive payment session

API returns { paymentId, brokerId }

3
Build checkout URL

{CHECKOUT_DOMAIN}/payments/merchant/checkout/?data={base64(...)}

4
Open checkout portal

window.open(url, "_blank") — user completes payment on PayBito portal

5
Redirect to result page

User is redirected to success.html or failure.html

Checkout URL Resolution Priority

  • data-checkout-url attribute on the <script> tag
  • Domain from broker lookup API (accounts.paybito.com)
  • Fallback → https://portal.paybito.com

Server-Side Webhook (Recommended)

app.post('/webhooks/paybito', express.json(), (req, res) => { const { paymentId, status, cartToken } = req.body; if (status === 'success') fulfillOrder(paymentId, cartToken); res.status(200).json({ received: true }); });

Security: Always validate order details server-side via webhook before fulfilling — never trust client-side totals.

Complete Integration Examples

Static HTML Page

<!DOCTYPE html><html lang="en"> <body> <h1>Wireless Headphones — $89.99</h1> <select id="color"><option>Black</option></select> <button onclick="addItem(event)">Add to Cart</button> <script src="PayBitoCart.js" data-merchant-id="YOUR_MERCHANT_ID" data-public-key="YOUR_PUBLIC_KEY" data-broker-id="YOUR_BROKER_ID"></script> <script> function addItem(evt) { PayBito.addToCart({ product_id: 'HDPHN-001', name: 'Wireless Headphones', price: 89.99, attributes: { color: document.getElementById('color').value }, available_quantity: 50 }, evt); } </script> </body></html>

WordPress Integration (functions.php)

function enqueue_paybito_cart() { wp_register_script( 'paybito-cart', get_template_directory_uri() . '/js/PayBitoCart.js', [], '4.4', true ); wp_script_add_data('paybito-cart', 'data-merchant-id', 'YOUR_MERCHANT_ID'); wp_script_add_data('paybito-cart', 'data-public-key', 'YOUR_PUBLIC_KEY'); wp_script_add_data('paybito-cart', 'data-broker-id', 'YOUR_BROKER_ID'); wp_enqueue_script('paybito-cart'); } add_action('wp_enqueue_scripts', 'enqueue_paybito_cart');

React / Next.js Integration

import { useEffect } from 'react'; export default function PayBitoCartProvider({ children }) { useEffect(() => { const script = document.createElement('script'); script.src = '/PayBitoCart.js'; script.setAttribute('data-merchant-id', process.env.NEXT_PUBLIC_MERCHANT_ID); script.setAttribute('data-public-key', process.env.NEXT_PUBLIC_PAYBITO_KEY); script.setAttribute('data-broker-id', process.env.NEXT_PUBLIC_BROKER_ID); document.body.appendChild(script); return () => { document.body.removeChild(script); }; }, []); return <>{children}</>; }

LocalStorage Keys & Data Persistence

Key Value Type TTL Purpose
paybito_cart_token String Until cleared Active cart session token
paybito_catalog_id String/Number Until cleared Product catalog ID for this session
pb_cart_items JSON Array Until cleared Local cache of current cart items
pb_api_creds JSON Object 24 hours Cached { clientId, clientSecret, domain, timestamp }

Manually Clearing the Cart

PayBito.clearCart(); // SDK method (recommended) // Or manually in the browser console: localStorage.removeItem('paybito_cart_token'); localStorage.removeItem('paybito_catalog_id'); localStorage.removeItem('pb_cart_items'); localStorage.removeItem('pb_api_creds'); location.reload();

Troubleshooting

Symptom Likely Cause Resolution
Cart button does nothing PayBitoCart.js not loaded yet Ensure <script> tag is before the button or use DOMContentLoaded
Console: "Invalid API key" Incorrect data-public-key Regenerate from Payments Portal → Developers → API Keys
All API calls rejected Domain not whitelisted Add domain in Payments Portal → Domain Whitelisting
"Adding..." spinner never resolves CORS issue or network error Check browser console; confirm domain is whitelisted
Cart resets on every page localStorage blocked Check if browser is in private/incognito mode
Checkout button opens nothing Popup blocker active Instruct users to allow popups from your domain
Attributes not showing in cart attributes is not a plain object Ensure attributes is a key-value object, not an array
Wrong checkout portal domain broker-id missing or invalid Provide data-broker-id or use data-checkout-url

Integration Checklist

Use this checklist to verify your integration before going live.

# Task Done?
1 Logged into Payments Portal → Developers → API Keys and created an API key
2 Noted down Merchant ID, Public Key (pk_*), and Broker ID
3 Added website domain in Payments Portal → Domain Whitelisting
4 Added localhost domain for local development (if applicable)
5 Hosted PayBitoCart.js on your server or CDN
6 Added <script> tag with correct data-* attributes to all relevant pages
7 Added addToCart() calls to all product buttons with correct product data
8 Created success.html for successful payment redirects
9 Created failure.html for failed/cancelled payment redirects
10 Configured webhook endpoint on PayBito dashboard
11 Tested Add-to-Cart flow end-to-end in sandbox
12 Tested on mobile devices (drawer, button state)
13 Verified pages are served over HTTPS
14 Validated server-side order details via webhook before fulfillment
Need Help?

Merchant Dashboard: portal.paybito.com  ·  Submit a support ticket from your PayBito dashboard  ·  Contact your dedicated account manager

SDK v4.4  ·  Documentation v1.2  ·  April 2026  ·  HashCash Consultants · PayBito Payment Solutions

Contents

paybito logo

Download the Mobile Apps

Contact Us

  (Max 120 Character)
  (Max 500 Character)
By checking this box, you agree to receive SMS messages from PayBitoPro. Reply STOP to opt out at any time. Reply HELP for customer care contact information. Message and data rates may apply. Message frequency may vary. Phone numbers collected for SMS consent will not be shared with third parties or affiliates for marketing purposes under any circumstance. Check out our Privacy Policy to learn more.

BitcoinBTC/USD

Ether CoinETH/USD

HCX CoinHCX/USD

BCH CoinBCH/USD

LitecoinLTC/USD

EOS CoinEOS/USD

ADA CoinADA/USD

Link CoinLINK/USD

BAT CoinBAT/USD

HBAR CoinHBAR/USD

+
Chat Now
Welcome to Paybito Support