Skip to Content

集成示例

本章提供完整的集成代码示例,使用标准 HTTP 请求,适用于任何语言和框架。


示例 1: 自定义 React 店铺

使用 React + Fetch 构建自定义店铺前端:

// src/App.tsx import { useEffect, useState } from "react"; const API_URL = import.meta.env.VITE_API_URL; function App() { const [config, setConfig] = useState(null); useEffect(() => { fetch(`${API_URL}/api/config`) .then((res) => res.json()) .then(setConfig); }, []); if (!config) return <div>加载中...</div>; return ( <div className="container"> <h1>{config.storeName}</h1> <div className="products"> {config.categories .flatMap((cat) => cat.products) .map((product) => ( <ProductCard key={product.id} product={product} channels={config.paymentChannels} /> ))} </div> </div> ); } function ProductCard({ product, channels }) { const [email, setEmail] = useState(""); const handleBuy = async () => { const res = await fetch(`${API_URL}/api/orders/create`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ productId: product.id, email, paymentChannelSlug: channels[0]?.slug, quantity: 1, }), }); const result = await res.json(); if (result.payUrl) window.location.href = result.payUrl; }; // ... 渲染 UI }

示例 2: 库存监控脚本 (Python)

监控库存并通过邮件告警:

import requests import time API_URL = 'https://your-domain.com' API_KEY = 'sk_live_xxxxx' # 在后台生成的 API Key def check_stock(): # 获取所有商品(需要认证) res = requests.get( f'{API_URL}/api/admin/products', headers={'Authorization': f'Bearer {API_KEY}'} ) products = res.json().get('data', []) for p in products: print(f"检查商品: {p['name']}, 库存: {p['stock']}") if p['stock'] < 10: send_alert(p['name'], p['stock']) def send_alert(name, stock): print(f"⚠️ 告警: {name} 库存仅剩 {stock}") # 这里可以添加发送邮件的代码... if __name__ == '__main__': while True: check_stock() time.sleep(300) # 每 5 分钟检查一次

示例 3: Node.js 批量生成优惠码

const API_URL = "https://your-domain.com"; const API_KEY = "sk_live_xxxxx"; async function generateCoupons() { const response = await fetch(`${API_URL}/api/admin/coupons/batch`, { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ count: 50, prefix: "VIP", discountType: "PERCENTAGE", discountValue: 20, // 8折 }), }); const data = await response.json(); console.log(`已生成 ${data.count} 个优惠码:`); console.log(data.codes); } generateCoupons();
最后更新于