Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8529ac2e60 | ||
|
|
7f47841fdc | ||
|
|
f5b45af30a | ||
|
|
851d45a573 | ||
|
|
b7a10ca678 | ||
|
|
8f0796c031 | ||
|
|
721a2be32b | ||
|
|
1fbb6711f2 |
No files matched your search
@@ -343,3 +343,46 @@ For details, please see the [LICENSE](./LICENSE) file.
|
||||
- [XRoute](https://xroute.ai): The Unified Interface For LLMs, provides better prices, better throughput, and no subscription.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): MemU is an open-source memory framework for AI companions
|
||||
|
||||
---
|
||||
|
||||
## 国内镜像部署(本项目维护,随 Release 更新)
|
||||
|
||||
镜像已双渠道发布,任选其一拉取:
|
||||
|
||||
- 公网:`gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1`、`jpccr.ccs.tencentyun.com/jinghui/xpack-mcp-market:v1.5.1`
|
||||
- 内网:`192.168.68.19:3200/jinghui/xpack-mcp-market:v1.5.1`
|
||||
|
||||
### 方式一:docker-compose(推荐,带齐全部服务参数)
|
||||
|
||||
```bash
|
||||
git clone http://192.168.68.19:3200/jinghui/xpack-mcp.git && cd xpack-mcp
|
||||
|
||||
# 1) 把 docker-compose.yml 中 xpack-mcp-market 服务的 image 改为公网镜像:
|
||||
# image: xpackai/xpack-mcp-market:zhcn
|
||||
# → image: gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1
|
||||
|
||||
# 2) 准备环境变量(支付渠道加密密钥,必须改掉示例值)
|
||||
cp .env.example .env && vim .env # 修改 PAYMENT_CONFIG_SECRET_KEY 为自己的 32 字节随机串
|
||||
|
||||
docker compose up -d # 启动 mysql/redis/rabbitmq/market 四个容器
|
||||
```
|
||||
|
||||
注意事项:
|
||||
- `PAYMENT_CONFIG_SECRET_KEY` 缺失时 compose 会直接报错拒绝启动(`.env` 不可删);
|
||||
- 数据库账号、Redis 密码、RabbitMQ 密码在 compose 里已固定,改任何一项都要同步改应用配置;
|
||||
- 数据目录 `./mysql-data` 与容器网络 `172.101.0.0/24` 不要与已有环境冲突。
|
||||
|
||||
### 方式二:docker run(主站单容器)
|
||||
|
||||
前置:MySQL 8.0.37 / Redis 7.2.4 / RabbitMQ 4.1.2 已就绪,且容器与依赖服务同一网络(应用默认按主机名 `xpack-mysql`、`xpack-redis`、`xpack-rabbitmq` 连接)。
|
||||
|
||||
```bash
|
||||
docker run -d --name xpack-mcp-market \
|
||||
--restart always --privileged \
|
||||
-p 8010:80 \
|
||||
-e PAYMENT_CONFIG_SECRET_KEY='<32字节随机串>' \
|
||||
-e PAYMENT_CONFIG_KEY_ID=default \
|
||||
--network <依赖服务所在网络> \
|
||||
gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1
|
||||
```
|
||||
@@ -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:
|
||||
|
||||
@@ -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": "网络错误,请重试",
|
||||
@@ -968,5 +968,12 @@
|
||||
"Example 100": "如 100",
|
||||
"Enter a non-negative integer": "请输入非负整数",
|
||||
"Free call limit saved": "免费调用上限已保存",
|
||||
"Failed to save free call limit": "保存免费调用上限失败"
|
||||
"Failed to save free call limit": "保存免费调用上限失败",
|
||||
"Publish MCP Service": "发布 MCP 服务",
|
||||
"Submit your own MCP service": "提交你的 MCP 服务并上架市场",
|
||||
"My Submissions": "我的提交记录",
|
||||
"No submissions yet": "还没有提交记录",
|
||||
"Pending Review": "待审核",
|
||||
"Approved": "已通过",
|
||||
"Rejected": "已拒绝"
|
||||
}
|
||||
@@ -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 />;
|
||||
}
|
||||
@@ -1,40 +1,260 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
|
||||
type SubType = "mcp";
|
||||
|
||||
type SubRecord = {
|
||||
id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
status: string;
|
||||
created_at?: string | null;
|
||||
review_note?: string | null;
|
||||
};
|
||||
|
||||
const TYPE_LABEL: Record<string, string> = {
|
||||
mcp: "MCP 服务",
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<string, { text: string; cls: string }> = {
|
||||
pending: { text: "待审核", cls: "bg-yellow-100 text-yellow-800" },
|
||||
approved: { text: "已通过", cls: "bg-green-100 text-green-800" },
|
||||
rejected: { text: "已拒绝", cls: "bg-red-100 text-red-700" },
|
||||
};
|
||||
|
||||
export default function SubmitPage() {
|
||||
const [type, setType] = useState("mcp");
|
||||
// 网页登录态存在 zustand store(XPack_Shared),localStorage["user_token"] 只有扩展侧栏才会写,
|
||||
// 用 store 判断才不会把已登录用户误判为未登录
|
||||
const user_token = useSharedStore((s: any) => s.user_token);
|
||||
const type: 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 [subs, setSubs] = useState<SubRecord[]>([]);
|
||||
const [loggedIn, setLoggedIn] = useState<boolean | null>(null);
|
||||
|
||||
const loadSubs = async () => {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
const d = await fetchAPI<{ success: boolean; data?: SubRecord[] }>(
|
||||
"/api/submission/submissions",
|
||||
{ method: "GET" }
|
||||
);
|
||||
if (d?.success && Array.isArray(d.data)) {
|
||||
setLoggedIn(true);
|
||||
setSubs(d.data);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* 网络异常按未登录处理,不影响提交表单 */
|
||||
}
|
||||
setLoggedIn(false);
|
||||
setSubs([]);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadSubs();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
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" && !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("");
|
||||
loadSubs();
|
||||
} 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 服务</h1>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<select value={type} onChange={e => setType(e.target.value)} className="border p-2 w-full">
|
||||
<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>
|
||||
)}
|
||||
|
||||
<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>
|
||||
)}
|
||||
|
||||
{loggedIn === false && (
|
||||
<p className="mt-6 text-sm text-gray-500">
|
||||
登录后可提交服务并查看审核状态。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loggedIn && (
|
||||
<div className="mt-8 border rounded p-4 bg-white">
|
||||
<h2 className="text-lg font-semibold mb-3">我的提交记录</h2>
|
||||
{subs.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">还没有提交记录</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{subs.map((s) => {
|
||||
const st = STATUS_LABEL[s.status] || {
|
||||
text: s.status,
|
||||
cls: "bg-gray-100 text-gray-600",
|
||||
};
|
||||
return (
|
||||
<li key={s.id} className="border rounded p-3 text-sm">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium truncate">{s.name}</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded text-xs whitespace-nowrap ${st.cls}`}
|
||||
>
|
||||
{st.text}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 mt-1 flex flex-wrap gap-x-4">
|
||||
<span>{TYPE_LABEL[s.type] || s.type}</span>
|
||||
{s.created_at && (
|
||||
<span>{new Date(s.created_at).toLocaleString("zh-CN")}</span>
|
||||
)}
|
||||
</div>
|
||||
{s.review_note && (
|
||||
<div className="text-xs text-orange-600 mt-1">
|
||||
审核备注:{s.review_note}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</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) {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { formatCurrency } from "@/shared/utils/currency";
|
||||
import DashboardOverview from "@/components/dashboard/DashboardOverview";
|
||||
import WalletManagement from "@/components/wallet/WalletManagement";
|
||||
import UserAccountBalance from "@/components/dashboard/UserAccountBalance";
|
||||
import { Home, Key, Wallet } from "lucide-react";
|
||||
import { Home, Key, Wallet, Rocket } from "lucide-react";
|
||||
import { Avatar, Card, CardBody, Button, Divider, Link } from "@nextui-org/react";
|
||||
import { RechargeModal } from "@/shared/components/modal/RechargeModal";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
@@ -92,9 +92,20 @@ const DashboardContent: React.FC = () => {
|
||||
label: "Dashboard",
|
||||
description: "Manage your integration and auth key",
|
||||
},
|
||||
{
|
||||
key: "publish-service",
|
||||
icon: <Rocket className="w-5 h-5" />,
|
||||
label: "Publish MCP Service",
|
||||
description: "Submit your own MCP service",
|
||||
},
|
||||
];
|
||||
|
||||
const handleTabNavigate = (tab: TabKey | string) => {
|
||||
// 发布 MCP 服务:跳转到独立提交页
|
||||
if (tab === "publish-service") {
|
||||
router.push("/submit");
|
||||
return;
|
||||
}
|
||||
setActiveTab(tab as TabKey);
|
||||
// update url params
|
||||
if (tab === TabKey.OVERVIEW) {
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 \
|
||||
@@ -16,6 +22,8 @@ RUN mkdir -p /$APP
|
||||
WORKDIR /$APP
|
||||
COPY requirements.txt /$APP/requirements.txt
|
||||
|
||||
# 国内 PyPI 镜像源(避免走代理直连 PyPI 过慢)
|
||||
ENV UV_DEFAULT_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
RUN uv venv && source .venv/bin/activate && uv pip install -r requirements.txt
|
||||
RUN echo $VERSION > .version
|
||||
|
||||
|
||||
@@ -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."""
|
||||
"""User submission controller for MCP 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,13 +25,135 @@ UPLOAD_DIR = "/tmp/submission_uploads"
|
||||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||
|
||||
|
||||
@router.post("/submission", summary="User submit MCP/Skill/Plugin")
|
||||
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")
|
||||
async def create_submission(
|
||||
request: Request,
|
||||
type: str = Form(...),
|
||||
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:
|
||||
@@ -34,9 +163,15 @@ async def create_submission(
|
||||
if not user_id:
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
if type not in ("mcp", "skill", "plugin"):
|
||||
if type != "mcp":
|
||||
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.
|
||||
|
||||
@@ -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
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""User submission model for MCP/Skill/Plugin marketplace."""
|
||||
"""User submission model for MCP marketplace."""
|
||||
from sqlalchemy import Column, String, Text, DateTime, JSON, Enum
|
||||
from sqlalchemy.sql import func
|
||||
from services.common.models.base import Base
|
||||
|
||||
@@ -10,6 +10,7 @@ class PaymentMethod(PyEnum):
|
||||
STRIPE = "stripe"
|
||||
ALIPAY = "alipay"
|
||||
WECHAT = "wechat"
|
||||
EPAY = "epay"
|
||||
|
||||
|
||||
class TransactionType(PyEnum):
|
||||
|
||||
Reference in new issue
Block a user