基于您提供的 FastAPI 后端,下面是一个对应的 React 支付页面示例。这个示例将包括一个表单,用户可以在其中输入必要的支付信息,提交后将请求发送到后端 API,并显示返回的结果。
步骤概览
- 创建 React 应用:使用
create-react-app 创建一个新的 React 项目。
- 安装依赖:安装
axios 以便进行 HTTP 请求。
- 实现支付表单:创建一个支付表单组件,允许用户输入
trade_order_id、payment、total_fee 和 title。
- 处理表单提交:在表单提交时,使用
axios 向后端发送 POST 请求,并处理响应。
- 显示支付结果:根据后端的响应显示支付成功或失败的消息。
1. 创建 React 应用
首先,确保您已安装 Node.js 和 npm 或 Yarn。然后,使用 create-react-app 创建一个新的项目:
npx create-react-app payment-app
cd payment-app
2. 安装 Axios
在项目目录中,安装 axios 以便进行 HTTP 请求:
npm install axios
或使用 Yarn:
yarn add axios
3. 实现支付表单
编辑 src/App.js 文件,创建一个支付表单组件:
// src/App.js
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [tradeOrderId, setTradeOrderId] = useState('');
const [payment, setPayment] = useState('');
const [totalFee, setTotalFee] = useState('');
const [title, setTitle] = useState('');
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
// 重置状态
setResponse(null);
setError(null);
// 构建支付请求数据
const paymentData = {
trade_order_id: tradeOrderId,
payment: payment,
total_fee: parseFloat(totalFee),
title: title,
};
try {
const res = await axios.post('http://localhost:8000/pay', paymentData, {
headers: {
'Content-Type': 'application/json',
},
});
setResponse(res.data);
} catch (err) {
if (err.response) {
// 服务器返回的错误
setError(err.response.data.detail || '支付处理失败');
} else {
// 网络或其他错误
setError('网络错误,请稍后再试');
}
}
};
return (
<div className="App">
<h1>支付页面</h1>
<form onSubmit={handleSubmit} className="payment-form">
<div className="form-group">
<label htmlFor="tradeOrderId">订单号 (trade_order_id):</label>
<input
type="text"
id="tradeOrderId"
value={tradeOrderId}
onChange={(e) => setTradeOrderId(e.target.value)}
required
/>
</div>
<div className="form-group">
<label htmlFor="payment">支付方式 (payment):</label>
<input
type="text"
id="payment"
value={payment}
onChange={(e) => setPayment(e.target.value)}
required
/>
</div>
<div className="form-group">
<label htmlFor="totalFee">金额 (total_fee):</label>
<input
type="number"
id="totalFee"
value={totalFee}
onChange={(e) => setTotalFee(e.target.value)}
step="0.01"
min="0"
required
/>
</div>
<div className="form-group">
<label htmlFor="title">标题 (title):</label>
<input
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<button type="submit">提交支付</button>
</form>
{response && (
<div className="response">
<h2>支付结果</h2>
<p><strong>Status:</strong> {response.status}</p>
<p><strong>Transaction ID:</strong> {response.transaction_id}</p>
<p><strong>Trade Order ID:</strong> {response.trade_order_id}</p>
<p><strong>Amount:</strong> {response.amount}</p>
<p><strong>Message:</strong> {response.message}</p>
</div>
)}
{error && (
<div className="error">
<h2>错误</h2>
<p>{error}</p>
</div>
)}
</div>
);
}
export default App;
4. 添加样式(可选)
为了让支付页面看起来更加美观,您可以编辑 src/App.css 添加一些基本样式:
/* src/App.css */
.App {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
h1 {
text-align: center;
margin-bottom: 30px;
}
.payment-form .form-group {
margin-bottom: 15px;
}
.payment-form label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.payment-form input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.payment-form button {
width: 100%;
padding: 10px;
background-color: #28a745;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
}
.payment-form button:hover {
background-color: #218838;
}
.response, .error {
margin-top: 30px;
padding: 15px;
border-radius: 4px;
}
.response {
background-color: #d4edda;
border: 1px solid #c3e6cb;
}
.error {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
}
.response h2, .error h2 {
margin-top: 0;
}
5. 运行 React 应用
在项目目录中,启动 React 应用:
npm start
或使用 Yarn:
yarn start
应用将默认在 http://localhost:3000 运行。确保您的 FastAPI 后端也在运行,并监听 http://localhost:8000。
完整的代码结构
为了帮助您更好地理解项目结构,以下是相关文件的完整代码:
src/App.js
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [tradeOrderId, setTradeOrderId] = useState('');
const [payment, setPayment] = useState('');
const [totalFee, setTotalFee] = useState('');
const [title, setTitle] = useState('');
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
// 重置状态
setResponse(null);
setError(null);
// 构建支付请求数据
const paymentData = {
trade_order_id: tradeOrderId,
payment: payment,
total_fee: parseFloat(totalFee),
title: title,
};
try {
const res = await axios.post('http://localhost:8000/pay', paymentData, {
headers: {
'Content-Type': 'application/json',
},
});
setResponse(res.data);
} catch (err) {
if (err.response) {
// 服务器返回的错误
setError(err.response.data.detail || '支付处理失败');
} else {
// 网络或其他错误
setError('网络错误,请稍后再试');
}
}
};
return (
<div className="App">
<h1>支付页面</h1>
<form onSubmit={handleSubmit} className="payment-form">
<div className="form-group">
<label htmlFor="tradeOrderId">订单号 (trade_order_id):</label>
<input
type="text"
id="tradeOrderId"
value={tradeOrderId}
onChange={(e) => setTradeOrderId(e.target.value)}
required
/>
</div>
<div className="form-group">
<label htmlFor="payment">支付方式 (payment):</label>
<input
type="text"
id="payment"
value={payment}
onChange={(e) => setPayment(e.target.value)}
required
/>
</div>
<div className="form-group">
<label htmlFor="totalFee">金额 (total_fee):</label>
<input
type="number"
id="totalFee"
value={totalFee}
onChange={(e) => setTotalFee(e.target.value)}
step="0.01"
min="0"
required
/>
</div>
<div className="form-group">
<label htmlFor="title">标题 (title):</label>
<input
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<button type="submit">提交支付</button>
</form>
{response && (
<div className="response">
<h2>支付结果</h2>
<p><strong>Status:</strong> {response.status}</p>
<p><strong>Transaction ID:</strong> {response.transaction_id}</p>
<p><strong>Trade Order ID:</strong> {response.trade_order_id}</p>
<p><strong>Amount:</strong> {response.amount}</p>
<p><strong>Message:</strong> {response.message}</p>
</div>
)}
{error && (
<div className="error">
<h2>错误</h2>
<p>{error}</p>
</div>
)}
</div>
);
}
export default App;
src/App.css
.App {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
h1 {
text-align: center;
margin-bottom: 30px;
}
.payment-form .form-group {
margin-bottom: 15px;
}
.payment-form label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.payment-form input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.payment-form button {
width: 100%;
padding: 10px;
background-color: #28a745;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
}
.payment-form button:hover {
background-color: #218838;
}
.response, .error {
margin-top: 30px;
padding: 15px;
border-radius: 4px;
}
.response {
background-color: #d4edda;
border: 1px solid #c3e6cb;
}
.error {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
}
.response h2, .error h2 {
margin-top: 0;
}
src/index.js
确保 src/index.js 正确引入 App 组件:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
public/index.html
确保在 public/index.html 中有一个 div 元素用于挂载 React 应用:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>支付页面</title>
</head>
<body>
<noscript>您需要启用 JavaScript 来运行此应用。</noscript>
<div id="root"></div>
</body>
</html>
运行和测试
- 启动后端:确保您的 FastAPI 后端正在运行,并监听
http://localhost:8000。
- 启动前端:在
payment-app 目录下,运行 npm start 启动 React 应用。
- 访问支付页面:打开浏览器,访问
http://localhost:3000。
- 填写支付信息并提交:在表单中输入
trade_order_id、payment、total_fee 和 title,然后点击“提交支付”按钮。
- 查看支付结果:提交后,页面将显示支付结果或错误消息。
注意事项
- CORS 配置:您现有的 FastAPI 后端已经配置了允许所有来源 (
allow_origins=["*"])。在生产环境中,建议将其限制为实际使用的前端域名以提高安全性。
- 环境变量:如果您的后端使用了环境变量 (
HUPI_APPID, HUPI_APPSECRET 等),确保在运行后端时正确设置这些变量。
- 错误处理:前端已经包含基本的错误处理逻辑,但根据实际需求,您可能需要更详细的错误反馈和处理。
- 安全性:确保在生产环境中,通过 HTTPS 保护通信安全,并对敏感信息进行适当的加密和保护。
通过以上步骤,您应该能够成功构建一个与 FastAPI 后端集成的 React 支付页面。如果有任何问题或需要进一步的帮助,请随时提问!