Compare commits

...
4 Commits
Author SHA1 Message Date
jinghui b7a10ca678 feat(ui): 站点货币单位由美元改为人民币
release / release (release) Canceled after 0s
- currency.ts: formatCurrency/formatPrice/formatBalance/getCurrencySymbol 默认币种
  USD→CNY,Intl locale en-US→zh-CN,显示为 ¥ 而非 CN¥
- 平台配置与管理后台默认 currency: USD→CNY
- 硬编码 $ 符号处(商品价格/余额表/充值弹窗/控制台营收/主题 Demo)全部改 ¥
- i18n: 'Minimum recharge amount is $1' key 改为 ¥1(中英同步)
- 说明: 易支付 exchange_rate=1,余额数值即人民币,仅改显示符号不改数值
2026-11-13 18:53:57 +08:00
jinghui 8f0796c031 fix(payment): epay异步回调免鉴权 + Dockerfile构建代理参数
release / release (release) Canceled after 0s
- /api/payment/callback_epay 与 refund_callback_epay 加入 NO_AUTH 白名单,
  易支付异步notify无用户token,此前被401拦截导致订单无法回执
- Dockerfile 增加 HTTP(S)_PROXY 构建参数,受限网络可构建
2026-11-13 18:16:29 +08:00
jinghui 721a2be32b feat(payment): integrate epay (易支付) gateway for CNY recharges
release / release (release) Canceled after 0s
- new EpayClient: V1 md5 signing, submit.php page pay, api.php order query
- create/verify epay payment links with CNY exchange-rate conversion
- signed async notify handler (/admin/payment/callback_epay) with amount
  check plus idempotent crediting, and a gateway query fallback
