Skip to content

Commit

Permalink
feat: 增加 重定向功能
Browse files Browse the repository at this point in the history
  • Loading branch information
CaoMeiYouRen committed Oct 1, 2024
1 parent 8704ec9 commit 3aaa826
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 10 deletions.
4 changes: 4 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ LOGFILES=false
# BASE_URL='http://localhost:3000'
BASE_URL=''

# 重定向地址,如果本云函数未处理请求,则重定向到该地址
# REDIRECT_URL='http://localhost:4000'
REDIRECT_URL=''

# 微信公众号相关配置
WX_TOKEN=''
WX_APP_ID=''
Expand Down
3 changes: 3 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ export const ADMIN_KEY = process.env.ADMIN_KEY || ''

// 基础路径
export const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`

// 重定向地址
export const REDIRECT_URL = process.env.REDIRECT_URL || ''
11 changes: 10 additions & 1 deletion src/routes/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { to } from 'await-to-js'
import { sha1, toCamelCase, xml2json } from '@/utils/helper'
import { WX_TOKEN } from '@/env'
import { REDIRECT_URL, WX_TOKEN } from '@/env'
import winstonLogger from '@/utils/logger'
import { WechatEventBody } from '@/interfaces/wechat-event-body'
import { handleEvent } from '@/services/event'
Expand Down Expand Up @@ -55,6 +55,15 @@ app.post('/', async (c) => {
const response = await handleEvent(body)

winstonLogger.isDebugEnabled() && winstonLogger.debug(`Response: \n${response}`)

if (response === 'redirect') { // 本云函数未处理请求,则重定向到该地址
if (REDIRECT_URL) {
const searchParams = new URLSearchParams(query)
return c.redirect(`${REDIRECT_URL}?${searchParams}`, 307)
}
c.header('Content-Type', 'text/xml')
return c.text('success', 200)
}
c.header('Content-Type', 'text/xml')
return c.text(response, 200)
})
Expand Down
11 changes: 2 additions & 9 deletions src/services/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,8 @@ export async function handleEvent(body: IWechatEventBody) {
content: respContent,
})
}
// 否则复读
// TODO 如果未匹配到关键词,则转发请求到下一个服务器
const respContent = `您发送的消息是:${content}`
return replyMessage({
toUserName: fromUserName,
fromUserName: toUserName,
msgType: 'text',
content: respContent,
})
// 未匹配到关键词,则转发请求到下一个服务器
return 'redirect'
}
case 'image': { // 图片消息
const { mediaId } = body
Expand Down

0 comments on commit 3aaa826

Please sign in to comment.