This commit is contained in:
Mrx
2026-02-28 17:41:30 +08:00
parent fd229f0d59
commit c4cc15f853
3 changed files with 44 additions and 2 deletions

View File

@@ -1,7 +1,9 @@
package captcha
import (
"context"
"os"
"strings"
"github.com/pkg/errors"
@@ -19,10 +21,23 @@ type Config struct {
SceneID string
}
// Verify 验证图形验证码,支持微信环境跳过验证
func Verify(cfg Config, captchaVerifyParam string) error {
return VerifyWithContext(context.Background(), cfg, captchaVerifyParam)
}
// VerifyWithContext 带上下文的验证函数
func VerifyWithContext(ctx context.Context, cfg Config, captchaVerifyParam string) error {
// 开发环境直接通过
if os.Getenv("ENV") == "development" {
return nil
}
// 检查是否为微信环境
if isWechatEnvironment(ctx) {
return nil
}
if captchaVerifyParam == "" {
return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "empty captchaVerifyParam")
}
@@ -50,3 +65,26 @@ func Verify(cfg Config, captchaVerifyParam string) error {
}
return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "verifyResult=false")
}
// isWechatEnvironment 检查是否为微信环境
func isWechatEnvironment(ctx context.Context) bool {
// 从上下文中获取请求头
userAgent := ""
if val := ctx.Value("user-agent"); val != nil {
if ua, ok := val.(string); ok {
userAgent = ua
}
}
if val := ctx.Value("User-Agent"); val != nil {
if ua, ok := val.(string); ok {
userAgent = ua
}
}
// 检查User-Agent是否包含微信标识
if strings.Contains(strings.ToLower(userAgent), "micromessenger") {
return true
}
return false
}