- epay channel config form, channel row and payment_method enum extended
- RechargeModal: send payment_method (was payment_channel, so every recharge
  fell through to Stripe and 500'd) and re-enable the channel picker
- payment config encryption key moved to a local .env, never committed
2026-11-13 15:17:05 +08:00
jinghui 1fbb6711f2 feat(submission): auto-publish approved submissions and expose review tab
- approving a submission now creates the McpService/McpToolApi records
- and records the published service id back on the submission
- review console folded into the admin console as a Submissions tab
- submit page rewritten around the shared submission API
2026-11-13 15:17:05 +08:00
31 changed files with 1327 additions and 120 deletions

No files matched your search

+6
View File
@@ -23,6 +23,12 @@ services:
container_name: xpack-mcp-market
privileged: true
restart: always
environment:
# AES-256-GCM key protecting payment channel config (epay merchant key, stripe secret).
# Lives here rather than in the image so the sample key shipped in .env.example
# can never decrypt this deployment's config.
- PAYMENT_CONFIG_SECRET_KEY=${PAYMENT_CONFIG_SECRET_KEY:?PAYMENT_CONFIG_SECRET_KEY not set - copy .env.example to .env}
- PAYMENT_CONFIG_KEY_ID=default
networks:
- xpack
ports:
+1 -1
View File
@@ -328,7 +328,7 @@
"Current Balance": "Current Balance",
"User recharged successfully": "User recharged successfully",
"Please enter a valid amount": "Please enter a valid amount",
"Minimum recharge amount is $1": "Minimum recharge amount is $1",
"Minimum recharge amount is ¥1": "Minimum recharge amount is ¥1",
"User not selected": "User not selected",
"Recharge failed": "Recharge failed",
"Network error, please try again": "Network error, please try again",
@@ -330,7 +330,7 @@
"Current Balance": "当前余额",
"User recharged successfully": "用户充值成功",
"Please enter a valid amount": "请输入有效金额",
"Minimum recharge amount is $1": "最低充值金额为 $1",
"Minimum recharge amount is ¥1": "最低充值金额为 ¥1",
"User not selected": "未选择用户",
"Recharge failed": "充值失败",
"Network error, please try again": "网络错误,请重试",
+3 -51
View File
@@ -1,55 +1,7 @@
"use client";
import React, { useEffect, useState } from "react";
import React from "react";
import { SubmissionsManagement } from "@/components/console/SubmissionsManagement";
export default function AdminSubmissionsPage() {
const [list, setList] = useState<any[]>([]);
const [status, setStatus] = useState("pending");
const load = async () => {
const res = await fetch(`/api/submission/admin/submissions?status=${status}`, { credentials: "include" });
const data = await res.json();
setList(data?.data || []);
};
useEffect(() => { load(); }, [status]);
const approve = async (id: string) => {
await fetch(`/api/submission/admin/submission/${id}/approve`, { method: "PUT", credentials: "include" });
load();
};
const reject = async (id: string) => {
await fetch(`/api/submission/admin/submission/${id}/reject`, { method: "PUT", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ note: "rejected" }) });
load();
};
return (
<div className="max-w-4xl mx-auto p-6">
<h1 className="text-2xl font-bold mb-4">提交审核</h1>
<select value={status} onChange={e => setStatus(e.target.value)} className="border p-2 mb-4">
<option value="pending">待审核</option>
<option value="approved">已通过</option>
<option value="rejected">已拒绝</option>
</select>
<table className="w-full border">
<thead><tr><th>名称</th><th>类型</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
{list.map((s: any) => (
<tr key={s.id} className="border-t">
<td className="p-2">{s.name}</td>
<td className="p-2">{s.type}</td>
<td className="p-2">{s.status}</td>
<td className="p-2">
{s.status === "pending" && (
<>
<button onClick={() => approve(s.id)} className="text-green-600 mr-2">通过</button>
<button onClick={() => reject(s.id)} className="text-red-600">拒绝</button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
return <SubmissionsManagement />;
}
+150 -17
View File
@@ -1,40 +1,173 @@
"use client";
import React, { useState } from "react";
import { fetchAPI } from "@/shared/rpc/common-function";
type SubType = "mcp" | "skill" | "plugin";
export default function SubmitPage() {
const [type, setType] = useState("mcp");
const [type, setType] = useState<SubType>("mcp");
const [name, setName] = useState("");
const [desc, setDesc] = useState("");
const [file, setFile] = useState<File | null>(null);
const [msg, setMsg] = useState("");
const [baseUrl, setBaseUrl] = useState("");
const [serviceType, setServiceType] = useState("openapi");
const [tags, setTags] = useState("");
const [chargeType, setChargeType] = useState<"free" | "paid">("free");
const [price, setPrice] = useState("");
const [freeDailyLimit, setFreeDailyLimit] = useState("");
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const fd = new FormData();
fd.append("type", type);
fd.append("name", name);
if (desc) fd.append("description", desc);
if (file) fd.append("file", file);
const res = await fetch("/api/submission/submission", { method: "POST", body: fd, credentials: "include" });
const data = await res.json();
setMsg(JSON.stringify(data));
setMsg(null);
if (typeof window !== "undefined" && !localStorage.getItem("user_token")) {
setMsg({ ok: false, text: "请先登录后再提交(右上角登录)" });
return;
}
if (type === "mcp" && !baseUrl.trim()) {
setMsg({ ok: false, text: "MCP 服务必须填写服务地址 base_url" });
return;
}
setSubmitting(true);
try {
const fd = new FormData();
fd.append("type", type);
fd.append("name", name);
if (desc) fd.append("description", desc);
if (file) fd.append("file", file);
if (type === "mcp") {
fd.append("base_url", baseUrl.trim());
fd.append("service_type", serviceType);
if (tags.trim()) fd.append("tags", tags.trim());
fd.append("charge_type", chargeType);
if (chargeType === "paid" && price) fd.append("price", price);
if (chargeType === "free" && freeDailyLimit) fd.append("free_daily_limit", freeDailyLimit);
}
const data = await fetchAPI<{ success: boolean; error_message?: string; data?: { id: string; status: string } }>(
"/api/submission/submission",
{ method: "POST", body: fd }
);
if (data?.success) {
setMsg({ ok: true, text: "提交成功,等待管理员审核。审核通过后将自动上架到市场。" });
setName(""); setDesc(""); setFile(null); setBaseUrl(""); setTags("");
} else {
setMsg({ ok: false, text: data?.error_message || "提交失败,请稍后重试" });
}
} catch (err) {
setMsg({ ok: false, text: "提交失败:" + (err as Error).message });
} finally {
setSubmitting(false);
}
};
const inputCls = "border p-2 w-full rounded";
return (
<div className="max-w-xl mx-auto p-6">
<h1 className="text-2xl font-bold mb-4">上传 MCP / Skill / Plugin</h1>
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-bold">上传 MCP / Skill / Plugin</h1>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<select value={type} onChange={e => setType(e.target.value)} className="border p-2 w-full">
<select value={type} onChange={(e) => setType(e.target.value as SubType)} className={inputCls}>
<option value="mcp">MCP 服务</option>
<option value="skill">AI 技能</option>
<option value="plugin">AI 插件</option>
</select>
<input value={name} onChange={e => setName(e.target.value)} placeholder="名称" className="border p-2 w-full" required />
<textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder="描述" className="border p-2 w-full" />
<input type="file" onChange={e => setFile(e.target.files?.[0] || null)} className="border p-2 w-full" />
<button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded">提交</button>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="名称" className={inputCls} required />
<textarea value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="描述" className={inputCls} rows={3} />
{type === "mcp" && (
<div className="space-y-3 border rounded p-3 bg-gray-50">
<div>
<label className="block text-sm font-medium mb-1">服务地址 base_url *</label>
<input
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
placeholder="http://192.168.1.10:8020"
className={inputCls}
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">服务类型</label>
<select value={serviceType} onChange={(e) => setServiceType(e.target.value)} className={inputCls}>
<option value="openapi">openapi(HTTP 接口)</option>
</select>
</div>
<div>
<label className="block text-sm font-medium mb-1">标签(逗号分隔)</label>
<input value={tags} onChange={(e) => setTags(e.target.value)} placeholder="工具, 搜索, 免费" className={inputCls} />
</div>
<div>
<label className="block text-sm font-medium mb-1">计费方式</label>
<select
value={chargeType}
onChange={(e) => setChargeType(e.target.value as "free" | "paid")}
className={inputCls}
>
<option value="free">免费</option>
<option value="paid">按次付费</option>
</select>
</div>
{chargeType === "paid" ? (
<div>
<label className="block text-sm font-medium mb-1">单价(元/次)</label>
<input
type="number" step="0.01" min="0"
value={price}
onChange={(e) => setPrice(e.target.value)}
placeholder="0.10"
className={inputCls}
/>
</div>
) : (
<div>
<label className="block text-sm font-medium mb-1">每日免费次数(留空 = 不限)</label>
<input
type="number" min="1"
value={freeDailyLimit}
onChange={(e) => setFreeDailyLimit(e.target.value)}
placeholder="100"
className={inputCls}
/>
</div>
)}
<div>
<label className="block text-sm font-medium mb-1">
OpenAPI 规范文件(.json,用于自动生成工具列表)
</label>
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
<p className="text-xs text-gray-500 mt-1">
上传后审核通过会自动生成工具;不上传则上架后需在服务管理里手动添加工具。
</p>
</div>
</div>
)}
{type !== "mcp" && (
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
)}
<button
type="submit"
disabled={submitting}
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
>
{submitting ? "提交中..." : "提交"}
</button>
</form>
{msg && <pre className="mt-4 text-sm">{msg}</pre>}
{msg && (
<pre className={`mt-4 text-sm whitespace-pre-wrap ${msg.ok ? "text-green-700" : "text-red-600"}`}>
{msg.text}
</pre>
)}
</div>
);
}
@@ -233,9 +233,9 @@ const ConsoleStats: React.FC = () => {
return transformToChartData(analyticsData);
}, [analyticsData]);
// Format revenue as currency (USD by default)
const formatCurrency = (value: number, currency: string = "USD") =>
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(
// Format revenue as currency (CNY by default)
const formatCurrency = (value: number, currency: string = "CNY") =>
new Intl.NumberFormat("zh-CN", { style: "currency", currency }).format(
value
);
if (loading) {
+21 -4
View File
@@ -12,7 +12,7 @@ import UserManagement from "@/components/user-management/UserManagement";
import RevenueManagement from "@/components/revenue-management/RevenueManagement";
import ConsoleSidebar from "./Sidebar";
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
import { Boxes, DollarSign, Home, ServerIcon, Users } from "lucide-react";
import { Boxes, DollarSign, Home, Inbox, ServerIcon, Users } from "lucide-react";
import OnboardingWelcome, { REQUIRED_TASK_KEYS } from "./OnboardingWelcome";
import ConsoleStats from "./ConsoleStats";
import SystemSettingsModal from "./SystemSettingsModal";
@@ -24,6 +24,7 @@ import {
updateAdminOnboardingTasks,
} from "@/api/onboard.api";
import ResourceGroupManagement from "../resource-group/resourceGroup";
import { SubmissionsManagement } from "./SubmissionsManagement";
const ConsoleContent: React.FC = () => {
const { t } = useTranslation();
@@ -37,9 +38,13 @@ const ConsoleContent: React.FC = () => {
const tabFromUrl = searchParams.get("tab") as TabKey;
if (
tabFromUrl &&
["mcp-services", "user-management", "revenue-management", "resource-group"].includes(
tabFromUrl
)
[
"mcp-services",
"user-management",
"revenue-management",
"resource-group",
"submissions",
].includes(tabFromUrl)
) {
return tabFromUrl;
}
@@ -69,6 +74,12 @@ const ConsoleContent: React.FC = () => {
label: t("MCP"),
description: t("Manage MCP servers and API tools"),
},
{
key: TabKey.SUBMISSIONS,
icon: <Inbox size={18} />,
label: t("Submissions"),
description: t("Review user submissions and publish to marketplace"),
},
{
key: TabKey.USER_MANAGEMENT,
icon: <Users size={18} />,
@@ -213,6 +224,12 @@ const ConsoleContent: React.FC = () => {
switch (activeTab) {
case TabKey.MCP_SERVICES:
return <MCPServicesManagement />;
case TabKey.SUBMISSIONS:
return (
<div className="h-full overflow-auto">
<SubmissionsManagement />
</div>
);
case TabKey.USER_MANAGEMENT:
return (
<div className="h-full overflow-auto">
@@ -4,6 +4,7 @@ import React from "react";
import { StripeConfigForm } from "../payment/StripeConfigForm";
import { AlipayConfigForm } from "../payment/AlipayConfigForm";
import { WechatConfigForm } from "../payment/WechatConfigForm";
import { EpayConfigForm } from "../payment/EpayConfigForm";
import { usePaymentChannelManagement } from "@/hooks/usePaymentChannelManagement";
interface PaymentChannelsContentProps {
@@ -17,12 +18,15 @@ export const PaymentChannelsContent: React.FC<PaymentChannelsContentProps> = ({
stripeConfig,
alipayConfig,
wechatConfig,
epayConfig,
isWechatSaving,
isStripeSaving,
isAlipaySaving,
isEpaySaving,
saveStripeConfig,
saveAlipayConfig,
saveWechatConfig,
saveEpayConfig,
enableChannel,
disableChannel,
} = usePaymentChannelManagement();
@@ -38,6 +42,15 @@ export const PaymentChannelsContent: React.FC<PaymentChannelsContentProps> = ({
isLoading={isStripeSaving}
labelPlacement={labelPlacement}
/>
{/* epay (易支付) configuration */}
<EpayConfigForm
config={epayConfig}
onSave={saveEpayConfig}
onEnable={enableChannel}
onDisable={disableChannel}
isLoading={isEpaySaving}
labelPlacement={labelPlacement}
/>
{/* coming soon */}
{/* alipay configuration */}
{/* <AlipayConfigForm
@@ -0,0 +1,173 @@
"use client";
import React, { useEffect, useState } from "react";
import { fetchAdminAPI } from "@/rpc/admin-api";
interface Metadata {
base_url?: string;
service_type?: string;
tags?: string;
charge_type?: string;
price?: number;
free_daily_limit?: number | null;
published_service_id?: string;
}
interface Submission {
id: string;
user_id: string;
type: string;
name: string;
description?: string;
file_path?: string;
metadata_json?: Metadata | null;
status: string;
created_at?: string;
review_note?: string;
}
const statusColor: Record<string, string> = {
pending: "bg-yellow-100 text-yellow-800",
approved: "bg-green-100 text-green-800",
rejected: "bg-red-100 text-red-800",
};
export function SubmissionsManagement() {
const [subs, setSubs] = useState<Submission[]>([]);
const [filter, setFilter] = useState<string>("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [rejectNote, setRejectNote] = useState<Record<string, string>>({});
const load = async () => {
setLoading(true);
setError("");
try {
const qs = filter ? `?status=${filter}` : "";
// fetchAdminAPI<T> already returns the { success, error_message, data } envelope
const response = await fetchAdminAPI<Submission[]>(
`/api/submission/admin/submissions${qs}`
);
if (response?.success === false) {
setError(response.error_message || "加载失败");
setSubs([]);
} else if (response?.data) {
setSubs(response.data);
} else {
setSubs([]);
}
} catch (err) {
setError("加载失败:" + (err as Error).message);
setSubs([]);
} finally {
setLoading(false);
}
};
useEffect(() => { load(); }, [filter]);
const act = async (id: string, action: "approve" | "reject") => {
const body: RequestInit =
action === "approve"
? { method: "PUT" }
: {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ note: rejectNote[id] || "" }),
};
await fetchAdminAPI(`/api/submission/admin/submission/${id}/${action}`, body);
load();
};
return (
<div className="max-w-6xl mx-auto p-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-bold">投稿审核</h1>
<select value={filter} onChange={(e) => setFilter(e.target.value)} className="border p-2">
<option value="">全部</option>
<option value="pending">待审核</option>
<option value="approved">已通过</option>
<option value="rejected">已拒绝</option>
</select>
</div>
{error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded">{error}</div>}
{loading && <div className="mb-4 text-gray-500">加载中...</div>}
{!loading && !error && subs.length === 0 && (
<div className="mb-4 text-gray-500">暂无提交记录</div>
)}
<div className="space-y-4">
{subs.map((s) => {
const meta = s.metadata_json || {};
return (
<div key={s.id} className="border rounded p-4 space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="font-semibold">{s.name}</span>
<span className="px-2 py-0.5 rounded text-xs">{s.type}</span>
<span className={`px-2 py-0.5 rounded text-xs ${statusColor[s.status] || "bg-gray-100"}`}>{s.status}</span>
</div>
<span className="text-sm text-gray-500">{s.created_at?.slice(0, 19).replace("T", " ")}</span>
</div>
{s.description && <p className="text-sm text-gray-700">{s.description}</p>}
{s.type === "mcp" && (meta.base_url || meta.tags || meta.charge_type) && (
<div className="text-sm text-gray-600 bg-gray-50 rounded p-2 space-y-1">
{meta.base_url && <div>服务地址:<code className="text-xs">{meta.base_url}</code></div>}
{meta.tags && <div>标签:{meta.tags}</div>}
<div>
计费:
{meta.charge_type === "paid"
? `按次付费 ¥${meta.price ?? 0}/次`
: `免费${meta.free_daily_limit ? `(每日 ${meta.free_daily_limit} 次)` : "(不限次)"}`}
</div>
{meta.published_service_id && (
<div className="text-green-700">
已上架市场,服务 ID:<code className="text-xs">{meta.published_service_id}</code>
</div>
)}
</div>
)}
{s.file_path && (
<div className="text-sm text-gray-500">
附件:<code className="text-xs">{s.file_path}</code>
</div>
)}
{s.review_note && (
<div className="text-sm text-gray-600">审核备注:{s.review_note}</div>
)}
{s.status === "pending" ? (
<div className="space-y-2">
<input
value={rejectNote[s.id] || ""}
onChange={(e) => setRejectNote({ ...rejectNote, [s.id]: e.target.value })}
placeholder="拒绝原因(可选)"
className="border p-2 w-full text-sm"
/>
<div className="flex gap-2">
<button
onClick={() => act(s.id, "approve")}
className="bg-green-600 text-white px-3 py-1 rounded text-sm"
>
通过(自动上架)
</button>
<button
onClick={() => act(s.id, "reject")}
className="bg-red-600 text-white px-3 py-1 rounded text-sm"
>
拒绝
</button>
</div>
</div>
) : null}
</div>
);
})}
</div>
</div>
);
}
@@ -170,25 +170,25 @@ const AccountBalanceTable: React.FC<AccountBalanceTableProps> = ({ userId, sourc
);
};
// 格式化金额,带正负号和美元符号
// 格式化金额,带正负号和人民币符号
const formatAmount = (amount: string | number): string => {
const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
if (isNaN(numAmount)) return '$0.00';
if (isNaN(numAmount)) return '¥0.00';
const absAmount = Math.abs(numAmount).toFixed(2);
if (numAmount > 0) {
return `+$${absAmount}`;
return `+¥${absAmount}`;
} else if (numAmount < 0) {
return `-$${absAmount}`;
return `-¥${absAmount}`;
}
return `$${absAmount}`;
return `¥${absAmount}`;
};
// 格式化余额,只显示美元符号,不带正负号
// 格式化余额,只显示人民币符号,不带正负号
const formatBalance = (balance: string | number): string => {
const numBalance = typeof balance === 'string' ? parseFloat(balance) : balance;
if (isNaN(numBalance)) return '$0.00';
if (isNaN(numBalance)) return '¥0.00';
return `$${Math.abs(numBalance).toFixed(2)}`;
return `¥${Math.abs(numBalance).toFixed(2)}`;
};
const getStatusColor = (status: number) => {
@@ -0,0 +1,234 @@
"use client";
import React, { useEffect, useState } from "react";
import { Input, Button, AccordionItem, Accordion, Switch } from "@nextui-org/react";
import { Eye, EyeOff } from "lucide-react";
import { EpayChannelConfig } from "@/types/payment";
import { useTranslation } from "@/shared/lib/useTranslation";
interface EpayConfigFormProps {
config: EpayChannelConfig;
onSave: (config: EpayChannelConfig) => void;
onEnable: (channelId: string) => Promise<boolean>;
onDisable: (channelId: string) => Promise<boolean>;
isLoading?: boolean;
labelPlacement?: "outside" | "inside";
}
export const EpayConfigForm: React.FC<EpayConfigFormProps> = ({
config,
onSave,
onEnable,
onDisable,
isLoading = false,
labelPlacement = "inside",
}) => {
const { t } = useTranslation();
const [formData, setFormData] = useState<EpayChannelConfig>(config);
const [showKey, setShowKey] = useState(false);
useEffect(() => {
setFormData(config);
}, [config]);
const handleInputChange = (field: keyof EpayChannelConfig, value: string | boolean) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const handleEnableDisable = async (value: boolean) => {
const result = value ? await onEnable("epay") : await onDisable("epay");
if (result) {
setFormData((prev) => ({ ...prev, is_enabled: value }));
}
};
const handleSave = () => onSave(formData);
const isFormValid =
!!formData?.gateway?.trim() && !!formData?.pid?.trim() && !!formData?.key?.trim();
const panelContent = () => (
<>
<div className={`flex flex-col gap-4 ${formData.is_enabled ? "" : "hidden"}`}>
<Input
label={t("Gateway URL")}
placeholder="https://pay.example.com"
description={t("Epay gateway base address, no trailing slash")}
value={formData.gateway || ""}
onChange={(e) => handleInputChange("gateway", e.target.value)}
isRequired
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
<Input
label={t("Merchant ID (pid)")}
placeholder={t("Enter Merchant ID")}
description={t("Numeric merchant id issued by the epay platform")}
value={formData.pid || ""}
onChange={(e) => handleInputChange("pid", e.target.value)}
isRequired
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
<Input
label={t("Merchant Key (key)")}
placeholder={t("Enter Merchant Key")}
description={t("Used to sign requests and verify notifications, 32 characters")}
value={formData.key || ""}
onChange={(e) => handleInputChange("key", e.target.value)}
type={showKey ? "text" : "password"}
isRequired
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
endContent={
<button
type="button"
onClick={() => setShowKey(!showKey)}
className="focus:outline-none"
>
{showKey ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
/>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium">{t("Payment Method")}</label>
<select
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
value={formData.pay_type || ""}
disabled={!formData.is_enabled}
onChange={(e) => handleInputChange("pay_type", e.target.value)}
>
<option value="">{t("Let customer choose at checkout")}</option>
<option value="alipay">{t("Alipay")}</option>
<option value="wxpay">{t("WeChat Pay")}</option>
<option value="qqpay">{t("QQ Wallet")}</option>
</select>
<span className="text-xs text-gray-500">
{t("Leave empty to show the gateway cashier with all methods")}
</span>
</div>
<Input
label={t("Exchange Rate")}
placeholder="1"
description={t(
"CNY charged per 1 balance unit. Default 1 means 1:1. e.g. 7 means a $10 recharge bills ¥70"
)}
value={String(formData.exchange_rate ?? 1)}
onChange={(e) => handleInputChange("exchange_rate", e.target.value)}
type="number"
min="0"
step="0.01"
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
<Input
label={t("Notify URL (optional)")}
placeholder={t("Auto derived from the site URL when empty")}
description={t(
"Async payment notification address that the gateway can reach from the internet"
)}
value={formData.notify_url || ""}
onChange={(e) => handleInputChange("notify_url", e.target.value)}
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
<Input
label={t("Return URL (optional)")}
placeholder={t("Auto derived when empty")}
description={t("Page opened after the customer finishes paying")}
value={formData.return_url || ""}
onChange={(e) => handleInputChange("return_url", e.target.value)}
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
</div>
{formData.is_enabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
isDisabled={!isFormValid}
size="sm"
>
{t("Save")}
</Button>
</div>
)}
</>
);
if (labelPlacement === "outside") {
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">{t("Enable Epay Payment")}</span>
<span className="text-xs text-gray-500">
{t("Alipay / WeChat Pay through your own epay gateway")}
</span>
</div>
<Switch
isSelected={formData.is_enabled || false}
onValueChange={handleEnableDisable}
color="primary"
size="sm"
/>
</div>
{panelContent()}
</div>
);
}
return (
<Accordion
variant="splitted"
itemClasses={{ base: "shadow-none border-1" }}
defaultExpandedKeys={["epay-config"]}
className="px-0"
>
<AccordionItem
key="epay-config"
title={
<div className="flex flex-col justify-between">
<div className="flex items-center justify-between w-full">
<div>
<h3 className="text-lg font-semibold">{t("Epay Configuration")}</h3>
<p className="text-sm text-gray-500">
{t("Configure your epay (Epay) gateway")}
</p>
</div>
<Switch
isSelected={formData.is_enabled || false}
onValueChange={handleEnableDisable}
size="sm"
/>
</div>
</div>
}
>
{panelContent()}
</AccordionItem>
</Accordion>
);
};
export default EpayConfigForm;
@@ -67,7 +67,7 @@ const DefaultDemo: React.FC = () => {
<span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
Beta
</span>
<span className="text-xs text-gray-500">$0.02 /Per Call</span>
<span className="text-xs text-gray-500">¥0.02 /Per Call</span>
</div>
</div>
@@ -79,7 +79,7 @@ const DefaultDemo: React.FC = () => {
<span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
Beta
</span>
<span className="text-xs text-gray-500">$0.02 /Per Call</span>
<span className="text-xs text-gray-500">¥0.02 /Per Call</span>
</div>
</div>
+2 -2
View File
@@ -68,7 +68,7 @@ const TemuDemo: React.FC = () => {
</p>
</div>
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-orange-600">$9.99</span>
<span className="text-xs font-bold text-orange-600">¥9.99</span>
<div className="flex items-center gap-1">
<Star className="w-2 h-2 text-yellow-400 fill-current" />
<span className="text-xs text-gray-500">4.8</span>
@@ -87,7 +87,7 @@ const TemuDemo: React.FC = () => {
</p>
</div>
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-orange-600">$14.99</span>
<span className="text-xs font-bold text-orange-600">¥14.99</span>
<div className="flex items-center gap-1">
<Star className="w-2 h-2 text-yellow-400 fill-current" />
<span className="text-xs text-gray-500">4.9</span>
@@ -46,7 +46,7 @@ export const AdminRechargeModal: React.FC<AdminRechargeModalProps> = ({
}
if (numAmount < 1) {
setError(t("Minimum recharge amount is $1"));
setError(t("Minimum recharge amount is ¥1"));
return;
}
@@ -102,7 +102,7 @@ export const AdminRechargeModal: React.FC<AdminRechargeModalProps> = ({
onChange={handleAmountChange}
startContent={
<div className="pointer-events-none flex items-center">
<span className="text-default-400 text-small">$</span>
<span className="text-default-400 text-small">¥</span>
</div>
}
isInvalid={!!error}
@@ -4,6 +4,7 @@ import {
StripeConfig,
AlipayConfig,
WechatConfig,
EpayChannelConfig,
PaymentChannelTestResult,
} from "@/types/payment";
import { paymentChannelService } from "@/services/paymentChannelService";
@@ -29,6 +30,14 @@ export const usePaymentChannelManagement = () => {
mch_id: "",
is_enabled: false,
});
const [epayConfig, setEpayConfig] = useState<EpayChannelConfig>({
gateway: "",
pid: "",
key: "",
pay_type: "",
exchange_rate: 1,
is_enabled: false,
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [testResult, setTestResult] = useState<PaymentChannelTestResult | null>(
@@ -37,6 +46,7 @@ export const usePaymentChannelManagement = () => {
const [isWechatSaving, setIsWechatSaving] = useState(false);
const [isStripeSaving, setIsStripeSaving] = useState(false);
const [isAlipaySaving, setIsAlipaySaving] = useState(false);
const [isEpaySaving, setIsEpaySaving] = useState(false);
// get payment channel list
const fetchChannels = useCallback(async () => {
@@ -69,6 +79,16 @@ export const usePaymentChannelManagement = () => {
} as AlipayConfig);
}
const epayChannel = response.data.find(
(channel) => channel.id === "epay"
);
if (epayChannel) {
setEpayConfig({
...epayChannel.config,
is_enabled: epayChannel.is_enabled,
} as EpayChannelConfig);
}
const wechatChannel = response.data.find(
(channel) => channel.id === "wechat"
);
@@ -184,6 +204,28 @@ export const usePaymentChannelManagement = () => {
}
}, []);
// save epay config
const saveEpayConfig = useCallback(async (config: EpayChannelConfig) => {
setIsEpaySaving(true);
setError(null);
try {
const result = await paymentChannelService.saveEpayConfig(config);
if (result) {
setEpayConfig(config);
return true;
}
return false;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : "Failed to save epay config";
setError(errorMessage);
return false;
} finally {
setIsEpaySaving(false);
}
}, []);
// save stripe config
const saveStripeConfig = useCallback(async (config: StripeConfig) => {
setIsStripeSaving(true);
@@ -316,6 +358,8 @@ export const usePaymentChannelManagement = () => {
stripeConfig,
alipayConfig,
wechatConfig,
epayConfig,
isEpaySaving,
isWechatSaving,
isStripeSaving,
isAlipaySaving,
@@ -326,6 +370,7 @@ export const usePaymentChannelManagement = () => {
saveStripeConfig,
saveAlipayConfig,
saveWechatConfig,
saveEpayConfig,
testStripeConnection,
testAlipayConnection,
testWechatConnection,
@@ -18,7 +18,7 @@ export const useSystemConfigManagement = () => {
const [platformConfig, setPlatformConfig] = useState<PlatformConfig>({
name: "",
logo: "",
currency: "USD",
currency: "CNY",
});
const [platformLoading, setPlatformLoading] = useState(false);
const [platformError, setPlatformError] = useState<string | null>(null);
@@ -2,6 +2,7 @@ import {
StripeConfig,
AlipayConfig,
WechatConfig,
EpayChannelConfig,
PaymentChannelApiItem,
PaymentChannelListResponse,
PaymentChannelTestResult,
@@ -187,6 +188,11 @@ export class PaymentChannelService {
return this.savePaymentChannelConfig("wechat", config, "WeChat");
}
// Save Epay (易支付) configuration
async saveEpayConfig(config: EpayChannelConfig): Promise<boolean> {
return this.savePaymentChannelConfig("epay", config, "Epay");
}
// Test Alipay connection
async testAlipayConnection(
config: AlipayConfig
@@ -38,7 +38,7 @@ export const Price: React.FC<PriceProps> = ({
return (
<div className="flex items-center gap-1">
<span className="text-sm font-medium text-green-600">
${priceText.toFixed(2)}
¥{priceText.toFixed(2)}
</span>
<span className="text-xs text-gray-500">/{t("Per Call")}</span>
</div>
@@ -51,14 +51,14 @@ export const Price: React.FC<PriceProps> = ({
<div className="flex items-center gap-1">
<span className="text-gray-600">{t("Input")}:</span>
<span className="font-medium text-green-600">
${inputPrice.toFixed(2)}
¥{inputPrice.toFixed(2)}
</span>
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
</div>
<div className="flex items-center gap-1">
<span className="text-gray-600">{t("Output")}:</span>
<span className="font-medium text-blue-600">
${outputPrice.toFixed(2)}
¥{outputPrice.toFixed(2)}
</span>
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
</div>
@@ -33,6 +33,17 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
paymentChannels[0]?.id || ""
);
// payment channels arrive asynchronously -- fall back to the first one so the
// confirm button is not stuck disabled on a modal opened before they load.
const effectiveChannel = selectedPaymentChannel || paymentChannels[0]?.id || "";
const currencySymbol = effectiveChannel === "epay" ? "¥" : "¥";
const channelLabel = (id: string, name: string) => {
if (id === "epay") return t("Epay (Alipay / WeChat)");
if (id === "stripe") return name || t("Credit Card");
return name || id;
};
const [paymentId, setPaymentId] = useState("");
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
@@ -44,11 +55,11 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
}
if (numAmount < 1) {
setError(t("Minimum recharge amount is $1"));
setError(t("Minimum recharge amount is ¥1"));
return;
}
if (!selectedPaymentChannel) {
if (!effectiveChannel) {
setError(t("Please select a payment method"));
return;
}
@@ -57,7 +68,9 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
method: "POST",
body: {
amount: numAmount,
payment_channel: selectedPaymentChannel,
currency: effectiveChannel === "epay" ? "cny" : "usd",
// channel id doubles as the payment method the backend switches on
payment_method: effectiveChannel,
success_url: window.location.origin + "/pay_success",
} as unknown as BodyInit,
});
@@ -128,7 +141,9 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
onChange={handleAmountChange}
startContent={
<div className="pointer-events-none flex items-center">
<span className="text-default-400 text-small">$</span>
<span className="text-default-400 text-small">
{currencySymbol}
</span>
</div>
}
type="text"
@@ -144,15 +159,13 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
}
}}
/>
{/**coming soon : select payment channel*/}
{/* {paymentChannels.length > 0 && (
{paymentChannels.length > 1 && (
<div className="space-y-2">
<label className="text-sm font-medium text-default-700">
{t("Payment Method")}
</label>
<RadioGroup
value={selectedPaymentChannel}
value={effectiveChannel}
onValueChange={setSelectedPaymentChannel}
isInvalid={!!error && error.includes("payment method")}
errorMessage={
@@ -165,12 +178,20 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
>
{paymentChannels.map((channel) => (
<Radio key={channel.id} value={channel.id}>
{channel.name}
{channelLabel(channel.id, channel.name)}
</Radio>
))}
</RadioGroup>
</div>
)} */}
)}
{effectiveChannel === "epay" && (
<p className="text-xs text-default-500">
{t(
"Billed in CNY via your epay gateway (Alipay / WeChat Pay), credited to your balance 1:1"
)}
</p>
)}
</ModalBody>
<ModalFooter>
<Button variant="light" onPress={handleClose}>
@@ -179,7 +200,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
<Button
color="primary"
onPress={handlePurchase}
isDisabled={!selectedPaymentChannel || !amount}
isDisabled={!effectiveChannel || !amount}
>
{t("Confirm")}
</Button>
@@ -14,7 +14,7 @@ import {
export const _DefaultPlatformConfig: PlatformConfig = {
name: "XPack",
logo: "/static/logo/logo.png",
currency: "USD",
currency: "CNY",
language: "en",
website_title: "Connect Your AI Agent to the Real World - XPack",
headline: "Connect Your AI Agent to the Real World",
+1
View File
@@ -4,6 +4,7 @@ export enum TabKey {
USER_MANAGEMENT = "user-management",
RESOURCE_GROUP = "resource-group",
REVENUE_MANAGEMENT = "revenue-management",
SUBMISSIONS = "submissions",
PAYMENT_CHANNELS = "payment-channels",
LOGIN_SETTINGS = "login-settings",
SYSTEM_SETTINGS = "system-settings",
+6 -6
View File
@@ -17,7 +17,7 @@ export interface CurrencyFormatOptions {
*/
export const formatCurrency = (
amount: number | undefined | null,
currency: string = 'USD',
currency: string = 'CNY',
options: CurrencyFormatOptions = {}
): string => {
// 处理无效值
@@ -33,7 +33,7 @@ export const formatCurrency = (
try {
if (showSymbol) {
return new Intl.NumberFormat('en-US', {
return new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: currency,
minimumFractionDigits,
@@ -64,7 +64,7 @@ export const formatCurrency = (
*/
export const formatPrice = (
priceInCents: number | undefined | null,
currency: string = 'USD',
currency: string = 'CNY',
options: CurrencyFormatOptions = {}
): string => {
if (priceInCents === undefined || priceInCents === null || isNaN(priceInCents)) {
@@ -80,9 +80,9 @@ export const formatPrice = (
* @param currency 货币代码
* @returns 货币符号
*/
export const getCurrencySymbol = (currency: string = 'USD'): string => {
export const getCurrencySymbol = (currency: string = 'CNY'): string => {
try {
const formatter = new Intl.NumberFormat('en-US', {
const formatter = new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: currency,
minimumFractionDigits: 0,
@@ -114,7 +114,7 @@ export const getCurrencySymbol = (currency: string = 'USD'): string => {
*/
export const formatBalance = (
balance: number | undefined | null,
currency: string = 'USD'
currency: string = 'CNY'
): string => {
return formatCurrency(balance, currency, {
minimumFractionDigits: 2,
+21 -2
View File
@@ -1,5 +1,5 @@
// payment channel type
export type PaymentChannelType = "stripe" | "alipay" | "wechat";
export type PaymentChannelType = "stripe" | "alipay" | "wechat" | "epay";
// stripe config - admin need to configure
export interface StripeConfig {
@@ -23,8 +23,27 @@ export interface WechatConfig {
is_enabled?: boolean;
}
// epay (易支付) config - admin need to configure
export interface EpayChannelConfig {
/** gateway base address, e.g. https://pay.example.com */
gateway: string;
/** merchant id */
pid: string;
/** merchant key used for md5 signing */
key: string;
/** "", alipay, wxpay or qqpay -- empty lets the customer choose */
pay_type?: string;
/** CNY charged per 1 balance unit (default 1 = 1:1) */
exchange_rate?: number | string;
/** async notify url, auto derived when empty */
notify_url?: string;
/** browser return url, auto derived when empty */
return_url?: string;
is_enabled?: boolean;
}
// union type for all payment configs
export type PaymentConfig = StripeConfig | AlipayConfig | WechatConfig;
export type PaymentConfig = StripeConfig | AlipayConfig | WechatConfig | EpayChannelConfig;
// API return payment channel item structure
export interface PaymentChannelApiItem {
+6
View File
@@ -3,6 +3,12 @@
# Description: Dockerfile for XPack
FROM python:3.12.11-alpine3.22
# Build-time proxy (needed for apk/pip in restricted networks)
ARG HTTP_PROXY
ARG HTTPS_PROXY
ARG NO_PROXY
ENV HTTP_PROXY=$HTTP_PROXY HTTPS_PROXY=$HTTPS_PROXY NO_PROXY=$NO_PROXY
RUN apk add nodejs=~22 npm uv nginx
# ENV TZ=Asia/Shanghai
# RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
@@ -1,6 +1,8 @@
from fastapi import APIRouter, Depends, Request
from fastapi.responses import PlainTextResponse
from sqlalchemy.orm import Session
from pydantic import BaseModel
from urllib.parse import parse_qsl
from services.common.database import get_db
from services.common.utils.response_utils import ResponseUtils
@@ -20,6 +22,15 @@ def get_user_wallet_history(db: Session = Depends(get_db)) -> UserWalletHistoryS
return UserWalletHistoryService(db)
def _request_base_url(request: Request) -> str:
"""Public base URL of this site (honours the reverse proxy headers)."""
forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip()
scheme = forwarded_proto or request.url.scheme or "http"
host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip()
host = host or request.headers.get("Host") or request.url.netloc
return f"{scheme}://{host}"
class CreatePaymentLinkRequest(BaseModel):
amount: float
currency: str = "usd"
@@ -53,6 +64,20 @@ def create_payment_link(
return ResponseUtils.error(message="Failed to create Wechat payment link", code=500)
task = OrderMonitorTask.get_instance()
task.add_order_to_monitor(payment_id=payment_info.get("payment_id"))
case "epay":
payment_info = payment.create_epay_payment_link(
user_id=user.id,
amount=body.amount,
base_url=_request_base_url(request),
success_url=body.success_url,
currency=body.currency,
)
if not payment_info:
return ResponseUtils.error(
message="Failed to create Epay payment link (check channel config)", code=500
)
# epay is settled by the async notify; the order monitor has no
# epay client, so it is intentionally not registered here.
case _:
if not body.success_url:
return ResponseUtils.error(message="Success URL is required for Stripe payments", code=400)
@@ -77,6 +102,32 @@ async def callback_stripe(
else:
return ResponseUtils.error(message="Stripe callback failed", code=500)
@router.get("/callback_epay")
@router.post("/callback_epay")
async def callback_epay(
request: Request,
payment: PaymentService = Depends(get_payment),
):
"""Handle an epay (易支付) async notify.
The gateway sends a GET query string (some forks POST form data) and
expects the literal body `success` to stop retrying.
"""
if request.method == "POST":
body = (await request.body()).decode("utf-8", "replace")
params = dict(parse_qsl(body, keep_blank_values=True))
else:
params = dict(request.query_params)
try:
ok = payment.epay_payment_callback(params)
except Exception as e: # never let an unexpected error hide the ack
from services.common.logging_config import get_logger
get_logger(__name__).error(f"Epay callback failed: {e}")
ok = False
return PlainTextResponse("success" if ok else "error", status_code=200 if ok else 500)
# @router.post("/callback_alipay", response_model=dict)
# async def callback_alipay(request: Request, payment: PaymentService = Depends(get_payment)):
# """Handle Alipay payment webhook callback."""
@@ -92,11 +143,22 @@ async def callback_stripe(
async def order_status(
request: Request,
payment_id: str,
payment: PaymentService = Depends(get_payment),
get_user_wallet_history: UserWalletHistoryService = Depends(get_user_wallet_history),
):
"""Check payment order completion status."""
if not UserUtils.is_normal_user(request):
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
if get_user_wallet_history.check_order_complete(payment_id):
return ResponseUtils.success({"status": 1})
# epay fallback: if the async notify never reached us, ask the gateway now.
try:
if payment.sync_epay_order(payment_id):
return ResponseUtils.success({"status": 1})
except Exception:
pass
if get_user_wallet_history.check_order_complete(payment_id):
return ResponseUtils.success({"status": 1})
return ResponseUtils.success({"status": 0})
@@ -1,15 +1,22 @@
"""User submission controller for MCP/Skill/Plugin marketplace."""
import json
import logging
import os
import uuid
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, Request, UploadFile, File, Form, HTTPException
from sqlalchemy.orm import Session
from services.common.database import get_db
from services.common.utils.response_utils import ResponseUtils
from services.common.utils.validation_utils import ValidationUtils
from services.admin_service.utils.user_utils import UserUtils
from services.common import error_msg
from services.common.models.submission import Submission
from services.common.models.mcp_service import McpService, ChargeType
from services.common.models.mcp_tool_api import McpToolApi, HttpMethod
from services.admin_service.services.openapi_helper import convert_openapi_for_ai
logger = logging.getLogger(__name__)
router = APIRouter()
@@ -18,6 +25,122 @@ UPLOAD_DIR = "/tmp/submission_uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
def _slugify(text: str) -> str:
"""Convert text to a slug-safe English string (letters, digits, -, _)."""
import re
s = re.sub(r"[^A-Za-z0-9]+", "-", (text or "").strip()).strip("-").lower()
return s or "service"
def _unique_slug(db: Session, text: str) -> str:
base = _slugify(text)
slug = base
counter = 1
while db.query(McpService).filter(McpService.slug_name == slug).first():
slug = f"{base}-{counter}"
counter += 1
return slug
def _publish_mcp_service(db: Session, sub: Submission) -> str:
"""
Create a market listing (mcp_service + mcp_tool_api rows) from an approved
MCP submission. Returns the new service id.
Tool definitions come from the uploaded file when it parses as an OpenAPI
spec; otherwise the service is published without tools (admin can add them
later from the service edit page).
"""
meta = sub.metadata_json or {}
base_url = (meta.get("base_url") or "").strip()
if not base_url:
raise ValueError("MCP submission is missing base_url")
charge_type_raw = (meta.get("charge_type") or "free").strip().lower()
try:
price = float(meta.get("price") or 0)
except (TypeError, ValueError):
price = 0.0
try:
free_daily_limit = int(meta.get("free_daily_limit")) if meta.get("free_daily_limit") else None
except (TypeError, ValueError):
free_daily_limit = None
if free_daily_limit is not None and free_daily_limit <= 0:
free_daily_limit = None
service_type = (meta.get("service_type") or "openapi").strip() or "openapi"
tags = meta.get("tags") or ""
if isinstance(tags, list):
tags = ",".join(str(t).strip() for t in tags if str(t).strip())
# Best-effort: parse the uploaded file as an OpenAPI spec to build tool rows.
openapi_data = None
if sub.file_path and os.path.exists(sub.file_path):
try:
with open(sub.file_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
openapi_data = convert_openapi_for_ai(content)
if not getattr(openapi_data, "apis", None):
openapi_data = None
except Exception as e: # noqa: BLE001 - file may not be an OpenAPI doc
logger.info("Submission %s file is not an OpenAPI spec: %s", sub.id, e)
openapi_data = None
service = McpService()
service.id = str(uuid.uuid4())
service.name = sub.name
service.slug_name = _unique_slug(db, sub.name)
desc = (sub.description or "").strip() or sub.name
service.short_description = desc[:255]
service.long_description = desc
service.base_url = base_url
service.headers = "[]"
service.charge_type = ChargeType.PER_CALL if (charge_type_raw in ("paid", "per_call") and price > 0) else ChargeType.FREE
service.price = price if service.charge_type == ChargeType.PER_CALL else 0.0
service.free_daily_limit = free_daily_limit if service.charge_type == ChargeType.FREE else None
service.tags = tags
service.service_type = service_type
service.enabled = 1 # auto-publish: immediately visible in the market
db.add(service)
db.flush()
tool_count = 0
if openapi_data is not None:
for api in openapi_data.apis:
try:
http_method = HttpMethod(api.method)
except ValueError:
# HEAD/OPTIONS/TRACE are not part of the supported tool enum
continue
tool = McpToolApi()
tool.id = str(uuid.uuid4())
tool.service_id = service.id
tool.name = api.summary or f"{api.method} {api.path}"
tool.description = api.description or api.summary or tool.name
tool.path = api.path
tool.method = http_method
tool.header_parameters = json.dumps(api.header_parameters) if api.header_parameters else ""
tool.query_parameters = json.dumps(api.query_parameters) if api.query_parameters else ""
tool.path_parameters = json.dumps(api.path_parameters) if api.path_parameters else ""
tool.request_body_schema = json.dumps(api.request_body_schema) if api.request_body_schema else ""
tool.response_schema = json.dumps(api.response_schema) if api.response_schema else ""
tool.response_examples = json.dumps(api.response_examples) if api.response_examples else ""
tool.response_headers = json.dumps(api.response_headers) if api.response_headers else ""
tool.operation_examples = json.dumps(api.operation_examples) if api.operation_examples else ""
tool.enabled = 1
tool.is_deleted = 0
db.add(tool)
tool_count += 1
db.flush()
logger.info(
"Auto-published submission %s -> service %s (%d tools, base_url=%s)",
sub.id, service.id, tool_count, base_url,
)
return service.id
@router.post("/submission", summary="User submit MCP/Skill/Plugin")
async def create_submission(
request: Request,
@@ -25,6 +148,12 @@ async def create_submission(
name: str = Form(...),
description: str = Form(None),
file: UploadFile = File(None),
base_url: str = Form(None),
service_type: str = Form(None),
tags: str = Form(None),
charge_type: str = Form(None),
price: float = Form(None),
free_daily_limit: int = Form(None),
db: Session = Depends(get_db),
):
try:
@@ -37,6 +166,12 @@ async def create_submission(
if type not in ("mcp", "skill", "plugin"):
return ResponseUtils.error(error_msg=error_msg.INVALID_PARAMETER)
# MCP submissions must declare where the service lives so that approving
# the submission can auto-publish a working market listing.
base_url = (base_url or "").strip()
if type == "mcp" and not base_url:
return ResponseUtils.error(message="base_url is required for MCP submissions")
file_path = None
if file:
safe_name = f"{uuid.uuid4()}_{file.filename}"
@@ -44,12 +179,24 @@ async def create_submission(
with open(file_path, "wb") as f:
f.write(await file.read())
metadata = {}
if type == "mcp":
metadata = {
"base_url": base_url,
"service_type": (service_type or "openapi").strip() or "openapi",
"tags": (tags or "").strip(),
"charge_type": (charge_type or "free").strip() or "free",
"price": price,
"free_daily_limit": free_daily_limit,
}
sub = Submission(
user_id=user_id,
type=type,
name=name,
description=description,
file_path=file_path,
metadata_json=metadata or None,
status="pending",
)
db.add(sub)
@@ -75,6 +222,7 @@ def list_submissions(request: Request, db: Session = Depends(get_db)):
"name": s.name,
"description": s.description,
"status": s.status,
"metadata_json": s.metadata_json,
"created_at": s.created_at.isoformat() if s.created_at else None,
"review_note": s.review_note,
}
@@ -101,16 +249,18 @@ def admin_list_submissions(request: Request, status: str = None, db: Session = D
"name": s.name,
"description": s.description,
"file_path": s.file_path,
"metadata_json": s.metadata_json,
"status": s.status,
"created_at": s.created_at.isoformat() if s.created_at else None,
"review_note": s.review_note,
"reviewed_at": s.reviewed_at.isoformat() if s.reviewed_at else None,
}
for s in subs
]
return ResponseUtils.success(data=data)
@router.put("/admin/submission/{sub_id}/approve", summary="Approve submission")
@router.put("/admin/submission/{sub_id}/approve", summary="Approve submission (auto-publish to market)")
def approve_submission(sub_id: str, request: Request, db: Session = Depends(get_db)):
if not UserUtils.is_admin(request):
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
@@ -118,12 +268,27 @@ def approve_submission(sub_id: str, request: Request, db: Session = Depends(get_
sub = db.query(Submission).filter(Submission.id == sub_id).first()
if not sub:
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
if sub.status != "pending":
return ResponseUtils.error(message="Submission has already been processed")
service_id = None
if sub.type == "mcp":
try:
service_id = _publish_mcp_service(db, sub)
except Exception as e: # noqa: BLE001 - report the exact reason to the admin
db.rollback()
logger.error("Auto-publish failed for submission %s: %s", sub_id, e)
return ResponseUtils.error(error_msg=f"Auto-publish failed: {e}")
sub.status = "approved"
sub.reviewer_id = UserUtils.get_request_user_id(request)
from datetime import datetime
sub.reviewed_at = datetime.utcnow()
if service_id:
meta = sub.metadata_json or {}
meta["published_service_id"] = service_id
sub.metadata_json = meta
db.commit()
return ResponseUtils.success()
return ResponseUtils.success(data={"service_id": service_id})
@router.put("/admin/submission/{sub_id}/reject", summary="Reject submission")
@@ -136,7 +301,6 @@ def reject_submission(sub_id: str, request: Request, body: dict = None, db: Sess
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
sub.status = "rejected"
sub.reviewer_id = UserUtils.get_request_user_id(request)
from datetime import datetime
sub.reviewed_at = datetime.utcnow()
if body:
sub.review_note = body.get("note")
@@ -181,6 +181,23 @@ class UserWalletHistoryRepository:
self.db.refresh(history)
return history
def set_callback_data(self, record_id: str, data: str) -> bool:
"""Persist raw gateway metadata (e.g. charged CNY amount) on a record."""
try:
obj = self.db.query(UserWalletHistory).filter(
UserWalletHistory.id == record_id
).first()
if not obj:
self.logging.error(f"UserWalletHistory not found: id={record_id}")
return False
obj.callback_data = data
self.db.commit()
return True
except Exception as e:
self.logging.error(f"Error setting callback_data: id={record_id}, error={str(e)}")
self.db.rollback()
return False
def deposit_complete(self, id: str, transaction_id: str) -> bool:
"""
Mark deposit order as completed and safely update balance_after.
@@ -1,3 +1,4 @@
import json
import stripe
import logging
import asyncio
@@ -11,10 +12,12 @@ from services.admin_service.repositories.user_wallet_history_repository import U
from services.admin_service.repositories.sys_config_repository import SysConfigRepository
from services.admin_service.services.payment_channel_service import PaymentChannelService
from services.admin_service.utils.alipay_client import AlipayClient
from services.admin_service.utils.epay_client import EpayClient, verify_sign
from services.admin_service.utils.wxpay_client import WxPayClient,WxPayConfig
from services.admin_service.constants.sys_config_key import (
KEY_PLATFORM_NAME
)
from services.common.models.user_wallet_history import PaymentMethod
from services.common.redis import redis_client
logger = logging.getLogger(__name__)
@@ -242,6 +245,202 @@ class PaymentService:
logger.error(f"Failed to create WeChat payment link: {str(e)}")
return None
def create_epay_payment_link(
self,
user_id: str,
amount: float,
base_url: str,
success_url: str = "",
currency: str = "cny",
) -> Optional[dict]:
"""Create an epay (易支付) page-pay link for the user.
The gateway settles in CNY while wallet balances use the platform unit,
so `exchange_rate` (CNY per 1 balance unit, default 1) converts the amount.
"""
config = self.payment_channel_service.get_config("epay")
if config is None or not config.get("enable"):
logger.error("Epay payment channel is not enabled or configured")
return None
gateway = str(config.get("gateway") or "").strip()
pid = str(config.get("pid") or "").strip()
key = str(config.get("key") or "").strip()
missing = [n for n, v in (("gateway", gateway), ("pid", pid), ("key", key)) if not v]
if missing:
logger.error(f"Epay payment configuration incomplete. Missing: {', '.join(missing)}")
return None
if amount is None or float(amount) <= 0:
raise ValueError("Invalid amount.")
user = self.user_repository.get_by_id(user_id)
if not user:
logger.error(f"User with ID {user_id} not found.")
raise ValueError("User not found.")
# Pending deposit record; its id is used as epay's out_trade_no.
history = self.user_wallet_history_repository.add_deposit(
user_id=user_id, amount=float(amount), payment_method="epay"
)
if history is None:
logger.error("Failed to create user wallet history for deposit.")
raise RuntimeError("Failed to create payment.")
try:
rate = float(config.get("exchange_rate") or 1)
except (TypeError, ValueError):
rate = 1.0
if rate <= 0:
rate = 1.0
money_cny = round(float(amount) * rate, 2)
if money_cny < 0.01:
money_cny = 0.01
base = (base_url or "").rstrip("/")
notify_url = str(config.get("notify_url") or "").strip() or f"{base}/api/payment/callback_epay"
return_url = str(config.get("return_url") or "").strip() or success_url or (base + "/")
platform_name = self.sys_config_repository.get_by_key(KEY_PLATFORM_NAME)
if platform_name is None:
platform_name = "XPack"
client = EpayClient(gateway=gateway, pid=pid, key=key)
pay_url = client.build_submit_url(
out_trade_no=history.id,
name=f"[Deposit] {platform_name}",
money=money_cny,
notify_url=notify_url,
return_url=return_url,
pay_type=str(config.get("pay_type") or "").strip(),
)
if not pay_url:
logger.error(f"Failed to build epay payment URL for order {history.id}")
return None
self.user_wallet_history_repository.set_callback_data(
history.id,
json.dumps({"money_cny": money_cny, "exchange_rate": rate}, ensure_ascii=False),
)
logger.info(
f"Created epay payment link for order {history.id}: {money_cny} CNY "
f"({amount} x {rate})"
)
return {"payment_link": pay_url, "payment_id": history.id}
def epay_payment_callback(self, params: dict) -> bool:
"""Handle an epay (易支付) async notify.
Verifies the MD5 signature, the trade status and the notified amount,
then credits the wallet exactly once (idempotent).
"""
config = self.payment_channel_service.get_config("epay")
if config is None or not config.get("enable"):
logger.error("Epay payment channel is disabled, dropping notify")
return False
key = str(config.get("key") or "")
out_trade_no = str(params.get("out_trade_no") or "")
if not verify_sign(params, key):
logger.error(f"Epay notify signature verification failed for order {out_trade_no}")
return False
trade_status = str(params.get("trade_status") or "")
if trade_status != "TRADE_SUCCESS":
logger.info(f"Epay notify order {out_trade_no} status '{trade_status}' ignored")
return True # acknowledged: nothing to credit, gateway should stop retrying
if not out_trade_no:
logger.error("Epay notify without out_trade_no")
return False
history = self.user_wallet_history_repository.get_by_id(out_trade_no)
if history is None:
logger.error(f"Epay notify for unknown order {out_trade_no}")
return False
method = getattr(history.payment_method, "value", history.payment_method)
if method != PaymentMethod.EPAY.value:
logger.error(f"Epay notify for order {out_trade_no} paid via '{method}'")
return False
try:
notified_money = round(float(params.get("money")), 2)
except (TypeError, ValueError):
logger.error(f"Epay notify for order {out_trade_no} has invalid money")
return False
charged_money = None
try:
meta = json.loads(history.callback_data) if history.callback_data else {}
charged_money = round(float(meta.get("money_cny")), 2)
except (TypeError, ValueError, json.JSONDecodeError):
charged_money = None
if charged_money is not None and abs(charged_money - notified_money) > 0.01:
logger.error(
f"Epay notify amount mismatch for order {out_trade_no}: "
f"notified={notified_money} charged={charged_money}"
)
return False
if history.status == 1:
logger.info(f"Epay notify order {out_trade_no} already completed")
return True
# `transaction_id` is unique: use the gateway trade_no as the channel id.
channel_tx = str(params.get("trade_no") or "") or f"epay-{out_trade_no}"
return self._add_wallet_balance(payment_id=out_trade_no, payment_channel_id=channel_tx)
def sync_epay_order(self, payment_id: str) -> bool:
"""Fallback settlement: query the gateway for a pending epay order.
Used when the async notify could not reach us (e.g. the site has no
public URL). Credits the wallet when the gateway reports payment.
Safe to call repeatedly -- already settled orders are a no-op.
"""
if not payment_id:
return False
history = self.user_wallet_history_repository.get_by_id(payment_id)
if history is None:
return False
method = getattr(history.payment_method, "value", history.payment_method)
if method != PaymentMethod.EPAY.value or history.status == 1:
return False
config = self.payment_channel_service.get_config("epay")
if config is None or not config.get("enable"):
return False
client = EpayClient(
gateway=str(config.get("gateway") or "").strip(),
pid=str(config.get("pid") or "").strip(),
key=str(config.get("key") or "").strip(),
)
data = client.query_order(payment_id)
if not data:
return False
if int(data.get("status", 0) or 0) != 1:
return False
try:
notified_money = round(float(data.get("money")), 2)
except (TypeError, ValueError):
notified_money = None
if notified_money is not None:
try:
meta = json.loads(history.callback_data) if history.callback_data else {}
charged_money = round(float(meta.get("money_cny")), 2)
except (TypeError, ValueError, json.JSONDecodeError):
charged_money = None
if charged_money is not None and abs(charged_money - notified_money) > 0.01:
logger.error(
f"Epay query amount mismatch for order {payment_id}: "
f"queried={notified_money} charged={charged_money}"
)
return False
channel_tx = str(data.get("trade_no") or "") or f"epay-{payment_id}"
logger.info(f"Settling epay order {payment_id} via gateway query (trade_no={channel_tx})")
return self._add_wallet_balance(payment_id=payment_id, payment_channel_id=channel_tx)
def payment_callback(self, payment_id: str, payment_channel_id: str, status: int = 1) -> bool:
"""
Handle Alipay payment webhook callback.
+135
View File
@@ -0,0 +1,135 @@
"""
Epay (易支付) V1 protocol client.
Protocol reference: https://pay.88531.cn gateway (classic epay / V1):
* Submit page : GET {gateway}/submit.php (browser side, no IP whitelist)
* API order : POST {gateway}/mapi.php (server side, IP whitelist)
* Query order : GET {gateway}/api.php?act=order (uses plaintext `key`, no sign)
* Async notify: GET {notify_url} -> reply exactly `success`
Signature (MD5):
1. drop `sign`, `sign_type` and params whose value is empty
2. sort params by ASCII ascending
3. join as `k1=v1&k2=v2` -- values are NOT url-encoded
4. append the merchant key directly (no separator), md5 -> 32 char LOWERCASE hex
"""
import hashlib
import json
import logging
import urllib.error
import urllib.request
from typing import Optional
from urllib.parse import quote, urlencode
logger = logging.getLogger(__name__)
SIGN_TYPE = "MD5"
def build_sign(params: dict, key: str) -> str:
"""Build the epay V1 MD5 signature for `params`."""
parts = []
for field in sorted(params.keys()):
if field in ("sign", "sign_type"):
continue
value = params[field]
if value is None or value == "":
continue
if isinstance(value, (list, dict, tuple, set)):
continue
parts.append(f"{field}={value}")
raw = "&".join(parts) + str(key)
return hashlib.md5(raw.encode("utf-8")).hexdigest().lower()
def verify_sign(params: dict, key: str) -> bool:
"""Verify an inbound epay notify. Comparison is case insensitive."""
given = str(params.get("sign", "") or "").strip()
if not given:
return False
return build_sign(params, key).lower() == given.lower()
class EpayClient:
"""Builds epay payment requests."""
def __init__(self, gateway: str, pid: str, key: str):
self.gateway = (gateway or "").rstrip("/")
self.pid = str(pid or "")
self.key = str(key or "")
@property
def configured(self) -> bool:
return bool(self.gateway and self.pid and self.key)
def build_submit_url(
self,
out_trade_no: str,
name: str,
money: float,
notify_url: str,
return_url: str = "",
pay_type: str = "",
param: str = "",
) -> Optional[str]:
"""Build the browser payment URL ({gateway}/submit.php).
Returns None when the client is not configured or the URL cannot be built.
"""
if not self.configured:
logger.error("Epay client is not configured (gateway/pid/key missing)")
return None
if not out_trade_no or not notify_url:
logger.error("Epay payment requires out_trade_no and notify_url")
return None
params = {
"pid": self.pid,
"out_trade_no": out_trade_no,
"notify_url": notify_url,
"name": str(name or "Deposit")[:64],
"money": f"{float(money):.2f}",
"sign_type": SIGN_TYPE,
}
if return_url:
params["return_url"] = return_url
if pay_type:
params["type"] = str(pay_type)
if param:
params["param"] = str(param)
params["sign"] = build_sign(params, self.key)
# urlencode for the actual HTTP request only -- the signature above was
# computed on the raw (decoded) values, exactly as the gateway expects.
query = urlencode(list(params.items()), quote_via=quote, safe="")
return f"{self.gateway}/submit.php?{query}"
def query_order(self, out_trade_no: str, timeout: float = 8.0) -> Optional[dict]:
"""Query one order through {gateway}/api.php?act=order.
Returns the parsed JSON body, or None when the gateway is unreachable
or rejects the call (e.g. our IP is not whitelisted).
"""
if not self.configured or not out_trade_no:
return None
params = {
"act": "order",
"pid": self.pid,
"key": self.key,
"out_trade_no": out_trade_no,
}
url = f"{self.gateway}/api.php?{urlencode(list(params.items()), quote_via=quote, safe='')}"
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
payload = resp.read().decode("utf-8", "replace")
except (urllib.error.URLError, OSError, ValueError) as exc:
logger.error(f"Epay order query failed for {out_trade_no}: {exc}")
return None
try:
data = json.loads(payload)
except json.JSONDecodeError:
logger.error(f"Epay order query returned non-JSON for {out_trade_no}: {payload[:200]}")
return None
if not isinstance(data, dict):
return None
return data
+3
View File
@@ -63,6 +63,9 @@ class Config:
"/api/web/mcp_services",
"/api/web/mcp_service_info",
"/api/payment/callback_stripe",
# epay (易支付) async notify — called by the gateway, no user token.
"/api/payment/callback_epay",
"/api/payment/refund_callback_epay",
# "/api/payment/callback_alipay",
]
@@ -10,6 +10,7 @@ class PaymentMethod(PyEnum):
STRIPE = "stripe"
ALIPAY = "alipay"
WECHAT = "wechat"
EPAY = "epay"
class TransactionType(PyEnum):