feat(payment): integrate epay (易支付) gateway for CNY recharges
release / release (release) Canceled after 0s
release / release (release) Canceled after 0s
- new EpayClient: V1 md5 signing, submit.php page pay, api.php order query - create/verify epay payment links with CNY exchange-rate conversion - signed async notify handler (/admin/payment/callback_epay) with amount check plus idempotent crediting, and a gateway query fallback - epay channel config form, channel row and payment_method enum extended - RechargeModal: send payment_method (was payment_channel, so every recharge fell through to Stripe and 500'd) and re-enable the channel picker - payment config encryption key moved to a local .env, never committed
This commit is contained in:
1 parent
1fbb6711f2
commit
721a2be32b
12 files changed
+770
-12
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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,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;
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -48,7 +59,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
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>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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})
|
||||
@@ -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
|
||||
@@ -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