/** * 支付客户端 - 封装支付 API 调用 * 用于前端发起支付、跳转支付页 */ import { getPaymentConfig, getJoinPaymentConfig } from "@/config/services.config"; import type { PayChannel, PayEnv } from "./types"; /** 发起支付并跳转(表单 POST 到 /api/pay) */ export function redirectToPay(params: { user_id: string; return_url: string; total_fee?: number; type?: string; channel: PayChannel; device: "pc" | "h5" | "wechat"; /** 是否使用「加入」场景配置(主题覆盖) */ useJoinConfig?: boolean; }): void { const baseConfig = getPaymentConfig(); const joinConfig = params.useJoinConfig ? getJoinPaymentConfig() : null; const total_fee = params.total_fee ?? joinConfig?.amount ?? baseConfig.defaultAmount; const type = params.type ?? joinConfig?.type ?? baseConfig.defaultType; const payForm = document.createElement("form"); payForm.method = "POST"; payForm.action = "/api/pay"; payForm.target = "_self"; payForm.style.display = "none"; const fields: [string, string][] = [ ["user_id", params.user_id], ["return_url", params.return_url], ["total_fee", String(total_fee)], ["type", type], ["channel", params.channel], ["device", params.device], ["html", "1"], ]; fields.forEach(([k, v]) => { const input = document.createElement("input"); input.type = "hidden"; input.name = k; input.value = v; payForm.appendChild(input); }); document.body.appendChild(payForm); payForm.submit(); } /** 根据 PayEnv 确定 device:微信内用 wechat 走收银台表单,payurl2 仅支持微信外 */ export function getDeviceFromEnv(env: PayEnv): "pc" | "h5" | "wechat" { if (env === "wechat") return "wechat"; return env === "pc" ? "pc" : "h5"; }