← 返回列表
全部 Skill›商业 Business›e-commerce

e-commerce

作者 @miles990 · 语言 en
E-commerce platforms, payment processing, and shopping cart patterns
商业 Business支付需海外环境访问网络敏感路径待翻译
最近源活动
—
检测 SKILL.md 语言
en
星标 ★
26
分支 Fork
0
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

E-Commerce Development

Overview

Building e-commerce applications with shopping carts, payment processing, inventory management, and order fulfillment.


Shopping Cart

Cart State Management

interface CartItem {
  productId: string;
  variantId?: string;
  quantity: number;
  price: number;
  name: string;
  image: string;
}

interface Cart {
  id: string;
  items: CartItem[];
  subtotal: number;
  tax: number;
  shipping: number;
  total: number;
  discountCode?: string;
  discountAmount: number;
}

// Zustand cart store
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface CartStore {
  cart: Cart;
  addItem: (item: Omit<CartItem, 'quantity'>, quantity?: number) => void;
  updateQuantity: (productId: string, quantity: number) => void;
  removeItem: (productId: string) => void;
  clearCart: () => void;
  applyDiscount: (code: string) => Promise<void>;
}

const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      cart: createEmptyCart(),

      addItem: (item, quantity = 1) => {
        set((state) => {
          const existingIndex = state.cart.items.findIndex(
            (i) => i.productId === item.productId && i.variantId === item.variantId
          );

          const newItems = [...state.cart.items];
          if (existingIndex >= 0) {
            newItems[existingIndex].quantity += quantity;
          } else {
            newItems.push({ ...item, quantity });
          }

          return { cart: recalculateCart({ ...state.cart, items: newItems }) };
        });
      },

      updateQuantity: (productId, quantity) => {
        set((state) => {
          if (quantity <= 0) {
            return {
              cart: recalculateCart({
                ...state.cart,
                items: state.cart.items.filter((i) => i.productId !== productId),
              }),
            };
          }

          const newItems = state.cart.items.map((item) =>
            item.productId === productId ? { ...item, quantity } : item
          );

          return { cart: recalculateCart({ ...state.cart, items: newItems }) };
        });
      },

      removeItem: (productId) => {
        set((state) => ({
          cart: recalculateCart({
            ...state.cart,
            items: state.cart.items.filter((i) => i.productId !== productId),
          }),
        }));
      },

      clearCart: () => set({ cart: createEmptyCart() }),

      applyDiscount: async (code) => {
        const discount = await validateDiscountCode(code);
        set((state) => ({
          cart: recalculateCart({
            ...state.cart,
            discountCode: code,
            discountAmount: discount.amount,
          }),
        }));
      },
    }),
    { name: 'cart-storage' }
  )
);

function recalculateCart(cart: Cart): Cart {
  const subtotal = cart.items.reduce(
    (sum, item) => sum + item.price * item.quantity,
    0
  );
  const tax = subtotal * 0.1; // 10% tax
  const shipping = subtotal > 100 ? 0 : 9.99;
  const total = subtotal + tax + shipping - cart.discountAmount;

  return { ...cart, subtotal, tax, shipping, total };
}

Payment Processing

Stripe Integration

import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2023-10-16',
});

// Create checkout session
async function createCheckoutSession(cart: Cart, customerId?: string) {
  const session = await stripe.checkout.sessions.create({
    mode: 'payment',
    customer: customerId,
    line_items: cart.items.map((item) => ({
      price_data: {
        currency: 'usd',
        product_data: {
          name: item.name,
          images: [item.image],
        },
        unit_amount: Math.round(item.price * 100),
      },
      quantity: item.quantity,
    })),
    discounts: cart.discountCode
      ? [{ coupon: cart.discountCode }]
      : undefined,
    shipping_address_collection: {
      allowed_countries: ['US', 'CA', 'GB'],
    },
    success_url: `${process.env.APP_URL}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/cart`,
    metadata: {
      cartId: cart.id,
    },
  });

  return session;
}

// Create payment intent (for custom checkout)
async function createPaymentIntent(amount: number, customerId?: string) {
  const paymentIntent = await stripe.paymentIntents.create({
    amount: Math.round(amount * 100),
    currency: 'usd',
    customer: customerId,
    automatic_payment_methods: { enabled: true },
  });

  return {
    clientSecret: paymentIntent.client_secret,
    paymentIntentId: paymentIntent.id,
  };
}

// Webhook handler
async function handleStripeWebhook(body: string, signature: string) {
  const event = stripe.webhooks.constructEvent(
    body,
    signature,
    process.env.STRIPE_WEBHOOK_SECRET!
  );

  switch (event.type) {
    case 'checkout.session.completed': {
      const session = event.data.object as Stripe.Checkout.Session;
      await fulfillOrder(session);
      break;
    }

    case 'payment_intent.succeeded': {
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      await handlePaymentSuccess(paymentIntent);
      break;
    }

    case 'payment_intent.payment_failed': {
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      await handlePaymentFailure(paymentIntent);
      break;
    }
  }
}

React Stripe Elements

import { loadStripe } from 
评论
Mmiles990
miles990
miles990/claude-software-skills
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@miles990
所属大类商业 Business / 支付
国内可用性需海外环境
最近源活动—
风险提示访问网络、敏感路径
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。