feat(admin): 短信配置独立页+短信宝支持;后台顶部面包屑导航优化

This commit is contained in:
QihuAI Design committed 2026-07-13 19:24:13 +08:00
1 parent c275cc3b5e
commit e38e18fbe7
8 files changed
+1528 -89

No files matched your search

+116
View File
@@ -45,6 +45,10 @@ class SmsConfigUpdate(BaseModel):
api_secret: Optional[str] = None api_secret: Optional[str] = None
sign_name: Optional[str] = None sign_name: Optional[str] = None
template_code: Optional[str] = None template_code: Optional[str] = None
# 短信宝 (SMSBao)
username: Optional[str] = None
password: Optional[str] = None
goods_id: Optional[str] = None
# ============================================================ # ============================================================
@@ -211,6 +215,9 @@ async def get_sms_config(
"api_secret": "", "api_secret": "",
"sign_name": "", "sign_name": "",
"template_code": "", "template_code": "",
"username": "",
"password": "",
"goods_id": "",
}, "message": "ok"} }, "message": "ok"}
return {"code": 0, "data": { return {"code": 0, "data": {
@@ -220,6 +227,9 @@ async def get_sms_config(
"api_secret": config.api_secret, "api_secret": config.api_secret,
"sign_name": config.sign_name, "sign_name": config.sign_name,
"template_code": config.template_code, "template_code": config.template_code,
"username": config.username,
"password": config.password,
"goods_id": config.goods_id,
}, "message": "ok"} }, "message": "ok"}
@@ -239,6 +249,9 @@ async def update_sms_config(
api_secret=req.api_secret or "", api_secret=req.api_secret or "",
sign_name=req.sign_name, sign_name=req.sign_name,
template_code=req.template_code, template_code=req.template_code,
username=req.username,
password=req.password,
goods_id=req.goods_id,
) )
db.add(config) db.add(config)
else: else:
@@ -252,6 +265,12 @@ async def update_sms_config(
config.sign_name = req.sign_name config.sign_name = req.sign_name
if req.template_code is not None: if req.template_code is not None:
config.template_code = req.template_code config.template_code = req.template_code
if req.username is not None:
config.username = req.username
if req.password is not None:
config.password = req.password
if req.goods_id is not None:
config.goods_id = req.goods_id
config.updated_at = datetime.now() config.updated_at = datetime.now()
db.commit() db.commit()
@@ -424,6 +443,22 @@ def _aliyun_sign(secret: str, params: dict, method: str = "GET") -> str:
return base64.b64encode(h.digest()).decode('utf-8') return base64.b64encode(h.digest()).decode('utf-8')
# 短信宝 (SMSBao) 辅助
def _smsbao_md5(password: str) -> str:
"""短信宝密码:登录密码的 MD5(32位,不区分大小写)"""
return hashlib.md5(password.encode("utf-8")).hexdigest()
SMSBAO_ERRORS = {
"0": "发送成功",
"30": "密码错误",
"40": "账号不存在",
"41": "余额不足",
"43": "IP地址限制",
"50": "内容含有敏感词",
"51": "手机号码不正确",
}
@router.post("/sms/test") @router.post("/sms/test")
async def test_sms_config( async def test_sms_config(
admin_user=Depends(get_current_admin), admin_user=Depends(get_current_admin),
@@ -451,6 +486,38 @@ async def test_sms_config(
logger.info(f"测试短信: provider={config.provider}, sign={config.sign_name}, phone={phone}") logger.info(f"测试短信: provider={config.provider}, sign={config.sign_name}, phone={phone}")
# 短信宝 (SMSBao)
if config.provider == "短信宝":
if not config.username or not config.password:
raise HTTPException(status_code=400, detail="未配置短信宝用户名或密码,请先在配置中填写")
sign = config.sign_name or ""
if "【" not in sign:
sign = f"【{sign}】" if sign else "【七虎AI】"
content = f"{sign}测试短信:您的验证码是123456,若非本人操作请忽略。"
pwd_md5 = _smsbao_md5(config.password)
params = {"u": config.username, "p": pwd_md5, "m": phone, "c": content}
if config.goods_id:
params["g"] = config.goods_id
import requests as http_requests
try:
resp = http_requests.get(
"https://api.smsbao.com/sms", params=params, timeout=10,
proxies={"http": None, "https": None},
)
code = resp.text.strip().split("\n")[0]
except Exception as e:
logger.error(f"短信宝请求失败: {e}")
raise HTTPException(status_code=500, detail=f"短信宝请求失败: {str(e)}")
if code == "0":
LogService.log_audit(
admin_id=admin_user.id, admin_name=admin_user.username,
action="test_sms_config", target_type="sms_config",
detail=f"短信宝测试短信发送成功 -> {phone}",
)
return {"message": f"测试短信已发送到 {phone}", "phone": phone}
msg = SMSBAO_ERRORS.get(code, f"未知错误码 {code}")
raise HTTPException(status_code=400, detail=f"短信宝发送失败: {msg} (code={code})")
# 只有阿里云短信支持测试 # 只有阿里云短信支持测试
if "阿里云" not in (config.provider or ""): if "阿里云" not in (config.provider or ""):
raise HTTPException( raise HTTPException(
@@ -506,3 +573,52 @@ async def test_sms_config(
except Exception as e: except Exception as e:
logger.error(f"测试短信发送失败: {e}") logger.error(f"测试短信发送失败: {e}")
raise HTTPException(status_code=500, detail=f"短信发送失败: {str(e)}") raise HTTPException(status_code=500, detail=f"短信发送失败: {str(e)}")
# ============================================================
# 短信宝余额查询
# ============================================================
@router.post("/sms/balance")
async def query_sms_balance(
admin_user=Depends(get_current_admin),
db: Session = Depends(get_db),
):
"""查询短信宝账户余额(发送条数, 剩余条数)"""
config = db.query(SmsConfig).first()
if not config or config.provider != "短信宝":
raise HTTPException(status_code=400, detail="仅短信宝支持余额查询,请先选择短信宝并保存账号")
if not config.username or not config.password:
raise HTTPException(status_code=400, detail="未配置短信宝用户名或密码")
import requests as http_requests
pwd_md5 = _smsbao_md5(config.password)
try:
resp = http_requests.get(
"https://www.smsbao.com/query",
params={"u": config.username, "p": pwd_md5},
timeout=10,
proxies={"http": None, "https": None},
)
lines = resp.text.strip().split("\n")
except Exception as e:
logger.error(f"短信宝余额查询请求失败: {e}")
raise HTTPException(status_code=500, detail=f"短信宝余额查询失败: {str(e)}")
code = lines[0].strip() if lines else ""
if code != "0":
msg = SMSBAO_ERRORS.get(code, f"未知错误码 {code}")
raise HTTPException(status_code=400, detail=f"查询失败: {msg}")
sent = remain = 0
if len(lines) >= 2:
parts = lines[1].split(",")
try:
sent = int(parts[0])
except (ValueError, IndexError):
sent = 0
try:
remain = int(parts[1])
except (ValueError, IndexError):
remain = 0
return {"code": 0, "data": {"sent": sent, "remain": remain}, "message": "ok"}
+4
View File
@@ -642,6 +642,10 @@ class SmsConfig(Base):
api_secret = Column(String(200), nullable=False) api_secret = Column(String(200), nullable=False)
sign_name = Column(String(100), default=None) sign_name = Column(String(100), default=None)
template_code = Column(String(100), default=None) template_code = Column(String(100), default=None)
# 短信宝 (SMSBao) 字段
username = Column(String(100), default=None) # 短信宝用户名 u
password = Column(String(200), default=None) # 短信宝密码(明文存储,发送时 MD5 32位)
goods_id = Column(String(100), default=None) # 短信宝专属通道产品 ID g
created_at = Column(DateTime, default=datetime.now) created_at = Column(DateTime, default=datetime.now)
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now) updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
+2
View File
@@ -28,6 +28,7 @@ const AdminDashboard = React.lazy(() => import('@/pages/admin/Dashboard'));
const AdminUsers = React.lazy(() => import('@/pages/admin/Users')); const AdminUsers = React.lazy(() => import('@/pages/admin/Users'));
const AdminModels = React.lazy(() => import('@/pages/admin/Models')); const AdminModels = React.lazy(() => import('@/pages/admin/Models'));
const AdminSiteSettings = React.lazy(() => import('@/pages/admin/SiteSettings')); const AdminSiteSettings = React.lazy(() => import('@/pages/admin/SiteSettings'));
const AdminSmsConfig = React.lazy(() => import('@/pages/admin/SmsConfig'));
const AdminPayment = React.lazy(() => import('@/pages/admin/Payment')); const AdminPayment = React.lazy(() => import('@/pages/admin/Payment'));
const AdminServices = React.lazy(() => import('@/pages/admin/Services')); const AdminServices = React.lazy(() => import('@/pages/admin/Services'));
const AdminMembership = React.lazy(() => import('@/pages/admin/Membership')); const AdminMembership = React.lazy(() => import('@/pages/admin/Membership'));
@@ -130,6 +131,7 @@ const App: React.FC = () => {
<Route path="users" element={<AdminUsers />} /> <Route path="users" element={<AdminUsers />} />
<Route path="models" element={<AdminModels />} /> <Route path="models" element={<AdminModels />} />
<Route path="settings" element={<AdminSiteSettings />} /> <Route path="settings" element={<AdminSiteSettings />} />
<Route path="sms" element={<AdminSmsConfig />} />
<Route path="payment" element={<AdminPayment />} /> <Route path="payment" element={<AdminPayment />} />
<Route path="services" element={<AdminServices />} /> <Route path="services" element={<AdminServices />} />
<Route path="membership" element={<AdminMembership />} /> <Route path="membership" element={<AdminMembership />} />
+1019 -13
View File
File diff suppressed because it is too large. Load diff
@@ -392,3 +392,111 @@
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
} }
/* ===== 页面头部与提示组件(短信配置等页复用) ===== */
.admin-page-header {
display: flex;
align-items: flex-end;
justify-content: space-between;
margin-bottom: var(--space-xl);
gap: var(--space-lg);
}
.admin-page-subtitle {
margin: 6px 0 0;
font-size: var(--text-sm);
color: var(--color-text-secondary);
}
.admin-alert {
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-md) var(--space-lg);
border-radius: var(--radius-md);
font-size: var(--text-sm);
margin-bottom: var(--space-lg);
border: 1px solid transparent;
line-height: 1.5;
}
.admin-alert-success {
background: var(--color-success-light);
border-color: var(--color-success);
color: var(--color-success);
}
.admin-alert-error {
background: var(--color-error-light);
border-color: var(--color-error);
color: var(--color-error);
}
.admin-alert-info {
background: var(--color-info-light);
border-color: var(--color-info);
color: var(--color-info);
}
.admin-form-hint {
margin-top: var(--space-md);
font-size: var(--text-xs);
color: var(--color-text-tertiary);
line-height: 1.6;
}
.admin-form-hint code {
background: var(--color-bg-tertiary);
padding: 1px 6px;
border-radius: var(--radius-sm);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: var(--text-xs);
}
.admin-tips {
margin: 0;
padding-left: var(--space-xl);
color: var(--color-text-secondary);
font-size: var(--text-sm);
line-height: 1.9;
}
.admin-tips li {
margin-bottom: var(--space-xs);
}
/* ===== 顶部栏与面包屑 ===== */
.admin-topbar {
position: sticky;
top: 0;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
height: 56px;
margin: calc(-1 * var(--space-2xl)) calc(-1 * var(--space-2xl)) var(--space-2xl);
padding: 0 var(--space-2xl);
background: rgba(255, 255, 255, 0.82);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border-bottom: 1px solid var(--color-border);
}
.admin-breadcrumb {
display: flex;
align-items: center;
gap: var(--space-sm);
font-size: var(--text-sm);
}
.crumb-root { color: var(--color-text-tertiary); }
.crumb-sep { color: var(--color-text-disabled); }
.crumb-group { color: var(--color-text-secondary); }
.crumb-current { color: var(--color-text-primary); font-weight: 600; }
.admin-topbar-user {
display: flex;
align-items: center;
gap: var(--space-sm);
font-size: var(--text-sm);
color: var(--color-text-secondary);
}
.admin-user-avatar.sm {
width: 28px;
height: 28px;
font-size: var(--text-xs);
}
.admin-topbar-username { font-weight: 600; color: var(--color-text-primary); }
@@ -73,6 +73,7 @@ const adminNavGroups: NavGroup[] = [
icon: 'settings', icon: 'settings',
items: [ items: [
{ path: '/admin/settings', icon: 'settings', label: '网站设置' }, { path: '/admin/settings', icon: 'settings', label: '网站设置' },
{ path: '/admin/sms', icon: 'sms', label: '短信配置' },
{ path: '/admin/logs', icon: 'logs', label: '日志与风控' }, { path: '/admin/logs', icon: 'logs', label: '日志与风控' },
{ path: '/admin/im-bots', icon: 'imbot', label: 'IM 机器人' }, { path: '/admin/im-bots', icon: 'imbot', label: 'IM 机器人' },
{ path: '/admin/privacy', icon: 'privacy', label: '隐私与本地代理' }, { path: '/admin/privacy', icon: 'privacy', label: '隐私与本地代理' },
@@ -123,12 +124,26 @@ const adminIconPaths: Record<string, JSX.Element> = {
apps: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>, apps: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
assets: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>, assets: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
chevron: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>, chevron: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>,
sms: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>,
}; };
const AdminLayout: React.FC = () => { const AdminLayout: React.FC = () => {
const { user, logout } = useAuth(); const { user, logout } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const navCrumb = (() => {
for (const g of adminNavGroups) {
for (const it of g.items) {
const match = it.exact
? location.pathname === it.path
: location.pathname === it.path || location.pathname.startsWith(it.path + '/');
if (match) return { group: g.title, label: it.label };
}
}
return { group: '', label: '' };
})();
const navGroup = navCrumb.group;
const navLabel = navCrumb.label;
// Default: all groups collapsed. Auto-expand the group containing the active route. // Default: all groups collapsed. Auto-expand the group containing the active route.
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(() => { const [expandedGroups, setExpandedGroups] = useState<Set<string>>(() => {
@@ -227,6 +242,17 @@ const AdminLayout: React.FC = () => {
</div> </div>
</aside> </aside>
<main className="admin-content"> <main className="admin-content">
<header className="admin-topbar">
<nav className="admin-breadcrumb" aria-label="breadcrumb">
<span className="crumb-root">管理控制台</span>
{navGroup && (<><span className="crumb-sep">/</span><span className="crumb-group">{navGroup}</span></>)}
{navLabel && (<><span className="crumb-sep">/</span><span className="crumb-current">{navLabel}</span></>)}
</nav>
<div className="admin-topbar-user">
<div className="admin-user-avatar sm">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
<span className="admin-topbar-username">{user?.username || 'admin'}</span>
</div>
</header>
<Outlet /> <Outlet />
</main> </main>
</div> </div>
+1 -76
View File
@@ -14,9 +14,6 @@ const SiteSettings: React.FC = () => {
const [mail, setMail] = useState({ const [mail, setMail] = useState({
smtp_host: '', smtp_port: 587, username: '', password: '', from_address: '', use_tls: true, smtp_host: '', smtp_port: 587, username: '', password: '', from_address: '', use_tls: true,
}); });
const [sms, setSms] = useState({
provider: '', api_key: '', api_secret: '', sign_name: '', template_code: '',
});
const [savedMsg, setSavedMsg] = useState<string | null>(null); const [savedMsg, setSavedMsg] = useState<string | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [testResult, setTestResult] = useState<string | null>(null); const [testResult, setTestResult] = useState<string | null>(null);
@@ -143,21 +140,6 @@ const SiteSettings: React.FC = () => {
}; };
// 保存短信配置 // 保存短信配置
const saveSmsConfig = async () => {
try {
await adminAPI.updateSmsConfig({
provider: sms.provider,
api_key: sms.api_key,
api_secret: sms.api_secret,
sign_name: sms.sign_name,
template_code: sms.template_code,
});
showSaved('短信配置');
} catch (e: any) {
alert('保存失败: ' + (e.detail || e.message));
}
};
// 发送测试邮件 - 先保存配置再发送 // 发送测试邮件 - 先保存配置再发送
const sendTestEmail = async () => { const sendTestEmail = async () => {
if (!emailTestTo.trim()) { if (!emailTestTo.trim()) {
@@ -193,16 +175,6 @@ const SiteSettings: React.FC = () => {
setShowEmailTest(true); setShowEmailTest(true);
}; };
// 发送测试短信
const sendTestSms = async () => {
try {
const res = await adminAPI.testSms();
showTestResult('测试短信发送成功: ' + (res?.message || 'OK'));
} catch (e: any) {
showTestResult('测试短信发送失败: ' + (e.detail || e.message));
}
};
if (loading) { if (loading) {
return <div style={{ padding: 40, textAlign: 'center' }}>加载中...</div>; return <div style={{ padding: 40, textAlign: 'center' }}>加载中...</div>;
} }
@@ -317,54 +289,7 @@ const SiteSettings: React.FC = () => {
</div> </div>
{/* SMS Config */} {/* SMS Config */}
<div className="admin-card"> {/* Email Test Modal */}
<div className="admin-card-header">
<h3 className="admin-card-title">
<SVGIcon size={18}><rect x="5" y="2" width="14" height="20" rx="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></SVGIcon>
{' '}短信配置
</h3>
</div>
<div className="admin-form-row">
<div className="admin-form-group">
<label className="admin-form-label">短信服务商</label>
<select className="admin-form-input" value={sms.provider} onChange={e => setSms({ ...sms, provider: e.target.value })}>
<option value="">请选择</option>
<option value="阿里云短信">阿里云短信</option>
<option value="腾讯云短信">腾讯云短信</option>
<option value="华为云短信">华为云短信</option>
</select>
</div>
<div className="admin-form-group">
<label className="admin-form-label">短信签名</label>
<input className="admin-form-input" value={sms.sign_name} onChange={e => setSms({ ...sms, sign_name: e.target.value })} />
</div>
</div>
<div className="admin-form-row">
<div className="admin-form-group">
<label className="admin-form-label">API Key</label>
<input className="admin-form-input" value={sms.api_key} onChange={e => setSms({ ...sms, api_key: e.target.value })} />
</div>
<div className="admin-form-group">
<label className="admin-form-label">API Secret</label>
<input className="admin-form-input" type="password" value={sms.api_secret} onChange={e => setSms({ ...sms, api_secret: e.target.value })} />
</div>
</div>
<div className="admin-form-actions">
<button className="admin-btn admin-btn-primary" onClick={saveSmsConfig}>
<SVGIcon><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></SVGIcon>
保存设置
</button>
<button className="admin-btn admin-btn-outline" onClick={sendTestSms}>
<SVGIcon><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></SVGIcon>
发送测试短信
</button>
</div>
</div>
{/* Email Test Modal */}
{showEmailTest && ( {showEmailTest && (
<div style={{ <div style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
+252
View File
@@ -0,0 +1,252 @@
import React, { useState, useEffect } from 'react';
import { adminAPI } from '@/api';
const SVGIcon: React.FC<{ children: React.ReactNode; size?: number }> = ({ children, size = 16 }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
{children}
</svg>
);
const SmsConfig: React.FC = () => {
const [cfg, setCfg] = useState<Record<string, string>>({
provider: '',
api_key: '',
api_secret: '',
sign_name: '',
template_code: '',
username: '',
password: '',
goods_id: '',
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [querying, setQuerying] = useState(false);
const [savedMsg, setSavedMsg] = useState<string | null>(null);
const [testResult, setTestResult] = useState<{ ok: boolean; msg: string } | null>(null);
const [balance, setBalance] = useState<{ sent: number; remain: number } | null>(null);
useEffect(() => {
(async () => {
try {
const res = await adminAPI.getSmsConfig();
const data = (res as any)?.data ?? res;
setCfg({
provider: data.provider || '',
api_key: data.api_key || '',
api_secret: data.api_secret || '',
sign_name: data.sign_name || '',
template_code: data.template_code || '',
username: data.username || '',
password: data.password || '',
goods_id: data.goods_id || '',
});
} catch (e) {
// ignore
} finally {
setLoading(false);
}
})();
}, []);
const update = (patch: Partial<Record<string, string>>) =>
setCfg((prev) => ({ ...prev, ...patch }));
const save = async () => {
setSaving(true);
setSavedMsg(null);
setTestResult(null);
try {
await adminAPI.updateSmsConfig({
provider: cfg.provider,
api_key: cfg.api_key,
api_secret: cfg.api_secret,
sign_name: cfg.sign_name,
template_code: cfg.template_code,
username: cfg.username,
password: cfg.password,
goods_id: cfg.goods_id,
});
setSavedMsg('短信配置已保存');
} catch (e: any) {
setSavedMsg('保存失败:' + (e?.response?.data?.detail || e?.message || '未知错误'));
} finally {
setSaving(false);
}
};
const sendTest = async () => {
setTesting(true);
setTestResult(null);
setSavedMsg(null);
try {
const res = await adminAPI.testSms();
const data = (res as any)?.data ?? res;
setTestResult({ ok: true, msg: data?.message || '测试短信已发送' });
} catch (e: any) {
setTestResult({ ok: false, msg: e?.response?.data?.detail || e?.message || '发送失败' });
} finally {
setTesting(false);
}
};
const queryBalance = async () => {
setQuerying(true);
setBalance(null);
setTestResult(null);
try {
const res = await adminAPI.getSmsBalance();
const data = (res as any)?.data ?? res;
setBalance({ sent: data?.sent ?? 0, remain: data?.remain ?? 0 });
} catch (e: any) {
setTestResult({ ok: false, msg: e?.response?.data?.detail || e?.message || '查询余额失败' });
} finally {
setQuerying(false);
}
};
const isSmsBao = cfg.provider === '短信宝';
if (loading) {
return <div className="admin-page"><div className="admin-page-title">短信配置</div><p style={{ color: 'var(--color-text-secondary)' }}>加载中…</p></div>;
}
return (
<div className="admin-page">
<div className="admin-page-header">
<div>
<h2 className="admin-page-title">短信配置</h2>
<p className="admin-page-subtitle">配置短信服务商,用于验证码、通知类短信的发送</p>
</div>
</div>
{savedMsg && (
<div className={`admin-alert ${savedMsg.startsWith('保存失败') ? 'admin-alert-error' : 'admin-alert-success'}`}>
{savedMsg}
</div>
)}
{testResult && (
<div className={`admin-alert ${testResult.ok ? 'admin-alert-success' : 'admin-alert-error'}`}>
{testResult.msg}
</div>
)}
{balance && (
<div className="admin-alert admin-alert-info">
短信宝账户:已发送 <b>{balance.sent}</b> 条,剩余 <b>{balance.remain}</b> 条
</div>
)}
<div className="admin-card">
<div className="admin-card-header">
<h3 className="admin-card-title">
<SVGIcon size={18}>
<rect x="5" y="2" width="14" height="20" rx="2" />
<line x1="12" y1="18" x2="12.01" y2="18" />
</SVGIcon>
{' '}服务商与账号
</h3>
</div>
<div className="admin-form-row">
<div className="admin-form-group">
<label className="admin-form-label">短信服务商</label>
<select className="admin-form-input" value={cfg.provider} onChange={(e) => update({ provider: e.target.value })}>
<option value="">请选择</option>
<option value="阿里云短信">阿里云短信</option>
<option value="腾讯云短信">腾讯云短信</option>
<option value="华为云短信">华为云短信</option>
<option value="短信宝">短信宝</option>
</select>
</div>
<div className="admin-form-group">
<label className="admin-form-label">短信签名</label>
<input
className="admin-form-input"
placeholder={isSmsBao ? '如:七虎AI(发送时自动包裹【】)' : '如:七虎AI'}
value={cfg.sign_name}
onChange={(e) => update({ sign_name: e.target.value })}
/>
</div>
</div>
{isSmsBao ? (
<>
<div className="admin-form-row">
<div className="admin-form-group">
<label className="admin-form-label">用户名 (u)</label>
<input className="admin-form-input" value={cfg.username} onChange={(e) => update({ username: e.target.value })} placeholder="短信宝登录用户名" />
</div>
<div className="admin-form-group">
<label className="admin-form-label">密码 (p)</label>
<input className="admin-form-input" type="password" value={cfg.password} onChange={(e) => update({ password: e.target.value })} placeholder="短信宝登录密码(发送时自动 MD5)" />
</div>
</div>
<div className="admin-form-row">
<div className="admin-form-group" style={{ maxWidth: 360 }}>
<label className="admin-form-label">专属通道产品 ID (g) <span style={{ color: 'var(--color-text-muted)' }}>选填</span></label>
<input className="admin-form-input" value={cfg.goods_id} onChange={(e) => update({ goods_id: e.target.value })} placeholder="留空使用默认通用产品" />
</div>
</div>
<div className="admin-form-hint">
短信宝发送接口:<code>api.smsbao.com/sms</code>,密码以登录密码的 MD5(32位) 提交,短信内容需包含签名 <code>【签名】</code>。
</div>
</>
) : (
<>
<div className="admin-form-row">
<div className="admin-form-group">
<label className="admin-form-label">API Key</label>
<input className="admin-form-input" value={cfg.api_key} onChange={(e) => update({ api_key: e.target.value })} placeholder={cfg.provider === '阿里云短信' ? 'AccessKey ID' : 'API Key'} />
</div>
<div className="admin-form-group">
<label className="admin-form-label">API Secret</label>
<input className="admin-form-input" type="password" value={cfg.api_secret} onChange={(e) => update({ api_secret: e.target.value })} placeholder={cfg.provider === '阿里云短信' ? 'AccessKey Secret' : 'API Secret'} />
</div>
</div>
{cfg.provider === '阿里云短信' && (
<div className="admin-form-row">
<div className="admin-form-group" style={{ maxWidth: 360 }}>
<label className="admin-form-label">模板 Code <span style={{ color: 'var(--color-text-muted)' }}>选填</span></label>
<input className="admin-form-input" value={cfg.template_code} onChange={(e) => update({ template_code: e.target.value })} placeholder="如 SMS_00000001" />
</div>
</div>
)}
</>
)}
<div className="admin-form-actions">
<button className="admin-btn admin-btn-primary" onClick={save} disabled={saving}>
<SVGIcon><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" /><polyline points="17 21 17 13 7 13 7 21" /><polyline points="7 3 7 8 15 8" /></SVGIcon>
{saving ? '保存中…' : '保存设置'}
</button>
<button className="admin-btn admin-btn-outline" onClick={sendTest} disabled={testing}>
<SVGIcon><line x1="22" y1="2" x2="11" y2="13" /><polygon points="22 2 15 22 11 13 2 9 2 2" /></SVGIcon>
{testing ? '发送中…' : '发送测试短信'}
</button>
{isSmsBao && (
<button className="admin-btn admin-btn-outline" onClick={queryBalance} disabled={querying}>
<SVGIcon><line x1="12" y1="1" x2="12" y2="23" /><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" /></SVGIcon>
{querying ? '查询中…' : '查询余额'}
</button>
)}
</div>
</div>
<div className="admin-card">
<div className="admin-card-header">
<h3 className="admin-card-title">
<SVGIcon size={18}><circle cx="12" cy="12" r="10" /><line x1="12" y1="16" x2="12" y2="12" /><line x1="12" y1="8" x2="12.01" y2="8" /></SVGIcon>
{' '}说明
</h3>
</div>
<ul className="admin-tips">
<li>测试短信将发送至<strong>当前管理员账号绑定的手机号</strong>,请先在用户管理中完善手机号。</li>
<li>阿里云、腾讯云、华为云使用平台统一的短信网关;短信宝为独立通道,支持余额查询。</li>
<li>短信内容须符合运营商规范,包含签名与退订提示,避免触发敏感词拦截。</li>
</ul>
</div>
</div>
);
};
export default SmsConfig;