refactor: simplify WeChat MP OAuth handling and update channel configuration structure

This commit is contained in:
mlogclub
2026-04-27 16:01:00 +08:00
parent fbabb174d2
commit 2220dcb0cb
4 changed files with 209 additions and 193 deletions
@@ -40,8 +40,7 @@ func (c *ChannelController) AnyConfig() *web.JsonResult {
func (c *ChannelController) AnyWechat_mpOauthAuthorize() *web.JsonResult { func (c *ChannelController) AnyWechat_mpOauthAuthorize() *web.JsonResult {
channelID, _ := params.Get(c.Ctx, "channelId") channelID, _ := params.Get(c.Ctx, "channelId")
returnPath, _ := params.Get(c.Ctx, "returnPath") redirectURL, err := services.ChannelService.BuildWechatMPOAuthURL(c.Ctx, channelID)
redirectURL, err := services.ChannelService.BuildWechatMPOAuthURL(c.Ctx, channelID, returnPath)
if err != nil { if err != nil {
return web.JsonError(err) return web.JsonError(err)
} }
@@ -91,8 +90,8 @@ func resolveWidgetConfig(channelType, rawConfig string) (*webLikeWidgetConfig, s
Title: cfg.Title, Title: cfg.Title,
Subtitle: cfg.Subtitle, Subtitle: cfg.Subtitle,
ThemeColor: cfg.ThemeColor, ThemeColor: cfg.ThemeColor,
Position: cfg.Position, Position: "right",
Width: cfg.Width, Width: "100%",
}, string(enums.ExternalSourceWechatMP), nil }, string(enums.ExternalSourceWechatMP), nil
default: default:
return nil, "", errorsx.InvalidParam("该渠道不支持开放客服配置") return nil, "", errorsx.InvalidParam("该渠道不支持开放客服配置")
+6 -9
View File
@@ -25,13 +25,10 @@ type WebChannelConfig struct {
} }
type WechatMPChannelConfig struct { type WechatMPChannelConfig struct {
Title string `json:"title"` Title string `json:"title"`
Subtitle string `json:"subtitle"` Subtitle string `json:"subtitle"`
ThemeColor string `json:"themeColor"` ThemeColor string `json:"themeColor"`
Position string `json:"position"` AppID string `json:"appId"`
Width string `json:"width"` AppSecret string `json:"appSecret"`
AppID string `json:"appId"` OAuthScope string `json:"oauthScope"`
AppSecret string `json:"appSecret"`
OAuthScope string `json:"oauthScope"`
OAuthEnabled bool `json:"oauthEnabled"`
} }
+15 -56
View File
@@ -42,16 +42,14 @@ type channelService struct {
} }
type wechatMPOAuthState struct { type wechatMPOAuthState struct {
ChannelID string `json:"channelId"` ChannelID string `json:"channelId"`
ReturnPath string `json:"returnPath"` ExpiresAt int64 `json:"expiresAt"`
ExpiresAt int64 `json:"expiresAt"`
} }
type WechatMPOAuthResult struct { type WechatMPOAuthResult struct {
ChannelID string ChannelID string
ExternalID string ExternalID string
ExternalName string ExternalName string
ReturnPath string
} }
func (s *channelService) Get(id int64) *models.Channel { func (s *channelService) Get(id int64) *models.Channel {
@@ -265,13 +263,10 @@ func (s *channelService) ParseWebChannelConfig(raw string) (*dto.WebChannelConfi
func (s *channelService) ParseWechatMPChannelConfig(raw string) (*dto.WechatMPChannelConfig, error) { func (s *channelService) ParseWechatMPChannelConfig(raw string) (*dto.WechatMPChannelConfig, error) {
raw = strings.TrimSpace(raw) raw = strings.TrimSpace(raw)
cfg := &dto.WechatMPChannelConfig{ cfg := &dto.WechatMPChannelConfig{
Title: "公众号客服", Title: "公众号客服",
Subtitle: "欢迎咨询", Subtitle: "欢迎咨询",
ThemeColor: "#2563eb", ThemeColor: "#2563eb",
Position: "right", OAuthScope: "snsapi_base",
Width: "380px",
OAuthScope: "snsapi_base",
OAuthEnabled: true,
} }
if raw != "" { if raw != "" {
if err := json.Unmarshal([]byte(raw), cfg); err != nil { if err := json.Unmarshal([]byte(raw), cfg); err != nil {
@@ -287,17 +282,6 @@ func (s *channelService) ParseWechatMPChannelConfig(raw string) (*dto.WechatMPCh
if cfg.ThemeColor == "" { if cfg.ThemeColor == "" {
cfg.ThemeColor = "#2563eb" cfg.ThemeColor = "#2563eb"
} }
cfg.Position = strings.TrimSpace(cfg.Position)
if cfg.Position == "" {
cfg.Position = "right"
}
if cfg.Position != "left" && cfg.Position != "right" {
return nil, errorsx.InvalidParam("微信公众号渠道配置 position 只能为 left 或 right")
}
cfg.Width = strings.TrimSpace(cfg.Width)
if cfg.Width == "" {
cfg.Width = "380px"
}
cfg.AppID = strings.TrimSpace(cfg.AppID) cfg.AppID = strings.TrimSpace(cfg.AppID)
cfg.AppSecret = strings.TrimSpace(cfg.AppSecret) cfg.AppSecret = strings.TrimSpace(cfg.AppSecret)
cfg.OAuthScope = strings.TrimSpace(cfg.OAuthScope) cfg.OAuthScope = strings.TrimSpace(cfg.OAuthScope)
@@ -310,7 +294,7 @@ func (s *channelService) ParseWechatMPChannelConfig(raw string) (*dto.WechatMPCh
return cfg, nil return cfg, nil
} }
func (s *channelService) BuildWechatMPOAuthURL(ctx iris.Context, channelID, returnPath string) (string, error) { func (s *channelService) BuildWechatMPOAuthURL(ctx iris.Context, channelID string) (string, error) {
channelID = strings.TrimSpace(channelID) channelID = strings.TrimSpace(channelID)
if channelID == "" { if channelID == "" {
return "", errorsx.InvalidParam("channelId不能为空") return "", errorsx.InvalidParam("channelId不能为空")
@@ -323,17 +307,13 @@ func (s *channelService) BuildWechatMPOAuthURL(ctx iris.Context, channelID, retu
if err != nil { if err != nil {
return "", errorsx.InvalidParam("微信公众号渠道配置不合法") return "", errorsx.InvalidParam("微信公众号渠道配置不合法")
} }
if !cfg.OAuthEnabled {
return "", errorsx.InvalidParam("微信公众号渠道未启用 OAuth")
}
if cfg.AppID == "" || cfg.AppSecret == "" { if cfg.AppID == "" || cfg.AppSecret == "" {
return "", errorsx.InvalidParam("微信公众号渠道缺少 appId 或 appSecret") return "", errorsx.InvalidParam("微信公众号渠道缺少 appId 或 appSecret")
} }
state, err := s.signWechatMPOAuthState(wechatMPOAuthState{ state, err := s.signWechatMPOAuthState(wechatMPOAuthState{
ChannelID: channel.ChannelID, ChannelID: channel.ChannelID,
ReturnPath: normalizeWechatMPReturnPath(returnPath), ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
}, cfg.AppSecret) }, cfg.AppSecret)
if err != nil { if err != nil {
return "", err return "", err
@@ -392,7 +372,6 @@ func (s *channelService) CompleteWechatMPOAuth(ctx context.Context, code, state
ChannelID: channel.ChannelID, ChannelID: channel.ChannelID,
ExternalID: strings.TrimSpace(token.OpenID), ExternalID: strings.TrimSpace(token.OpenID),
ExternalName: externalName, ExternalName: externalName,
ReturnPath: normalizeWechatMPReturnPath(payload.ReturnPath),
}, nil }, nil
} }
@@ -533,12 +512,8 @@ func (s *channelService) signWechatMPOAuthState(payload wechatMPOAuthState, secr
if payload.ChannelID == "" || payload.ExpiresAt <= 0 { if payload.ChannelID == "" || payload.ExpiresAt <= 0 {
return "", errors.New("invalid oauth state payload") return "", errors.New("invalid oauth state payload")
} }
payload.ReturnPath = normalizeWechatMPReturnPath(payload.ReturnPath)
if len(payload.ReturnPath) > 14 {
payload.ReturnPath = "/kefu/chat/"
}
encodedPayload := base64.RawURLEncoding.EncodeToString([]byte( encodedPayload := base64.RawURLEncoding.EncodeToString([]byte(
fmt.Sprintf("%s|%d|%s", payload.ChannelID, payload.ExpiresAt, payload.ReturnPath), fmt.Sprintf("%s|%d", payload.ChannelID, payload.ExpiresAt),
)) ))
mac := hmac.New(sha256.New, []byte(secret)) mac := hmac.New(sha256.New, []byte(secret))
_, _ = mac.Write([]byte(encodedPayload)) _, _ = mac.Write([]byte(encodedPayload))
@@ -579,8 +554,8 @@ func decodeWechatMPOAuthStatePayload(raw string) (*wechatMPOAuthState, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
stateParts := strings.SplitN(string(data), "|", 3) stateParts := strings.Split(string(data), "|")
if len(stateParts) != 3 { if len(stateParts) != 2 {
return nil, errors.New("invalid oauth state payload") return nil, errors.New("invalid oauth state payload")
} }
expiresAt, err := strconv.ParseInt(stateParts[1], 10, 64) expiresAt, err := strconv.ParseInt(stateParts[1], 10, 64)
@@ -588,32 +563,16 @@ func decodeWechatMPOAuthStatePayload(raw string) (*wechatMPOAuthState, error) {
return nil, err return nil, err
} }
payload := &wechatMPOAuthState{ payload := &wechatMPOAuthState{
ChannelID: strings.TrimSpace(stateParts[0]), ChannelID: strings.TrimSpace(stateParts[0]),
ReturnPath: strings.TrimSpace(stateParts[2]), ExpiresAt: expiresAt,
ExpiresAt: expiresAt,
} }
payload.ChannelID = strings.TrimSpace(payload.ChannelID) payload.ChannelID = strings.TrimSpace(payload.ChannelID)
payload.ReturnPath = normalizeWechatMPReturnPath(payload.ReturnPath)
if payload.ChannelID == "" || payload.ExpiresAt <= 0 { if payload.ChannelID == "" || payload.ExpiresAt <= 0 {
return nil, errors.New("invalid oauth state payload") return nil, errors.New("invalid oauth state payload")
} }
return payload, nil return payload, nil
} }
func normalizeWechatMPReturnPath(returnPath string) string {
returnPath = strings.TrimSpace(returnPath)
if returnPath == "" {
return "/kefu/chat/"
}
if !strings.HasPrefix(returnPath, "/") || strings.HasPrefix(returnPath, "//") {
return "/kefu/chat/"
}
if strings.Contains(returnPath, "\n") || strings.Contains(returnPath, "\r") {
return "/kefu/chat/"
}
return returnPath
}
func buildAbsoluteURL(ctx iris.Context, path string, values url.Values) string { func buildAbsoluteURL(ctx iris.Context, path string, values url.Values) string {
scheme := ctx.GetHeader("X-Forwarded-Proto") scheme := ctx.GetHeader("X-Forwarded-Proto")
if scheme == "" { if scheme == "" {
@@ -649,5 +608,5 @@ func BuildWechatMPChatRedirectURL(ctx iris.Context, result *WechatMPOAuthResult)
if result.ExternalName != "" { if result.ExternalName != "" {
values.Set("subject", result.ExternalName) values.Set("subject", result.ExternalName)
} }
return buildAbsoluteURL(ctx, normalizeWechatMPReturnPath(result.ReturnPath), values) return buildAbsoluteURL(ctx, "/kefu/chat/", values)
} }
+185 -124
View File
@@ -60,11 +60,13 @@ type WebChannelConfig = {
width?: string width?: string
} }
type WechatMPChannelConfig = WebChannelConfig & { type WechatMPChannelConfig = {
title?: string
subtitle?: string
themeColor?: string
appId?: string appId?: string
appSecret?: string appSecret?: string
oauthScope?: "snsapi_base" | "snsapi_userinfo" oauthScope?: "snsapi_base" | "snsapi_userinfo"
oauthEnabled?: boolean
} }
const defaultWebChannelConfig: Required<WebChannelConfig> = { const defaultWebChannelConfig: Required<WebChannelConfig> = {
@@ -175,28 +177,28 @@ function parseWebChannelConfig(configJson: string): Required<WebChannelConfig> {
function parseWechatMPChannelConfig(configJson: string): Required<WechatMPChannelConfig> { function parseWechatMPChannelConfig(configJson: string): Required<WechatMPChannelConfig> {
const fallback = { const fallback = {
...defaultWebChannelConfig,
title: "公众号客服", title: "公众号客服",
subtitle: defaultWebChannelConfig.subtitle,
themeColor: defaultWebChannelConfig.themeColor,
appId: "", appId: "",
appSecret: "", appSecret: "",
oauthScope: "snsapi_base" as const, oauthScope: "snsapi_base" as const,
oauthEnabled: true,
} }
if (!configJson.trim()) { if (!configJson.trim()) {
return fallback return fallback
} }
try { try {
const parsed = JSON.parse(configJson) as WechatMPChannelConfig const parsed = JSON.parse(configJson) as WechatMPChannelConfig
const base = parseWebChannelConfig(configJson)
const oauthScope = const oauthScope =
parsed.oauthScope === "snsapi_userinfo" ? "snsapi_userinfo" : "snsapi_base" parsed.oauthScope === "snsapi_userinfo" ? "snsapi_userinfo" : "snsapi_base"
return { return {
...base,
title: parsed.title?.trim() || fallback.title, title: parsed.title?.trim() || fallback.title,
subtitle: parsed.subtitle?.trim() ?? fallback.subtitle,
themeColor:
parsed.themeColor?.trim() || defaultWebChannelConfig.themeColor,
appId: parsed.appId?.trim() || "", appId: parsed.appId?.trim() || "",
appSecret: parsed.appSecret?.trim() || "", appSecret: parsed.appSecret?.trim() || "",
oauthScope, oauthScope,
oauthEnabled: parsed.oauthEnabled ?? true,
} }
} catch { } catch {
return fallback return fallback
@@ -212,7 +214,6 @@ function buildForm(item: AdminChannel | null): EditForm {
const wechatConfig = isWechatMP const wechatConfig = isWechatMP
? parseWechatMPChannelConfig(item.configJson) ? parseWechatMPChannelConfig(item.configJson)
: null : null
const widgetConfig = wechatConfig ?? webConfig
return { return {
channelType: channelType:
item.channelType === "wxwork_kf" item.channelType === "wxwork_kf"
@@ -223,11 +224,11 @@ function buildForm(item: AdminChannel | null): EditForm {
aiAgentId: item.aiAgentId > 0 ? String(item.aiAgentId) : "", aiAgentId: item.aiAgentId > 0 ? String(item.aiAgentId) : "",
name: item.name, name: item.name,
openKfId: parseOpenKfId(item.configJson), openKfId: parseOpenKfId(item.configJson),
widgetTitle: widgetConfig.title, widgetTitle: wechatConfig?.title ?? webConfig.title,
widgetSubtitle: widgetConfig.subtitle, widgetSubtitle: wechatConfig?.subtitle ?? webConfig.subtitle,
widgetThemeColor: widgetConfig.themeColor, widgetThemeColor: wechatConfig?.themeColor ?? webConfig.themeColor,
widgetPosition: widgetConfig.position, widgetPosition: webConfig.position,
widgetWidth: widgetConfig.width, widgetWidth: webConfig.width,
wechatAppId: wechatConfig?.appId ?? "", wechatAppId: wechatConfig?.appId ?? "",
wechatAppSecret: wechatConfig?.appSecret ?? "", wechatAppSecret: wechatConfig?.appSecret ?? "",
wechatOAuthScope: wechatConfig?.oauthScope ?? "snsapi_base", wechatOAuthScope: wechatConfig?.oauthScope ?? "snsapi_base",
@@ -244,8 +245,6 @@ function buildPayload(form: EditForm, status: number): CreateAdminChannelPayload
subtitle: form.widgetSubtitle.trim(), subtitle: form.widgetSubtitle.trim(),
themeColor: themeColor:
form.widgetThemeColor.trim() || defaultWebChannelConfig.themeColor, form.widgetThemeColor.trim() || defaultWebChannelConfig.themeColor,
position: form.widgetPosition || defaultWebChannelConfig.position,
width: form.widgetWidth.trim() || defaultWebChannelConfig.width,
} }
const configJson = const configJson =
channelType === "wxwork_kf" channelType === "wxwork_kf"
@@ -256,9 +255,12 @@ function buildPayload(form: EditForm, status: number): CreateAdminChannelPayload
appId: form.wechatAppId.trim(), appId: form.wechatAppId.trim(),
appSecret: form.wechatAppSecret.trim(), appSecret: form.wechatAppSecret.trim(),
oauthScope: form.wechatOAuthScope || "snsapi_base", oauthScope: form.wechatOAuthScope || "snsapi_base",
oauthEnabled: true,
}) })
: JSON.stringify(webLikeConfig) : JSON.stringify({
...webLikeConfig,
position: form.widgetPosition || defaultWebChannelConfig.position,
width: form.widgetWidth.trim() || defaultWebChannelConfig.width,
})
return { return {
channelType, channelType,
aiAgentId: Number(form.aiAgentId), aiAgentId: Number(form.aiAgentId),
@@ -324,7 +326,6 @@ function ChannelFormBody({
} = form } = form
const channelType = useWatch({ control, name: "channelType" }) const channelType = useWatch({ control, name: "channelType" })
const openKfId = useWatch({ control, name: "openKfId" }) const openKfId = useWatch({ control, name: "openKfId" })
const isWebLikeChannel = channelType === "web" || channelType === "wechat_mp"
useEffect(() => { useEffect(() => {
async function loadAIAgents() { async function loadAIAgents() {
@@ -532,7 +533,7 @@ function ChannelFormBody({
</Field> </Field>
) : null} ) : null}
{isWebLikeChannel ? ( {channelType === "web" || channelType === "wechat_mp" ? (
<> <>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{channelType === "wechat_mp" ? ( {channelType === "wechat_mp" ? (
@@ -619,43 +620,48 @@ function ChannelFormBody({
</FieldContent> </FieldContent>
</Field> </Field>
<Field data-invalid={!!errors.widgetPosition}> {channelType === "web" ? (
<FieldLabel></FieldLabel> <>
<FieldContent> <Field data-invalid={!!errors.widgetPosition}>
<Controller <FieldLabel></FieldLabel>
control={control} <FieldContent>
name="widgetPosition" <Controller
render={({ field }) => ( control={control}
<OptionCombobox name="widgetPosition"
value={field.value} render={({ field }) => (
options={[...widgetPositionOptions]} <OptionCombobox
placeholder="请选择挂载位置" value={field.value}
searchPlaceholder="搜索挂载位置" options={[...widgetPositionOptions]}
emptyText="未找到挂载位置" placeholder="请选择挂载位置"
onChange={field.onChange} searchPlaceholder="搜索挂载位置"
emptyText="未找到挂载位置"
onChange={field.onChange}
/>
)}
/> />
)} <FieldError errors={[errors.widgetPosition]} />
/> </FieldContent>
<FieldError errors={[errors.widgetPosition]} /> </Field>
</FieldContent>
</Field>
<Field data-invalid={!!errors.widgetWidth}> <Field data-invalid={!!errors.widgetWidth}>
<FieldLabel htmlFor="channel-widget-width"></FieldLabel> <FieldLabel htmlFor="channel-widget-width"></FieldLabel>
<FieldContent> <FieldContent>
<Input <Input
id="channel-widget-width" id="channel-widget-width"
placeholder="380px" placeholder="380px"
{...register("widgetWidth")} {...register("widgetWidth")}
/> />
<FieldError errors={[errors.widgetWidth]} /> <FieldError errors={[errors.widgetWidth]} />
</FieldContent> </FieldContent>
</Field> </Field>
</>
) : null}
</div> </div>
<WebAccessGuide {channelType === "wechat_mp" ? (
channelId={channelDetail?.channelId || ""} <WechatMPAccessGuide channelId={channelDetail?.channelId || ""} />
channelType={channelType === "wechat_mp" ? "wechat_mp" : "web"} ) : (
/> <WebAccessGuide channelId={channelDetail?.channelId || ""} />
)}
</> </>
) : null} ) : null}
</div> </div>
@@ -673,15 +679,8 @@ function ChannelFormBody({
) )
} }
function WebAccessGuide({ function WebAccessGuide({ channelId }: { channelId: string }) {
channelId,
channelType,
}: {
channelId: string
channelType: "web" | "wechat_mp"
}) {
const [origin, setOrigin] = useState("") const [origin, setOrigin] = useState("")
const isWechatMP = channelType === "wechat_mp"
useEffect(() => { useEffect(() => {
setOrigin(window.location.origin) setOrigin(window.location.origin)
@@ -691,16 +690,10 @@ function WebAccessGuide({
if (!origin || !channelId) { if (!origin || !channelId) {
return "" return ""
} }
const url = new URL( const url = new URL("/kefu/chat/", origin)
isWechatMP ? "/api/channel/wechat_mp/oauth/authorize" : "/kefu/chat/",
origin
)
url.searchParams.set("channelId", channelId) url.searchParams.set("channelId", channelId)
if (isWechatMP) {
url.searchParams.set("returnPath", "/kefu/chat/")
}
return url.toString() return url.toString()
}, [channelId, isWechatMP, origin]) }, [channelId, origin])
const testUrl = useMemo(() => { const testUrl = useMemo(() => {
if (!origin || !channelId) { if (!origin || !channelId) {
@@ -717,11 +710,11 @@ function WebAccessGuide({
} }
return `<script> return `<script>
window.CSAgentConfig = { window.CSAgentConfig = {
channelId: "${channelId}"${isWechatMP ? ',\n externalSource: "wechat_mp"' : ""} channelId: "${channelId}"
}; };
</script> </script>
<script async src="${origin}/sdk/cs-ai-agent-sdk.min.js"></script>` <script async src="${origin}/sdk/cs-ai-agent-sdk.min.js"></script>`
}, [channelId, isWechatMP, origin]) }, [channelId, origin])
async function copyText(text: string, successMessage: string) { async function copyText(text: string, successMessage: string) {
if (!text) { if (!text) {
@@ -738,14 +731,10 @@ function WebAccessGuide({
return ( return (
<div className="space-y-4 border-t pt-4"> <div className="space-y-4 border-t pt-4">
<div> <div>
<div className="text-sm font-medium"> <div className="text-sm font-medium">Web </div>
{isWechatMP ? "微信公众号接入信息" : "Web 接入信息"}
</div>
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
{channelId {channelId
? isWechatMP ? "复制链接或嵌入代码即可接入当前 Web 渠道。"
? "将授权链接配置到公众号菜单,用户授权后会进入客服窗口。"
: "复制链接或嵌入代码即可接入当前 Web 渠道。"
: "保存渠道后生成接入链接。"} : "保存渠道后生成接入链接。"}
</div> </div>
</div> </div>
@@ -757,9 +746,7 @@ function WebAccessGuide({
) : ( ) : (
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground"> <div className="text-xs font-medium text-muted-foreground">访</div>
{isWechatMP ? "公众号菜单授权链接" : "直接访问链接"}
</div>
<div className="flex flex-col gap-2 sm:flex-row"> <div className="flex flex-col gap-2 sm:flex-row">
<Input readOnly value={accessUrl} className="font-mono text-xs" /> <Input readOnly value={accessUrl} className="font-mono text-xs" />
<div className="flex gap-2"> <div className="flex gap-2">
@@ -785,55 +772,129 @@ function WebAccessGuide({
</div> </div>
</div> </div>
{!isWechatMP ? ( <div className="space-y-2">
<div className="space-y-2"> <div className="flex items-center justify-between gap-2">
<div className="flex items-center justify-between gap-2"> <div className="text-xs font-medium text-muted-foreground">
<div className="text-xs font-medium text-muted-foreground">
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => copyText(snippet, "已复制接入代码")}
>
<CopyIcon className="size-4" />
</Button>
</div> </div>
<pre className="max-h-48 overflow-auto rounded-md bg-muted p-3 text-xs leading-5"> <Button
<code>{snippet}</code> type="button"
</pre> variant="outline"
size="sm"
onClick={() => copyText(snippet, "已复制接入代码")}
>
<CopyIcon className="size-4" />
</Button>
</div> </div>
) : null} <pre className="max-h-48 overflow-auto rounded-md bg-muted p-3 text-xs leading-5">
<code>{snippet}</code>
</pre>
</div>
<div className="flex flex-col gap-2 rounded-md bg-muted px-3 py-3 text-xs text-muted-foreground"> <div className="flex flex-col gap-2 rounded-md bg-muted px-3 py-3 text-xs text-muted-foreground">
<div className="font-medium text-foreground"></div> <div className="font-medium text-foreground"></div>
{isWechatMP ? ( <div>1. </div>
<> <div>2. HTML body </div>
<div>1. </div> <div>3. </div>
<div>2. </div> <div>4. 使访</div>
<div>3. openid </div> <div className="pt-1">
</> <Button
) : ( type="button"
<> variant="outline"
<div>1. </div> size="sm"
<div>2. HTML body </div> onClick={() => window.open(testUrl, "_blank", "noopener,noreferrer")}
<div>3. </div> >
<div>4. 使访</div> <ExternalLinkIcon className="size-4" />
<div className="pt-1">
<Button </Button>
type="button" </div>
variant="outline" </div>
size="sm" </div>
onClick={() => window.open(testUrl, "_blank", "noopener,noreferrer")} )}
> </div>
<ExternalLinkIcon className="size-4" /> )
}
</Button>
</div> function WechatMPAccessGuide({ channelId }: { channelId: string }) {
</> const [origin, setOrigin] = useState("")
)}
useEffect(() => {
setOrigin(window.location.origin)
}, [])
const menuUrl = useMemo(() => {
if (!origin || !channelId) {
return ""
}
const url = new URL("/api/channel/wechat_mp/oauth/authorize", origin)
url.searchParams.set("channelId", channelId)
return url.toString()
}, [channelId, origin])
async function copyText(text: string) {
if (!text) {
return
}
try {
await navigator.clipboard.writeText(text)
toast.success("已复制公众号菜单链接")
} catch {
toast.error("复制失败")
}
}
return (
<div className="space-y-4 border-t pt-4">
<div>
<div className="text-sm font-medium"></div>
<div className="text-xs text-muted-foreground">
{channelId
? "将该链接配置到微信公众号自定义菜单,用户点击菜单后进入客服聊天页。"
: "保存渠道后生成公众号菜单链接。"}
</div>
</div>
{!channelId ? (
<div className="rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground">
channelId
</div>
) : (
<div className="space-y-4">
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground">
</div>
<div className="flex flex-col gap-2 sm:flex-row">
<Input readOnly value={menuUrl} className="font-mono text-xs" />
<div className="flex gap-2">
<Button
type="button"
variant="outline"
size="icon"
title="复制链接"
onClick={() => copyText(menuUrl)}
>
<CopyIcon className="size-4" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
title="打开链接"
onClick={() => window.open(menuUrl, "_blank", "noopener,noreferrer")}
>
<ExternalLinkIcon className="size-4" />
</Button>
</div>
</div>
</div>
<div className="flex flex-col gap-2 rounded-md bg-muted px-3 py-3 text-xs text-muted-foreground">
<div className="font-medium text-foreground"></div>
<div>1. </div>
<div>2. </div>
<div>3. openid </div>
</div> </div>
</div> </div>
)} )}