Habify BaseHabify Base
E-CommerceHabify Base · Billing & Commerce Engineering2026-11-268 min read

Building a Complete E-Commerce Storefront with OTP Login, Direct QR Pay & Automated Invoicing

Run a full storefront backend: filterable product catalogs, deduplicated shopping carts, frictionless phone OTP sign-in, direct bank QR checkout, and automated tax e-invoices.

OTP & Password LoginSearch & Cart SyncDirect QR CheckoutAuto E-Invoicing
Habify Base e-commerce backend flow covering carts, OTP login, and direct merchant checkout

You can launch a complete online storefront backend on Habify Base in hours instead of spending weeks stitching user accounts, shopping carts, payment callbacks, and tax invoices together. Host your Next.js or Astro storefront anywhere while Habify Base runs an isolated PostgreSQL 18 database, shopper login, direct checkout, and automated e-invoicing.

Sensitive flows stay cleanly separated between browser and server: browsers query public catalogs and the signed-in shopper's own cart under Row-Level Security, while your server locks authoritative prices before creating a payment session.

1. Storefront Capability Map on Habify Base

From product discovery to post-purchase compliance, six built-in primitives handle the core storefront lifecycle:

Storefront NeedHabify Base SolutionPractical Benefit
Catalog search & paginationMulti-condition filters, exact total counts & read ViewsShow stock and pricing safely straight from the browser
Shopper authenticationIsolated Email/Password or Phone/Email OTP per projectReturning buyers view orders quickly without password friction
Idempotent shopping cartConflict-safe UPSERT per user and product IDPrevents duplicate cart rows on rapid clicks or multi-tab edits
QR & card checkoutDirect BYO merchant accounts + signed payment relayFunds settle straight into your own bank with 0% commission
Automated tax e-invoices7 certified VN e-invoice suppliers (+ POS series M)Supports standard corporate VAT or non-VAT sales receipts
Regulatory storefront pack12 statutory pages & 8 pre-filled filing documentsMatches online.gov.vn notification fields right away

2. Structuring Products, Carts, and Row-Level Order Security

Every table runs under PostgreSQL Default-Deny Row-Level Security. Anonymous shoppers can read active catalog listings, while shopping carts and order histories stay strictly scoped to the signed-in user ID.

To expose combined product attributes in a single read-only query, declare a public SQL View with security_invoker = true so all underlying table policies still apply:

sql
CREATE TABLE public.products (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  sku text NOT NULL UNIQUE,
  name text NOT NULL,
  price_vnd bigint NOT NULL CHECK (price_vnd >= 0),
  stock_qty int NOT NULL DEFAULT 0,
  is_active boolean NOT NULL DEFAULT true
);

ALTER TABLE public.products ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.products FORCE ROW LEVEL SECURITY;
CREATE POLICY products_public_read ON public.products
  FOR SELECT USING (is_active = true);

CREATE TABLE public.cart_items (
  user_id uuid NOT NULL,
  product_id uuid NOT NULL REFERENCES public.products(id) ON DELETE CASCADE,
  qty int NOT NULL CHECK (qty > 0),
  updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, product_id)
);

ALTER TABLE public.cart_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.cart_items FORCE ROW LEVEL SECURITY;
CREATE POLICY cart_owner_all ON public.cart_items
  USING (user_id::text = current_setting('app.current_user_id', true))
  WITH CHECK (user_id::text = current_setting('app.current_user_id', true));

CREATE VIEW public.storefront_catalog
WITH (security_invoker = true) AS
SELECT id, sku, name, price_vnd, (stock_qty > 0) AS in_stock
FROM public.products;

3. Product Search, Phone OTP Login, and Cart Sync with the SDK

In your storefront code, @habifybase/sdk gives you clean browser primitives: filter by name or SKU with exact pagination counts, verify shoppers over BYO phone OTP, and upsert shopping cart items cleanly:

ts
import { HabifyPublicClient } from "@habifybase/sdk";

export const habify = new HabifyPublicClient({
  apiKey: process.env.NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY!,
  projectSlug: "shop-example",
});

// 1. Tìm theo tên hoặc mã SKU kèm tổng số kết quả để phân trang
const { data: items, meta } = await habify.db
  .from("storefront_catalog")
  .select("*", { count: "exact" })
  .or([{ name: { ilike: "%linen%" } }, { sku: { ilike: "%linen%" } }])
  .range(0, 19);

// 2. Đăng nhập nhanh bằng số điện thoại OTP
await habify.auth.sendOtp({
  phone: "0912345678",
  purpose: "login",
  channel: "sms",
  turnstile_token,
});
const session = await habify.auth.verifyOtp({
  phone: "0912345678",
  code: otpCode,
  purpose: "login",
});

// 3. Lưu giỏ hàng an toàn không trùng lặp
await habify.db
  .from("cart_items")
  .upsert(
    { user_id: session.user.id, product_id: productId, qty: 2 },
    { onConflict: "user_id,product_id" },
  );

4. Direct Merchant QR Checkout and Automated E-Invoicing

At checkout, your browser sends product IDs and quantities to your backend Route Handler. The server calculates totals from authoritative PostgreSQL prices and opens a direct BYO merchant session so funds settle straight into your company account with zero platform cut.

Once settled, Habify Base validates the upstream callback, relays a signed payment confirmation event to your shop webhook, updates stock atomically, and issues an e-invoice through your linked tax supplier.

Frequently Asked Questions

How do storefronts prevent buyers from tampering with product prices in the browser?

Compute totals strictly on your server Route Handler using your secret key by reading unit prices from PostgreSQL based on submitted product IDs and quantities.

Does Habify Base charge a transaction percentage on store sales?

No. Checkout flows route directly through your own BYO merchant credentials with 0% commission.

Where should I host my Next.js or Astro storefront UI?

Host your storefront on Vercel, Cloudflare Pages, Netlify, or your own VPS and point it to your Habify Base project endpoint.

Need a SePay Merchant Account?

Customer VietQR transfers and Visa/Mastercard/JCB card payments settle directly into your own bank account. Register with SePay before connecting credentials in your project.

Related Documentation & Guides

Launch This Architecture in Free Sandbox in 3 Minutes

Spin up an isolated PostgreSQL 18 database, grab your hb_pk_* / hb_sk_* keys, and wire @habifybase/sdk.

More Engineering Articles & Use Cases