Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

请基于这个api后端构建对应的react支付页面: from fastapi import FastAPI, HTTPException from…

  1. User

    请基于这个api后端构建对应的react支付页面:

    from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import hashlib import time import httpx from urllib.parse import urlencode, unquote_plus import os from typing import Dict, Any import logging import config

    app = FastAPI()

    Setup CORS

    app.add_middleware( CORSMiddleware, allow_origins=[""], # Change this for production allow_credentials=True, allow_methods=[""], allow_headers=["*"], )

    Setup logging

    logging.basicConfig(level=logging.INFO)

    Pydantic models

    class PaymentRequest(BaseModel): trade_order_id: str payment: str total_fee: float title: str

    class PaymentResponse(BaseModel): status: str transaction_id: str trade_order_id: str amount: float message: str

    Hupi utility functions

    def ksort(d: Dict[str, Any]) -> Dict[str, Any]: return dict(sorted(d.items()))

    def sign(attributes: Dict[str, Any], app_secret: str) -> str: attributes = ksort(attributes) sign_str = unquote_plus(urlencode(attributes)) + app_secret logging.info(f"String to hash: {sign_str}") return hashlib.md5(sign_str.encode('utf-8')).hexdigest()

    async def curl(data: Dict[str, Any], url: str, app_secret: str) -> Dict[str, Any]: data['hash'] = sign(data, app_secret) headers = {"Referer": "http://localhost:5000"} async with httpx.AsyncClient() as client: response = await client.post(url, data=data, headers=headers) return response.json()

    async def process_payment(payment_data: PaymentRequest) -> Dict[str, Any]: appid = os.getenv("HUPI_APPID", "202303140058") app_secret = os.getenv("HUPI_APPSECRET", "60b31fde738c25dd0b28f7bff7f06311") url = "https://api.xunhuweb.com/payment/do.html" current_time = str(int(time.time()))

    data = {
        "version": "1.1",
        "lang": "zh-cn",
        "plugins": "fastapi",
        "appid": appid,
        "trade_order_id": payment_data.trade_order_id,
        "payment": payment_data.payment,
        "is_app": "Y",
        "total_fee": payment_data.total_fee,
        "title": payment_data.title,
        "description": "",
        "time": current_time,
        "notify_url": f"{config.domain}/notify_url",
        "return_url": f"{config.domain}/return_url",
        "callback_url": f"{config.domain}/callback_url",
        "nonce_str": current_time,
    }
    logging.info(f"Request data: {data}")
    return await curl(data, url, app_secret)
    

    @app.post("/pay", response_model=PaymentResponse) async def pay(payment_request: PaymentRequest): logging.info(f"Payment request received: {payment_request}") try: response = await process_payment(payment_request) logging.info(f"Payment response: {response}") return PaymentResponse( status=response.get('status', 'unknown'), transaction_id=response.get('transaction_id', ''), trade_order_id=payment_request.trade_order_id, amount=payment_request.total_fee, message=response.get('message', 'Payment processed') ) except Exception as e: logging.error(f"Error processing payment: {e}") raise HTTPException(status_code=500, detail="Payment processing failed")

    if name == 'main': import uvicorn uvicorn.run(app, host="localhost", port=8000)

  2. Assistant

    To create a React payment page that interacts with the FastAPI backend you provided, you can follow these steps. I'll outline how to build a simple form that collects payment details and sends them to the API.

    Step 1: Set up a React Project

    First, create a new React app using Create React App:

    npx create-react-app payment-page
    cd payment-page
    

    Step 2: Create a Payment Form Component

    Create a new file called PaymentForm.js inside the src directory and add the following code:

    import React, { useState } from "react";
    import axios from "axios";
    
    function PaymentForm() {
      const [formData, setFormData] = useState({
        trade_order_id: "",
        payment: "",
        total_fee: 0,
        title: ""
      });
    
      const [paymentResponse, setPaymentResponse] = useState(null);
    
      const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({
          ...formData,
          [name]: value
        });
      };
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
          const response = await axios.post("http://localhost:8000/pay", formData);
          setPaymentResponse(response.data);
        } catch (error) {
          console.error("Error processing payment:", error);
          alert("Payment processing failed");
        }
      };
    
      return (
        <div>
          <h2>Payment Form</h2>
          <form onSubmit={handleSubmit}>
            <div>
              <label>Trade Order ID:</label>
              <input type="text" name="trade_order_id" value={formData.trade_order_id} onChange={handleChange} required />
            </div>
            <div>
              <label>Payment Type:</label>
              <input type="text" name="payment" value={formData.payment} onChange={handleChange} required />
            </div>
            <div>
              <label>Total Fee:</label>
              <input type="number" name="total_fee" value={formData.total_fee} onChange={handleChange} required />
            </div>
            <div>
              <label>Title:</label>
              <input type="text" name="title" value={formData.title} onChange={handleChange} required />
            </div>
            <button type="submit">Submit Payment</button>
          </form>
    
          {paymentResponse && (
            <div>
              <h3>Payment Response</h3>
              <p>Status: {paymentResponse.status}</p>
              <p>Transaction ID: {paymentResponse.transaction_id}</p>
              <p>Trade Order ID: {paymentResponse.trade_order_id}</p>
              <p>Amount: {paymentResponse.amount}</p>
              <p>Message: {paymentResponse.message}</p>
            </div>
          )}
        </div>
      );
    }
    
    export default PaymentForm;
    

    Step 3: Update the App.js to render the Payment Form

    Replace the content of src/App.js with:

    import React from 'react';
    import PaymentForm from './PaymentForm';
    
    function App() {
      return (
        <div className="App">
          <header className="App-header">
            <h1>React Payment Page</h1>
            <PaymentForm />
          </header>
        </div>
      );
    }
    
    export default App;
    

    Step 4: Install Axios

    Axios is used to send HTTP requests. Install it in your React project:

    npm install axios
    

    Step 5: Run the React App

    Start your React app by running:

    npm start
    

    By following these steps, you'll have a basic React payment page that collects payment details and sends them to your FastAPI backend for processing.

    Remember that the FastAPI server must be running on http://localhost:8000 as specified in the axios.post() call. The form includes a simple interface with fields for the trade order ID, payment type, and other details. The response from the API is displayed below the form after submission.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.