更新密码找回uniapp
This commit is contained in:
1 parent
7f9a66da0f
commit
3fdda89833
1304 files changed
+3503
-26132
No files matched your search
@@ -17,18 +17,12 @@ import (
|
||||
"github.com/beego/beego/v2/core/logs"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 微信公众平台服务端 API 调用(access_token / 带参二维码 / 模板消息 / 订阅通知 / 用户信息)
|
||||
// =============================================================
|
||||
|
||||
const apiBase = "https://api.weixin.qq.com"
|
||||
|
||||
var httpClient = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
// APIError 微信接口业务错误(HTTP 200 但 errcode 非 0)。
|
||||
// Error() 输出保留 errcode / errmsg 原始信息,便于日志检索与前端展示。
|
||||
type APIError struct {
|
||||
API string // 调用的接口(如「获取 access_token」)
|
||||
API string
|
||||
Code int
|
||||
Msg string
|
||||
}
|
||||
@@ -37,7 +31,6 @@ func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("%s 失败:errcode=%d errmsg=%s", e.API, e.Code, e.Msg)
|
||||
}
|
||||
|
||||
// Explain 返回常见 errcode 的中文排查建议;未知错误码返回空串。
|
||||
func (e *APIError) Explain() string {
|
||||
switch e.Code {
|
||||
case 40013:
|
||||
@@ -54,24 +47,18 @@ func (e *APIError) Explain() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// ============================ 出口 IP 探测(40164 IP 白名单排查用) ============================
|
||||
|
||||
var (
|
||||
outboundIPMu sync.Mutex
|
||||
outboundIPCache string
|
||||
outboundIPAt time.Time
|
||||
)
|
||||
|
||||
// outboundIPTTL 出口 IP 缓存时长(探测失败也按此负缓存,避免每次请求都外网探测)
|
||||
const outboundIPTTL = 5 * time.Minute
|
||||
|
||||
// ipDetectServices 出口 IP 探测服务,按顺序尝试,任一返回 IPv4 即采用
|
||||
var ipDetectServices = []string{"https://ifconfig.me/ip", "https://api.ipify.org", "https://myip.ipip.net"}
|
||||
|
||||
var ipv4Re = regexp.MustCompile(`\d{1,3}(?:\.\d{1,3}){3}`)
|
||||
|
||||
// OutboundIP 返回本服务器访问公网时的出口 IP(微信后台「IP白名单」需填入该 IP)。
|
||||
// 结果内存缓存 5 分钟;服务器无法访问探测服务时返回空串,不影响主流程。
|
||||
func OutboundIP() string {
|
||||
outboundIPMu.Lock()
|
||||
if time.Since(outboundIPAt) < outboundIPTTL {
|
||||
@@ -108,7 +95,6 @@ func detectOutboundIP() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// firstIPv4 取文本中第一个合法 IPv4(形如 1.2.3.4),无则返回空串。
|
||||
func firstIPv4(s string) string {
|
||||
m := ipv4Re.FindString(s)
|
||||
if m == "" || net.ParseIP(m) == nil {
|
||||
@@ -117,7 +103,6 @@ func firstIPv4(s string) string {
|
||||
return m
|
||||
}
|
||||
|
||||
// ErrMsgIPs 从微信 errmsg 中提取 IP(如 "invalid ip 1.2.3.4 ipv6 ::ffff:1.2.3.4")。
|
||||
func ErrMsgIPs(errmsg string) []string {
|
||||
var out []string
|
||||
seen := make(map[string]bool)
|
||||
@@ -131,9 +116,6 @@ func ErrMsgIPs(errmsg string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// logAPIError 记录微信接口错误详情:
|
||||
// errcode / errmsg / 微信提示的 IP / 本服务器出口 IP / 排查建议只落服务端日志。
|
||||
// 注册页、登录页等匿名可访问页面不应回显这些信息(暴露服务器出口 IP 与内部错误)。
|
||||
func logAPIError(scene string, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
@@ -154,7 +136,6 @@ func logAPIError(scene string, err error) {
|
||||
logs.Warning("[wechat-mp] %s 失败:%s", scene, detail)
|
||||
}
|
||||
|
||||
// ExplainError 提取微信接口错误的中文排查建议;无可用建议时返回 ("", false)。
|
||||
func ExplainError(err error) (string, bool) {
|
||||
var ae *APIError
|
||||
if errors.As(err, &ae) {
|
||||
@@ -165,7 +146,6 @@ func ExplainError(err error) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 access_token(内存缓存,提前 5 分钟刷新)
|
||||
func GetAccessToken(cfg *Config) (string, error) {
|
||||
if cfg == nil || cfg.AppID == "" || cfg.AppSecret == "" {
|
||||
return "", fmt.Errorf("AppID / AppSecret 未配置")
|
||||
@@ -204,8 +184,6 @@ func GetAccessToken(cfg *Config) (string, error) {
|
||||
return resp.AccessToken, nil
|
||||
}
|
||||
|
||||
// CreateQRCode 创建带参数临时二维码(字符串场景值),返回二维码图片地址。
|
||||
// scene 会通过「关注事件的 EventKey(qrscene_<scene>)/ 扫码事件的 EventKey(<scene>)」回传。
|
||||
func CreateQRCode(cfg *Config, scene string, expireSeconds int) (string, error) {
|
||||
token, err := GetAccessToken(cfg)
|
||||
if err != nil {
|
||||
@@ -240,8 +218,6 @@ func CreateQRCode(cfg *Config, scene string, expireSeconds int) (string, error)
|
||||
return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + url.QueryEscape(resp.Ticket), nil
|
||||
}
|
||||
|
||||
// SendTemplateMessage 发送模板消息(需认证服务号 + 模板ID)
|
||||
// data 键为模板字段名(first / keyword1 / remark ...),值为文本内容。
|
||||
func SendTemplateMessage(cfg *Config, openid, jumpURL string, data map[string]string) error {
|
||||
if cfg.TemplateID == "" {
|
||||
return fmt.Errorf("未配置模板消息 ID(认证后在公众号后台申请)")
|
||||
@@ -277,7 +253,6 @@ func SendTemplateMessage(cfg *Config, openid, jumpURL string, data map[string]st
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendSubscribeMessage 发送订阅通知(一次性订阅,需用户先在页面完成订阅授权)
|
||||
func SendSubscribeMessage(cfg *Config, openid, templateID, page string, data map[string]string) error {
|
||||
if templateID == "" {
|
||||
return fmt.Errorf("未配置订阅通知模板 ID")
|
||||
@@ -312,7 +287,6 @@ func SendSubscribeMessage(cfg *Config, openid, templateID, page string, data map
|
||||
return nil
|
||||
}
|
||||
|
||||
// UserInfo 用户基本信息(昵称/头像等;未认证公众号可能接口受限,调用失败由上层忽略)
|
||||
type UserInfo struct {
|
||||
OpenID string `json:"openid"`
|
||||
Nickname string `json:"nickname"`
|
||||
@@ -324,7 +298,6 @@ type UserInfo struct {
|
||||
Subscribe int `json:"subscribe"`
|
||||
}
|
||||
|
||||
// FetchUserInfo 拉取用户基本信息(失败不算错,由调用方容错)
|
||||
func FetchUserInfo(cfg *Config, openid string) (*UserInfo, error) {
|
||||
token, err := GetAccessToken(cfg)
|
||||
if err != nil {
|
||||
@@ -346,8 +319,6 @@ func FetchUserInfo(cfg *Config, openid string) (*UserInfo, error) {
|
||||
return &resp.UserInfo, nil
|
||||
}
|
||||
|
||||
// ============================ HTTP 辅助 ============================
|
||||
|
||||
func httpGetJSON(api string, out interface{}) error {
|
||||
resp, err := httpClient.Get(api)
|
||||
if err != nil {
|
||||
|
||||
@@ -14,12 +14,6 @@ import (
|
||||
"github.com/beego/beego/v2/client/orm"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 关注绑定:扫码关注 → 公众号被动回复验证码 → 平台核销完成绑定
|
||||
// 一个绑定会话 = 一条 yz_platform_wechat_mp_verify_code(scene + 6位验证码 + 过期时间)
|
||||
// =============================================================
|
||||
|
||||
// DefaultVerifyTTL 验证码默认有效期
|
||||
const DefaultVerifyTTL = 5 * time.Minute
|
||||
|
||||
var (
|
||||
@@ -30,8 +24,6 @@ var (
|
||||
ErrSceneInvalid = errors.New("二维码无效或已失效")
|
||||
)
|
||||
|
||||
// CreateVerifyCode 创建绑定会话并生成带参二维码。
|
||||
// bindType 为 platform_user / tenant_user,bindID 为发起方用户 ID。
|
||||
func CreateVerifyCode(bindType string, bindID, bindTid uint64, ttl time.Duration) (scene, code, qrURL string, expireAt time.Time, err error) {
|
||||
cfg, err := LoadEnabledConfig()
|
||||
if err != nil {
|
||||
@@ -67,7 +59,6 @@ func CreateVerifyCode(bindType string, bindID, bindTid uint64, ttl time.Duration
|
||||
return scene, code, qrURL, expireAt, nil
|
||||
}
|
||||
|
||||
// GetVerifyCode 按 scene 查询绑定会话(过期时惰性标记)
|
||||
func GetVerifyCode(scene string) (*models.WechatMpVerifyCode, error) {
|
||||
scene = strings.TrimSpace(scene)
|
||||
if scene == "" {
|
||||
@@ -87,7 +78,6 @@ func GetVerifyCode(scene string) (*models.WechatMpVerifyCode, error) {
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// ConfirmVerifyCode 核销验证码并完成绑定,返回粉丝记录
|
||||
func ConfirmVerifyCode(bindType string, bindID, bindTid uint64, scene, code string) (*models.WechatMpFollower, error) {
|
||||
row, err := GetVerifyCode(scene)
|
||||
if err != nil {
|
||||
@@ -105,8 +95,6 @@ func ConfirmVerifyCode(bindType string, bindID, bindTid uint64, scene, code stri
|
||||
return nil, ErrCodeExpired
|
||||
}
|
||||
if strings.TrimSpace(code) != row.Code {
|
||||
// 验证码不属于该二维码会话(用户在公众号内单独发送「验证码」取得):
|
||||
// 回退按验证码认领,保证「不扫码直接取码」的绑定路径可用
|
||||
return ConfirmVerifyCodeByCode(bindType, bindID, bindTid, code)
|
||||
}
|
||||
now := time.Now()
|
||||
@@ -118,9 +106,6 @@ func ConfirmVerifyCode(bindType string, bindID, bindTid uint64, scene, code stri
|
||||
return BindFollower(row.OpenID, bindType, bindID, bindTid)
|
||||
}
|
||||
|
||||
// CreateOpenIDVerify 由公众号消息发起绑定会话:openid 已知(消息发送者),
|
||||
// 绑定目标(bind_type/bind_id)为空,待系统页面登录用户输入验证码后认领。
|
||||
// 与扫码会话共用一张表,区别仅在发起方与归属信息。
|
||||
func CreateOpenIDVerify(openid string, ttl time.Duration) (*models.WechatMpVerifyCode, error) {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -135,7 +120,7 @@ func CreateOpenIDVerify(openid string, ttl time.Duration) (*models.WechatMpVerif
|
||||
Scene: randomScene(),
|
||||
Code: randomCode6(),
|
||||
OpenID: openid,
|
||||
Status: models.WechatVerifyStatusScanned, // 微信号已知,等同「已扫码待核销」
|
||||
Status: models.WechatVerifyStatusScanned,
|
||||
ExpireAt: &expireAt,
|
||||
CreateTime: now,
|
||||
UpdateTime: &now,
|
||||
@@ -146,9 +131,6 @@ func CreateOpenIDVerify(openid string, ttl time.Duration) (*models.WechatMpVerif
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// ConfirmVerifyCodeByCode 按验证码认领「公众号发起」的绑定会话(系统页面未展示二维码时使用):
|
||||
// 匹配最近一条 bind_id=0、openid 非空、未核销、未过期的会话,用 CAS 更新占位后绑定到当前账号。
|
||||
// 只认领无归属的会话,不会影响他人扫码发起的会话,避免绑定串号。
|
||||
func ConfirmVerifyCodeByCode(bindType string, bindID, bindTid uint64, code string) (*models.WechatMpFollower, error) {
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
@@ -170,7 +152,6 @@ func ConfirmVerifyCodeByCode(bindType string, bindID, bindTid uint64, code strin
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
// CAS:仅当仍是「待核销」时更新,避免同一验证码被并发认领
|
||||
affected, uerr := models.Orm.QueryTable(new(models.WechatMpVerifyCode)).
|
||||
Filter("id", row.ID).
|
||||
Filter("status", models.WechatVerifyStatusScanned).
|
||||
@@ -190,8 +171,6 @@ func ConfirmVerifyCodeByCode(bindType string, bindID, bindTid uint64, code strin
|
||||
return BindFollower(row.OpenID, bindType, bindID, bindTid)
|
||||
}
|
||||
|
||||
// BindFollower 将 openid 绑定到指定账号。
|
||||
// 同一账号只保留一个微信:旧的 openid 绑定关系会被清除。
|
||||
func BindFollower(openid, bindType string, bindID, bindTid uint64) (*models.WechatMpFollower, error) {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -236,7 +215,6 @@ func BindFollower(openid, bindType string, bindID, bindTid uint64) (*models.Wech
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// UnbindByUser 清除某账号的微信绑定(按绑定对象维度)
|
||||
func UnbindByUser(bindType string, bindID uint64) error {
|
||||
if bindID == 0 {
|
||||
return nil
|
||||
@@ -251,7 +229,6 @@ func UnbindByUser(bindType string, bindID uint64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// GetFollowerByUser 查询某账号已绑定的粉丝记录(未绑定返回 nil, nil)
|
||||
func GetFollowerByUser(bindType string, bindID uint64) (*models.WechatMpFollower, error) {
|
||||
if bindID == 0 {
|
||||
return nil, nil
|
||||
@@ -272,7 +249,6 @@ func GetFollowerByUser(bindType string, bindID uint64) (*models.WechatMpFollower
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// GetFollowerByOpenID 按 openid 查询粉丝记录(不存在返回 nil, nil)
|
||||
func GetFollowerByOpenID(openid string) (*models.WechatMpFollower, error) {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -289,9 +265,6 @@ func GetFollowerByOpenID(openid string) (*models.WechatMpFollower, error) {
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// LatestPendingVerifyByOpenID 查询该微信号最近一条「未核销且未过期」的绑定会话,用于重发验证码。
|
||||
// 命中范围:扫码会话(扫码时写入 openid)与公众号内发起的待认领会话(创建即带 openid)。
|
||||
// 他人发起的、尚未扫码的会话 openid 为空,不会被命中,避免绑定串号。
|
||||
func LatestPendingVerifyByOpenID(openid string) (*models.WechatMpVerifyCode, error) {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -313,7 +286,6 @@ func LatestPendingVerifyByOpenID(openid string) (*models.WechatMpVerifyCode, err
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// UpsertSubscribe 关注事件:创建/恢复粉丝记录
|
||||
func UpsertSubscribe(openid string, at time.Time) (*models.WechatMpFollower, error) {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -343,7 +315,6 @@ func UpsertSubscribe(openid string, at time.Time) (*models.WechatMpFollower, err
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// MarkUnsubscribe 取关事件
|
||||
func MarkUnsubscribe(openid string, at time.Time) error {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -357,7 +328,6 @@ func MarkUnsubscribe(openid string, at time.Time) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// RefreshFollowerProfile 尝试拉取粉丝昵称/头像(未认证公众号可能受限,失败静默忽略)
|
||||
func RefreshFollowerProfile(cfg *Config, openid string) {
|
||||
if cfg == nil || openid == "" {
|
||||
return
|
||||
@@ -383,7 +353,6 @@ func RefreshFollowerProfile(cfg *Config, openid string) {
|
||||
_, _ = models.Orm.QueryTable(new(models.WechatMpFollower)).Filter("openid", openid).Update(up)
|
||||
}
|
||||
|
||||
// HandleInbound 处理入站消息/事件,返回需要被动回复的文本(空字符串表示不回复)
|
||||
func HandleInbound(cfg *Config, msg *InboundMessage) string {
|
||||
if msg == nil {
|
||||
return ""
|
||||
@@ -398,13 +367,11 @@ func HandleInbound(cfg *Config, msg *InboundMessage) string {
|
||||
_, _ = UpsertSubscribe(openid, now)
|
||||
scene := strings.TrimPrefix(strings.TrimSpace(msg.EventKey), "qrscene_")
|
||||
if scene != "" {
|
||||
// 带参二维码:先看是否为扫码登录会话(自动回复确认链接)
|
||||
if reply, ok := HandleScanLoginEvent(scene, openid); ok {
|
||||
return reply
|
||||
}
|
||||
return handleScanScene(cfg, scene, openid)
|
||||
}
|
||||
// 普通关注:已绑定直接给「确认登录」链接,未绑定提示先绑定
|
||||
return DirectLoginReply(openid)
|
||||
case "scan":
|
||||
scene := strings.TrimSpace(msg.EventKey)
|
||||
@@ -416,7 +383,6 @@ func HandleInbound(cfg *Config, msg *InboundMessage) string {
|
||||
_ = MarkUnsubscribe(openid, now)
|
||||
return ""
|
||||
case "click":
|
||||
// 自定义菜单点击:键值为登录入口时直接回复确认登录链接
|
||||
if isLoginMenuKey(msg.EventKey) {
|
||||
return DirectLoginReply(openid)
|
||||
}
|
||||
@@ -428,17 +394,11 @@ func HandleInbound(cfg *Config, msg *InboundMessage) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// handleTextIntent 处理公众号文本消息:
|
||||
// - 发送「登录」:已绑定用户获取一次性登录链接(见 login.go);
|
||||
// - 发送「验证码」等关键词:返回该微信号的验证码(复用未核销会话;没有则在公众号侧
|
||||
// 新建「待认领」会话),用户回系统页面输入即完成绑定,无需先扫码;
|
||||
// - 其余文本:给出绑定引导。
|
||||
func handleTextIntent(openid, content string) string {
|
||||
text := strings.TrimSpace(content)
|
||||
if isLoginKeyword(text) {
|
||||
return DirectLoginReply(openid)
|
||||
}
|
||||
// 「注册」:注册页账号注册方式取码(无二维码兜底路径)
|
||||
if isRegisterKeyword(text) {
|
||||
row, err := LatestPendingRegisterVerifyByOpenID(openid)
|
||||
if err != nil || row == nil {
|
||||
@@ -458,10 +418,8 @@ func handleTextIntent(openid, content string) string {
|
||||
if !isBindKeyword(text) {
|
||||
return textBindGuide()
|
||||
}
|
||||
// 1) 复用该微信号未核销、未过期的会话(扫码会话或此前公众号发起的会话)
|
||||
row, err := LatestPendingVerifyByOpenID(openid)
|
||||
if err != nil || row == nil {
|
||||
// 2) 公众号侧直接发起:新建待认领会话,绑定目标由系统页面登录用户输入验证码后认领
|
||||
row, err = CreateOpenIDVerify(openid, 0)
|
||||
if err != nil {
|
||||
return "系统繁忙,请稍后重新发送。"
|
||||
@@ -480,12 +438,10 @@ func handleTextIntent(openid, content string) string {
|
||||
return fmt.Sprintf("您的验证码是:%s\n请在系统页面「绑定微信」处输入完成绑定(%d 分钟内有效)。%s", row.Code, minutes, tip)
|
||||
}
|
||||
|
||||
// isRegisterKeyword 判断文本是否为「注册」意图(注册页账号注册取码)
|
||||
func isRegisterKeyword(text string) bool {
|
||||
return text == "注册" || strings.Contains(text, "注册")
|
||||
}
|
||||
|
||||
// isBindKeyword 判断文本是否为「获取验证码 / 绑定」类意图
|
||||
func isBindKeyword(text string) bool {
|
||||
if text == "" {
|
||||
return false
|
||||
@@ -497,13 +453,11 @@ func isBindKeyword(text string) bool {
|
||||
return strings.Contains(text, "验证码")
|
||||
}
|
||||
|
||||
// textBindGuide 非关键词文本的绑定引导
|
||||
func textBindGuide() string {
|
||||
return "如需绑定账号:请在系统页面点击「绑定微信」,然后直接在本公众号发送「验证码」," +
|
||||
"收到 6 位验证码后回到系统页面输入即可完成绑定。\n绑定后在本公众号发送「登录」可获取一次性登录链接。"
|
||||
}
|
||||
|
||||
// BindGuides 系统页面「绑定微信」卡片的操作指引(未认证公众号无带参二维码,仅引导发码取码)
|
||||
func BindGuides() []string {
|
||||
return []string{
|
||||
"① 用微信扫码关注本公众号(或微信搜索公众号名称进入会话)",
|
||||
@@ -512,7 +466,6 @@ func BindGuides() []string {
|
||||
}
|
||||
}
|
||||
|
||||
// handleScanScene 扫码(关注/已关注)后的统一处理:写入验证码会话 + 回复验证码
|
||||
func handleScanScene(cfg *Config, scene, openid string) string {
|
||||
if strings.TrimSpace(scene) == "" {
|
||||
return "未能识别二维码信息,请在系统页面重新获取二维码后再扫码。"
|
||||
@@ -536,7 +489,6 @@ func handleScanScene(cfg *Config, scene, openid string) string {
|
||||
}); uerr != nil {
|
||||
return "系统繁忙,请稍后重新扫码。"
|
||||
}
|
||||
// 拉取昵称头像(失败不影响绑定流程)
|
||||
RefreshFollowerProfile(cfg, openid)
|
||||
|
||||
minutes := int(time.Until(*row.ExpireAt).Minutes())
|
||||
@@ -546,8 +498,6 @@ func handleScanScene(cfg *Config, scene, openid string) string {
|
||||
return fmt.Sprintf("您的验证码是:%s\n请回到系统页面输入完成绑定(%d 分钟内有效)。", row.Code, minutes)
|
||||
}
|
||||
|
||||
// ============================ 随机值 ============================
|
||||
|
||||
func randomScene() string {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
|
||||
@@ -12,37 +12,29 @@ import (
|
||||
beego "github.com/beego/beego/v2/server/web"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 微信公众号(服务号)配置与 access_token
|
||||
// =============================================================
|
||||
|
||||
// 消息加解密方式
|
||||
const (
|
||||
EncryptModePlain = "plain" // 明文模式
|
||||
EncryptModeCompatible = "compatible" // 兼容模式
|
||||
EncryptModeSafe = "safe" // 安全模式
|
||||
EncryptModePlain = "plain"
|
||||
EncryptModeCompatible = "compatible"
|
||||
EncryptModeSafe = "safe"
|
||||
)
|
||||
|
||||
// Config 服务号运行配置(敏感字段已解密)
|
||||
type Config struct {
|
||||
ID uint64
|
||||
AppID string
|
||||
AppSecret string // 明文
|
||||
AppSecret string
|
||||
Token string
|
||||
AESKey string // 明文(43 位 EncodingAESKey)
|
||||
AESKey string
|
||||
EncryptMode string
|
||||
TemplateID string
|
||||
Verified bool
|
||||
Enabled bool
|
||||
Remark string
|
||||
|
||||
FollowQrcode string // 关注二维码(data URL),绑定页展示供扫码关注
|
||||
FollowQrcode string
|
||||
}
|
||||
|
||||
// ErrNotConfigured 未配置或未启用
|
||||
var ErrNotConfigured = errors.New("微信公众号未配置或未启用")
|
||||
|
||||
// LoadConfig 读取服务号配置(单行,敏感字段解密);未配置返回 ErrNotConfigured
|
||||
func LoadConfig() (*Config, error) {
|
||||
var row models.WechatMpConfig
|
||||
err := models.Orm.QueryTable(new(models.WechatMpConfig)).OrderBy("id").One(&row)
|
||||
@@ -83,7 +75,6 @@ func LoadConfig() (*Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadEnabledConfig 读取并校验启用状态
|
||||
func LoadEnabledConfig() (*Config, error) {
|
||||
cfg, err := LoadConfig()
|
||||
if err != nil {
|
||||
@@ -95,12 +86,11 @@ func LoadEnabledConfig() (*Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// SaveInput 保存配置入参(敏感字段支持掩码表示不改)
|
||||
type SaveInput struct {
|
||||
AppID string
|
||||
AppSecret string // 掩码 / 空串 = 保持不变
|
||||
AppSecret string
|
||||
Token string
|
||||
AESKey string // 掩码 / 空串 = 保持不变
|
||||
AESKey string
|
||||
EncryptMode string
|
||||
TemplateID string
|
||||
Verified bool
|
||||
@@ -108,7 +98,6 @@ type SaveInput struct {
|
||||
Remark string
|
||||
}
|
||||
|
||||
// SaveConfig 保存服务号配置(不存在则创建)
|
||||
func SaveConfig(in SaveInput) error {
|
||||
if strings.TrimSpace(in.AppID) == "" {
|
||||
return errors.New("AppID 不能为空")
|
||||
@@ -130,7 +119,6 @@ func SaveConfig(in SaveInput) error {
|
||||
row = models.WechatMpConfig{}
|
||||
}
|
||||
|
||||
// 敏感字段:掩码/空串表示保持原值
|
||||
secret := strings.TrimSpace(in.AppSecret)
|
||||
if secret != "" && !IsMasked(secret) {
|
||||
enc, eerr := EncryptSecret(secret)
|
||||
@@ -174,7 +162,6 @@ func SaveConfig(in SaveInput) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// SaveFollowQrcode 保存/清空关注二维码(data URL,空串表示删除)
|
||||
func SaveFollowQrcode(dataURL string) error {
|
||||
dataURL = strings.TrimSpace(dataURL)
|
||||
now := time.Now()
|
||||
@@ -182,7 +169,6 @@ func SaveFollowQrcode(dataURL string) error {
|
||||
err := models.Orm.QueryTable(new(models.WechatMpConfig)).OrderBy("id").One(&row)
|
||||
if err != nil {
|
||||
if err == orm.ErrNoRows {
|
||||
// 尚无配置行:仅存二维码,其余字段留空
|
||||
row = models.WechatMpConfig{FollowQrcode: dataURL, EncryptMode: EncryptModePlain, CreateTime: now}
|
||||
_, err = models.Orm.Insert(&row)
|
||||
return err
|
||||
@@ -195,7 +181,6 @@ func SaveFollowQrcode(dataURL string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// FollowQrcodeURL 读取关注二维码(未配置时返回空串)
|
||||
func FollowQrcodeURL() string {
|
||||
cfg, err := LoadConfig()
|
||||
if err != nil {
|
||||
@@ -204,8 +189,6 @@ func FollowQrcodeURL() string {
|
||||
return cfg.FollowQrcode
|
||||
}
|
||||
|
||||
// CallbackURL 微信服务器回调地址(供公众号后台「服务器配置」填写)。
|
||||
// 优先读取 app.conf 的 wechat_mp_callback_base,其次回落 payment_callback_base(同为对外 API 域名)。
|
||||
func CallbackURL() string {
|
||||
base, _ := beego.AppConfig.String("wechat_mp_callback_base")
|
||||
if strings.TrimSpace(base) == "" {
|
||||
@@ -218,8 +201,6 @@ func CallbackURL() string {
|
||||
return base + "/api/wechat/mp/callback"
|
||||
}
|
||||
|
||||
// ============================ access_token 缓存 ============================
|
||||
|
||||
type tokenEntry struct {
|
||||
appID string
|
||||
token string
|
||||
@@ -232,7 +213,6 @@ var (
|
||||
tokenMinTTL = 5 * time.Minute
|
||||
)
|
||||
|
||||
// resetTokenCacheForTest 仅供测试清理缓存
|
||||
func resetTokenCacheForTest() {
|
||||
tokenMu.Lock()
|
||||
defer tokenMu.Unlock()
|
||||
|
||||
@@ -13,16 +13,6 @@ import (
|
||||
beego "github.com/beego/beego/v2/server/web"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 微信公众号敏感字段(AppSecret / EncodingAESKey)的对称加密与掩码
|
||||
//
|
||||
// yz_platform_wechat_mp_config.app_secret / aes_key 以 AES-256-GCM 加密后存储,
|
||||
// 格式:base64( "YZW1:" + nonce + ciphertext )。
|
||||
// 密钥来源:app.conf 的 wechat_mp_secret_key(任意长度字符串,内部做 SHA-256 派生);
|
||||
// 未配置时退回内置兜底密钥(保证开箱可用),上线前建议在 app.conf 配置该值。
|
||||
// 注意:更换密钥后,历史密文将无法解密,需要重新保存一次配置。
|
||||
// =============================================================
|
||||
|
||||
const (
|
||||
cipherPrefix = "YZW1:"
|
||||
fallbackSecretKey = "yunzer_wechat_mp_default_secret_key_v1"
|
||||
@@ -37,7 +27,6 @@ func configKey() []byte {
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// EncryptSecret 加密敏感字段;空串原样返回
|
||||
func EncryptSecret(plain string) (string, error) {
|
||||
if plain == "" {
|
||||
return "", nil
|
||||
@@ -60,7 +49,6 @@ func EncryptSecret(plain string) (string, error) {
|
||||
return base64.StdEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// DecryptSecret 解密敏感字段;空串原样返回
|
||||
func DecryptSecret(encoded string) (string, error) {
|
||||
if encoded == "" {
|
||||
return "", nil
|
||||
@@ -89,7 +77,6 @@ func DecryptSecret(encoded string) (string, error) {
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
// MaskSecret 生成掩码:保留末 4 位
|
||||
func MaskSecret(v string) string {
|
||||
if v == "" {
|
||||
return ""
|
||||
@@ -100,7 +87,6 @@ func MaskSecret(v string) string {
|
||||
return "******" + v[len(v)-4:]
|
||||
}
|
||||
|
||||
// IsMasked 判断前端回传的值是否仍是掩码(表示「不修改原值」)
|
||||
func IsMasked(v string) bool {
|
||||
return strings.HasPrefix(v, "******")
|
||||
}
|
||||
@@ -13,15 +13,6 @@ import (
|
||||
beego "github.com/beego/beego/v2/server/web"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 公众号微信登录(免认证方案):
|
||||
// 用户在公众号内发送「登录」→ 后端校验绑定关系并生成一次性登录令牌 →
|
||||
// 被动回复登录链接 → 用户在微信内打开链接 → 前端 /mp-login 页面
|
||||
// 用令牌调用 /api/wechat/mp/login 换取正式登录态。
|
||||
// 未认证公众号无法使用网页授权(snsapi_*),一次性链接是替代方案。
|
||||
// =============================================================
|
||||
|
||||
// DefaultLoginTokenTTL 登录令牌默认有效期
|
||||
const DefaultLoginTokenTTL = 5 * time.Minute
|
||||
|
||||
var (
|
||||
@@ -38,10 +29,6 @@ func randomTokenHex(nBytes int) string {
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// LoginLinkURL 由一次性令牌拼出前端登录页链接。
|
||||
// 页面基址读取 app.conf 的 wechat_mp_login_base(前端应用对外可访问地址,
|
||||
// 如 https://back.yunzer.cn),缺省回落 wechat_mp_callback_base / payment_callback_base。
|
||||
// 未配置时返回空串,由调用方给出提示。
|
||||
func LoginLinkURL(token string) string {
|
||||
base, _ := beego.AppConfig.String("wechat_mp_login_base")
|
||||
if strings.TrimSpace(base) == "" {
|
||||
@@ -57,7 +44,6 @@ func LoginLinkURL(token string) string {
|
||||
return base + "/#/mp-login?token=" + url.QueryEscape(token)
|
||||
}
|
||||
|
||||
// CreateLoginToken 为已绑定的粉丝生成一次性登录令牌。
|
||||
func CreateLoginToken(f *models.WechatMpFollower, ttl time.Duration) (token string, expireAt time.Time, err error) {
|
||||
if f == nil || strings.TrimSpace(f.BindType) == "" || f.BindID == 0 {
|
||||
return "", time.Time{}, errors.New("该微信尚未绑定账号")
|
||||
@@ -86,7 +72,6 @@ func CreateLoginToken(f *models.WechatMpFollower, ttl time.Duration) (token stri
|
||||
return token, expireAt, nil
|
||||
}
|
||||
|
||||
// ConsumeLoginToken 核销一次性登录令牌(CAS 防重放),返回令牌携带的绑定信息。
|
||||
func ConsumeLoginToken(token string) (*models.WechatMpLoginToken, error) {
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" {
|
||||
@@ -117,7 +102,6 @@ func ConsumeLoginToken(token string) (*models.WechatMpLoginToken, error) {
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// isLoginKeyword 判断文本是否为「登录」意图
|
||||
func isLoginKeyword(text string) bool {
|
||||
switch strings.TrimSpace(text) {
|
||||
case "登录", "登陸", "login", "Login", "微信登录", "微信登陆":
|
||||
@@ -126,9 +110,6 @@ func isLoginKeyword(text string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// isLoginMenuKey 判断自定义菜单点击(CLICK 事件)的 EventKey 是否为「登录」入口。
|
||||
// 菜单在公众号后台手动配置即可(未认证公众号同样支持),
|
||||
// 用户点菜单 → CLICK 事件 → 自动回复确认登录链接,免输入。
|
||||
func isLoginMenuKey(key string) bool {
|
||||
k := strings.TrimSpace(key)
|
||||
if k == "" {
|
||||
|
||||
@@ -8,14 +8,6 @@ import (
|
||||
"github.com/beego/beego/v2/core/logs"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 公众号自定义菜单:发布「扫码登录」菜单(点击事件 → CLICK 事件 → 自动回复
|
||||
// 确认登录链接,用户不用输入任何内容)。
|
||||
// 注意:菜单接口(menu/create)与带参二维码同属认证后能力,
|
||||
// 未认证公众号会返回 48001,届时需改用「公众号内发送登录」路径。
|
||||
// =============================================================
|
||||
|
||||
// LoginMenuKey 登录菜单的事件键值(与 isLoginMenuKey 保持一致)
|
||||
const LoginMenuKey = "LOGIN"
|
||||
|
||||
type mpMenuButton struct {
|
||||
@@ -30,13 +22,11 @@ type mpMenuGetResp struct {
|
||||
Menu struct {
|
||||
Button []mpMenuButton `json:"button"`
|
||||
} `json:"menu"`
|
||||
// 个性化菜单:命中条件时会覆盖默认菜单(公众号底部看到的可能来自这里)
|
||||
ConditionalMenu []map[string]interface{} `json:"conditionalmenu"`
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
// PublishMenuResult 发布结果(供页面展示与排查)
|
||||
type PublishMenuResult struct {
|
||||
Buttons []mpMenuButton `json:"button"`
|
||||
AlreadyExists bool `json:"already_exists"`
|
||||
@@ -48,19 +38,12 @@ type mpMenuCreateResp struct {
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
// PublishLoginMenu 在现有菜单基础上追加「扫码登录」菜单并发布。
|
||||
// - 已存在登录菜单:不再重复发布(AlreadyExists=true);
|
||||
// - 一级菜单满 3 个:返回错误提示;
|
||||
// - 存在个性化菜单:一并返回条数(个性化菜单会覆盖默认菜单,需到公众号后台处理)。
|
||||
//
|
||||
// 注意:微信客户端有菜单缓存,发布后通常需重新关注或等待(最长 24 小时)才可见。
|
||||
func PublishLoginMenu(cfg *Config) (*PublishMenuResult, error) {
|
||||
token, err := GetAccessToken(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 1) 读取现有菜单;46003(菜单不存在)视为空菜单
|
||||
var cur mpMenuGetResp
|
||||
if gerr := httpGetJSON(apiBase+"/cgi-bin/menu/get?access_token="+url.QueryEscape(token), &cur); gerr != nil {
|
||||
return nil, gerr
|
||||
@@ -84,7 +67,6 @@ func PublishLoginMenu(cfg *Config) (*PublishMenuResult, error) {
|
||||
return nil, errors.New("一级菜单已达 3 个上限,请到公众号后台精简后再发布")
|
||||
}
|
||||
|
||||
// 2) 追加登录菜单并发布
|
||||
buttons = append(buttons, mpMenuButton{Type: "click", Name: "扫码登录", Key: LoginMenuKey})
|
||||
var created mpMenuCreateResp
|
||||
if perr := httpPostJSON(apiBase+"/cgi-bin/menu/create?access_token="+url.QueryEscape(token),
|
||||
|
||||
@@ -16,30 +16,22 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 微信被动消息:签名校验 / 安全模式 AES 加解密 / XML 解析与回复构造
|
||||
// 规范参考:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Message_encryption_and_decryption_instructions.html
|
||||
// =============================================================
|
||||
|
||||
// pkcs7BlockSize 微信官方填充块大小(注意不是 16,是 32)
|
||||
const pkcs7BlockSize = 32
|
||||
|
||||
// InboundMessage 接收到的消息/事件(已解密后的 XML 内容)
|
||||
type InboundMessage struct {
|
||||
XMLName xml.Name `xml:"xml"`
|
||||
ToUserName string `xml:"ToUserName"`
|
||||
FromUserName string `xml:"FromUserName"`
|
||||
CreateTime int64 `xml:"CreateTime"`
|
||||
MsgType string `xml:"MsgType"` // text / image / event ...
|
||||
MsgType string `xml:"MsgType"`
|
||||
Content string `xml:"Content"`
|
||||
Event string `xml:"Event"` // subscribe / unsubscribe / SCAN / CLICK ...
|
||||
EventKey string `xml:"EventKey"` // qrscene_<scene> 或 <scene>
|
||||
Event string `xml:"Event"`
|
||||
EventKey string `xml:"EventKey"`
|
||||
Ticket string `xml:"Ticket"`
|
||||
MsgID int64 `xml:"MsgId"`
|
||||
Encrypt string `xml:"Encrypt"` // 安全模式下外层 XML 携带的密文
|
||||
Encrypt string `xml:"Encrypt"`
|
||||
}
|
||||
|
||||
// ParseInboundXML 解析(明文/已解密的)消息 XML
|
||||
func ParseInboundXML(raw string) (*InboundMessage, error) {
|
||||
var msg InboundMessage
|
||||
if err := xml.Unmarshal([]byte(raw), &msg); err != nil {
|
||||
@@ -48,7 +40,6 @@ func ParseInboundXML(raw string) (*InboundMessage, error) {
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
// CheckSignature 明文模式签名校验:sha1(sort(token, timestamp, nonce))
|
||||
func CheckSignature(token, timestamp, nonce, signature string) bool {
|
||||
if token == "" || signature == "" {
|
||||
return false
|
||||
@@ -59,7 +50,6 @@ func CheckSignature(token, timestamp, nonce, signature string) bool {
|
||||
return hex.EncodeToString(sum[:]) == signature
|
||||
}
|
||||
|
||||
// CheckMsgSignature 安全/兼容模式签名校验:sha1(sort(token, timestamp, nonce, encrypt))
|
||||
func CheckMsgSignature(token, timestamp, nonce, encrypt, msgSignature string) bool {
|
||||
if token == "" || msgSignature == "" {
|
||||
return false
|
||||
@@ -70,7 +60,6 @@ func CheckMsgSignature(token, timestamp, nonce, encrypt, msgSignature string) bo
|
||||
return hex.EncodeToString(sum[:]) == msgSignature
|
||||
}
|
||||
|
||||
// MsgSignature 计算安全模式消息签名(回复加密时使用)
|
||||
func MsgSignature(token, timestamp, nonce, encrypt string) string {
|
||||
arr := []string{token, timestamp, nonce, encrypt}
|
||||
sort.Strings(arr)
|
||||
@@ -78,8 +67,6 @@ func MsgSignature(token, timestamp, nonce, encrypt string) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// ============================ AES 加解密 ============================
|
||||
|
||||
func decodeAESKey(encodingAESKey string) ([]byte, error) {
|
||||
key := strings.TrimSpace(encodingAESKey)
|
||||
if len(key) != 43 {
|
||||
@@ -88,7 +75,6 @@ func decodeAESKey(encodingAESKey string) ([]byte, error) {
|
||||
return base64.StdEncoding.DecodeString(key + "=")
|
||||
}
|
||||
|
||||
// DecryptMessage 安全模式消息解密,返回明文 XML;appID 非空时会校验一致性
|
||||
func DecryptMessage(aesKey, appID, encryptBase64 string) (string, error) {
|
||||
key, err := decodeAESKey(aesKey)
|
||||
if err != nil {
|
||||
@@ -127,7 +113,6 @@ func DecryptMessage(aesKey, appID, encryptBase64 string) (string, error) {
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// EncryptMessage 安全模式消息加密,返回 base64 密文
|
||||
func EncryptMessage(aesKey, appID, msg string) (string, error) {
|
||||
key, err := decodeAESKey(aesKey)
|
||||
if err != nil {
|
||||
@@ -187,9 +172,6 @@ func pkcs7Unpad(data []byte) ([]byte, error) {
|
||||
return data[:len(data)-pad], nil
|
||||
}
|
||||
|
||||
// ============================ 被动回复构造 ============================
|
||||
|
||||
// BuildTextReply 构造文本消息回复 XML(明文模式直接返回)
|
||||
func BuildTextReply(toUser, fromUser, content string, timestamp int64) string {
|
||||
esc := func(s string) string {
|
||||
return strings.NewReplacer(
|
||||
@@ -201,7 +183,6 @@ func BuildTextReply(toUser, fromUser, content string, timestamp int64) string {
|
||||
esc(toUser), esc(fromUser), timestamp, esc(content))
|
||||
}
|
||||
|
||||
// BuildEncryptedReply 安全模式回复:对明文回复加密并组装外层 XML
|
||||
func BuildEncryptedReply(cfg *Config, plainReply, timestamp, nonce string) (string, error) {
|
||||
encrypt, err := EncryptMessage(cfg.AESKey, cfg.AppID, plainReply)
|
||||
if err != nil {
|
||||
|
||||
@@ -7,25 +7,15 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 消息推送(认证后可用):
|
||||
// 未认证服务号微信不允许主动推送(模板消息/订阅通知/客服消息均受限),
|
||||
// 本层只负责在认证后通过模板消息把提醒/公告发给已关注粉丝;
|
||||
// 未认证时返回 ErrNotVerified,由上层给出明确提示。
|
||||
// =============================================================
|
||||
|
||||
// ErrNotVerified 公众号未认证,无法主动推送
|
||||
var ErrNotVerified = errors.New("公众号未认证:模板消息推送需认证后使用(当前仅支持关注与被动回复)")
|
||||
|
||||
// PushMessage 推送内容(对应「标题/内容/备注」通用模板字段)
|
||||
type PushMessage struct {
|
||||
Title string // first:首行说明
|
||||
Content string // keyword1:主体内容
|
||||
Remark string // remark:备注
|
||||
URL string // 点击跳转地址(可选)
|
||||
Title string
|
||||
Content string
|
||||
Remark string
|
||||
URL string
|
||||
}
|
||||
|
||||
// PushToOpenID 向指定粉丝推送一条模板消息
|
||||
func PushToOpenID(cfg *Config, openid string, msg PushMessage) error {
|
||||
if cfg == nil {
|
||||
return ErrNotConfigured
|
||||
@@ -55,21 +45,14 @@ func PushToOpenID(cfg *Config, openid string, msg PushMessage) error {
|
||||
})
|
||||
}
|
||||
|
||||
// PushScope 推送范围
|
||||
type PushScope struct {
|
||||
// BindType 为空表示全部已关注粉丝;platform_user / tenant_user 只推绑定对应类型账号的粉丝
|
||||
BindType string
|
||||
// BindID 非 0 时只推给该绑定账号(与 BindType 组合使用)
|
||||
BindID uint64
|
||||
// Tid 非 0 时只推给绑定该租户的用户(tenant_user 场景)
|
||||
Tid uint64
|
||||
}
|
||||
|
||||
// MaxBatchPush 单次批量推送上限
|
||||
const MaxBatchPush = 500
|
||||
|
||||
// PushToFollowers 按范围批量推送,返回成功/失败数量。
|
||||
// 仅推送给「已关注(subscribe=1)且未删除」的粉丝。
|
||||
func PushToFollowers(cfg *Config, scope PushScope, msg PushMessage) (sent, failed int, err error) {
|
||||
if cfg == nil {
|
||||
return 0, 0, ErrNotConfigured
|
||||
@@ -104,7 +87,6 @@ func PushToFollowers(cfg *Config, scope PushScope, msg PushMessage) (sent, faile
|
||||
continue
|
||||
}
|
||||
sent++
|
||||
// 简单节流,避免触发微信频率限制
|
||||
if i%20 == 19 {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
|
||||
@@ -10,26 +10,12 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 注册「账号注册」验证码:网页发起 → 展示带参二维码(scene)→
|
||||
// 用户微信扫码关注 → 服务号被动回复 6 位验证码 → 网页填码核销。
|
||||
// 复用 yz_platform_wechat_mp_verify_code 会话表(bind_type="register"),
|
||||
// 扫码事件回复走通用 handleScanScene,无需新增事件处理。
|
||||
// =============================================================
|
||||
|
||||
// WechatBindTypeRegister 注册验证码会话类型(yz_platform_wechat_mp_verify_code.bind_type)
|
||||
const WechatBindTypeRegister = "register"
|
||||
|
||||
// ErrRegisterCodeInvalid 账号注册:验证码无效 / 已使用(引导语指向「注册」而非绑定用的「验证码」)
|
||||
var ErrRegisterCodeInvalid = errors.New("验证码不正确或已过期:请在公众号内重新发送「注册」获取")
|
||||
|
||||
// RegisterQRDownNotice 带参二维码不可用(IP 白名单 40164 / 未认证 48001 等)时,
|
||||
// 回显给注册页的用户级引导:详细原因见服务端日志,不暴露服务器出口 IP。
|
||||
const RegisterQRDownNotice = "二维码暂不可用:请在公众号内直接发送「注册」获取验证码"
|
||||
|
||||
// StartRegisterVerify 创建注册验证码会话并生成带参二维码。
|
||||
// 带参二维码生成失败(未认证公众号 48001 等)时回退:qrURL 为空、
|
||||
// notice 返回引导(用户在公众号内发送「注册」获取验证码),scene 仍有效可轮询。
|
||||
func StartRegisterVerify(ttl time.Duration) (scene, qrURL, notice string, expireAt time.Time, err error) {
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultVerifyTTL
|
||||
@@ -57,22 +43,12 @@ func StartRegisterVerify(ttl time.Duration) (scene, qrURL, notice string, expire
|
||||
}
|
||||
qrURL, err = CreateQRCode(cfg, scene, int(ttl.Seconds())+120)
|
||||
if err != nil {
|
||||
// 注册页匿名可访问:errcode / errmsg / 服务器出口 IP 等排查信息已在
|
||||
// CreateQRCode 内落到服务端日志(见 logAPIError),此处只回显用户级引导,
|
||||
// 避免向访客泄露服务器出口 IP 与内部错误细节;
|
||||
// 会话仍然有效,「公众号内发送注册」这条兜底路径可正常核销。
|
||||
logs.Warning("[wechat-mp] 注册二维码不可用,已回退公众号发送「注册」:%v", err)
|
||||
return scene, "", RegisterQRDownNotice, expireAt, nil
|
||||
}
|
||||
return scene, qrURL, "", expireAt, nil
|
||||
}
|
||||
|
||||
// ConfirmAccountRegisterVerify 账号注册的验证码核销:
|
||||
// 优先按 scene 核销二维码会话;该会话尚未扫码(用户没扫码,改为在公众号内发送
|
||||
// 「注册」取码)、scene 失效或验证码不属于该会话时,直接按验证码认领会话。
|
||||
//
|
||||
// 账号注册不绑定手机号,服务号无法按手机号把「发送者」与网页会话关联起来,
|
||||
// 因此不要求网页会话必须先被扫码:验证码有效即视为公众号内本人操作。
|
||||
func ConfirmAccountRegisterVerify(scene, code string) (string, error) {
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
@@ -85,7 +61,6 @@ func ConfirmAccountRegisterVerify(scene, code string) (string, error) {
|
||||
}
|
||||
openID, err := ConfirmRegisterVerifyByCode(code)
|
||||
if err != nil {
|
||||
// 按码认领失败的提示要指向注册场景(发送「注册」),而非绑定场景的「验证码」
|
||||
if errors.Is(err, ErrCodeNotPending) || errors.Is(err, ErrCodeUsed) {
|
||||
return "", ErrRegisterCodeInvalid
|
||||
}
|
||||
@@ -94,7 +69,6 @@ func ConfirmAccountRegisterVerify(scene, code string) (string, error) {
|
||||
return openID, nil
|
||||
}
|
||||
|
||||
// GetRegisterVerifyStatus 查询注册会话扫码状态(网页轮询展示「已扫码」)
|
||||
func GetRegisterVerifyStatus(scene string) (scanned bool, expireAt time.Time, err error) {
|
||||
row, err := GetVerifyCode(scene)
|
||||
if err != nil {
|
||||
@@ -109,8 +83,6 @@ func GetRegisterVerifyStatus(scene string) (scanned bool, expireAt time.Time, er
|
||||
return row.Status == models.WechatVerifyStatusScanned, expireAt, nil
|
||||
}
|
||||
|
||||
// ConfirmRegisterVerify 核销注册验证码:校验会话归属与状态,返回扫码人 openid。
|
||||
// 要求会话已被扫码(openid 已写入)、验证码匹配,核销后一次性失效。
|
||||
func ConfirmRegisterVerify(scene, code string) (openid string, err error) {
|
||||
row, err := GetVerifyCode(scene)
|
||||
if err != nil {
|
||||
@@ -140,8 +112,6 @@ func ConfirmRegisterVerify(scene, code string) (openid string, err error) {
|
||||
return row.OpenID, nil
|
||||
}
|
||||
|
||||
// CreateRegisterOpenIDVerify 公众号内发送「注册」时创建的注册会话:
|
||||
// openid 已知(消息发送者),网页端按验证码核销(无带参二维码的兜底路径)。
|
||||
func CreateRegisterOpenIDVerify(openid string, ttl time.Duration) (*models.WechatMpVerifyCode, error) {
|
||||
openid = strings.TrimSpace(openid)
|
||||
if openid == "" {
|
||||
@@ -156,7 +126,7 @@ func CreateRegisterOpenIDVerify(openid string, ttl time.Duration) (*models.Wecha
|
||||
Scene: randomScene(),
|
||||
Code: randomCode6(),
|
||||
OpenID: openid,
|
||||
Status: models.WechatVerifyStatusScanned, // 微信号已知,等同「已扫码待核销」
|
||||
Status: models.WechatVerifyStatusScanned,
|
||||
BindType: WechatBindTypeRegister,
|
||||
ExpireAt: &expireAt,
|
||||
CreateTime: now,
|
||||
@@ -168,7 +138,6 @@ func CreateRegisterOpenIDVerify(openid string, ttl time.Duration) (*models.Wecha
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// LatestPendingRegisterVerifyByOpenID 该微信号最近一条未核销的注册会话(重发验证码时复用)
|
||||
func LatestPendingRegisterVerifyByOpenID(openid string) (*models.WechatMpVerifyCode, error) {
|
||||
var row models.WechatMpVerifyCode
|
||||
err := models.Orm.QueryTable(new(models.WechatMpVerifyCode)).
|
||||
@@ -184,8 +153,6 @@ func LatestPendingRegisterVerifyByOpenID(openid string) (*models.WechatMpVerifyC
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// ConfirmRegisterVerifyByCode 无二维码兜底:按验证码认领「公众号发起」的注册会话。
|
||||
// 只认领 bind_type=register、openid 非空、已扫码待核销的最近会话,CAS 核销防止重复使用。
|
||||
func ConfirmRegisterVerifyByCode(code string) (string, error) {
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
|
||||
@@ -10,25 +10,10 @@ import (
|
||||
"server/models"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 公众号扫码登录(带参二维码方案):
|
||||
// PC 端 /auth/login 扫码面板发起会话并轮询 → 展示带参二维码(scene=会话标识)→
|
||||
// 用户微信扫码:已关注触发 SCAN 事件 / 未关注关注后触发 subscribe 事件,
|
||||
// 服务号【自动】回复「确认登录」一次性链接(无需用户输入任何内容)→
|
||||
// 用户点击链接(/mp-login 兑换,链接携带 scene)→ 精确认领 PC 会话 →
|
||||
// PC 端轮询到确认后建立 UAC 会话自动登录。全程无极验 / 无登录码。
|
||||
// 注:带参二维码需认证公众号;未认证(48001)时回退普通关注二维码,
|
||||
// 用户在公众号发送「登录」换取确认链接。
|
||||
// =============================================================
|
||||
|
||||
// ScanLoginTTL 扫码登录会话有效期
|
||||
const ScanLoginTTL = 5 * time.Minute
|
||||
|
||||
var ErrScanLoginInvalid = errors.New("扫码登录会话不存在或已过期,请刷新二维码重试")
|
||||
|
||||
// StartScanLogin 发起 PC 扫码登录会话,并生成带参二维码。
|
||||
// 带参二维码生成失败(未认证公众号 48001 等)时回退普通关注二维码:
|
||||
// qrURL 为空、notice 返回回退原因,前端需明确提示用户走「发送登录」路径。
|
||||
func StartScanLogin() (scene, qrURL, notice string, expireAt time.Time, err error) {
|
||||
scene = randomScene()
|
||||
now := time.Now()
|
||||
@@ -64,7 +49,6 @@ func StartScanLogin() (scene, qrURL, notice string, expireAt time.Time, err erro
|
||||
return scene, "", notice, expireAt, nil
|
||||
}
|
||||
|
||||
// GetScanLogin 查询扫码登录会话(过期时惰性标记)
|
||||
func GetScanLogin(scene string) (*models.WechatMpScanLogin, error) {
|
||||
scene = strings.TrimSpace(scene)
|
||||
if scene == "" {
|
||||
@@ -85,9 +69,6 @@ func GetScanLogin(scene string) (*models.WechatMpScanLogin, error) {
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// HandleScanLoginEvent 带参二维码扫码事件(SCAN / subscribe 带 qrscene):
|
||||
// scene 属于等待中的扫码登录会话时,自动回复「确认登录」链接(已绑定)
|
||||
// 或绑定提示(未绑定),并返回 true;不属于登录会话返回 false 交由绑定流程处理。
|
||||
func HandleScanLoginEvent(scene, openid string) (string, bool) {
|
||||
scene = strings.TrimSpace(scene)
|
||||
if scene == "" {
|
||||
@@ -129,11 +110,6 @@ func HandleScanLoginEvent(scene, openid string) (string, bool) {
|
||||
return fmt.Sprintf("【扫码登录确认】\n点击以下链接确认登录(%d 分钟内有效,仅可使用一次):\n%s\n\n确认后您的电脑将自动登录。如非本人操作,请忽略本条消息。", minutes, link), true
|
||||
}
|
||||
|
||||
// DirectLoginReply 判断该微信的绑定状态并返回对应回复:
|
||||
// - 已绑定:直接给出「确认登录」一次性链接(点击后 web 直接登录);
|
||||
// - 未绑定:提示先去系统页面完成绑定。
|
||||
//
|
||||
// 用于普通关注(无 scene)与公众号内发送「登录」的兜底路径。
|
||||
func DirectLoginReply(openid string) string {
|
||||
f, err := GetFollowerByOpenID(openid)
|
||||
if err != nil || f == nil || strings.TrimSpace(f.BindType) == "" || f.BindID == 0 {
|
||||
@@ -157,7 +133,6 @@ func DirectLoginReply(openid string) string {
|
||||
return fmt.Sprintf("【确认登录】\n点击以下链接直接登录(%d 分钟内有效,仅可使用一次):\n%s\n\n如非本人操作,请忽略本条消息。", minutes, link)
|
||||
}
|
||||
|
||||
// ConfirmScanLoginByToken 兑换确认链接时精确认领 PC 扫码会话(scene + 令牌双重匹配,CAS)
|
||||
func ConfirmScanLoginByToken(scene, loginToken, bindType string, bindID, bindTid uint64) {
|
||||
scene = strings.TrimSpace(scene)
|
||||
if scene == "" || strings.TrimSpace(loginToken) == "" {
|
||||
@@ -177,8 +152,6 @@ func ConfirmScanLoginByToken(scene, loginToken, bindType string, bindID, bindTid
|
||||
})
|
||||
}
|
||||
|
||||
// ConfirmOldestPendingScanLogin 无 scene 的兜底认领(「登录」文本路径):
|
||||
// 认领最早一条待确认 PC 会话;没有等待中的会话时静默跳过。
|
||||
func ConfirmOldestPendingScanLogin(bindType string, bindID, bindTid uint64) {
|
||||
now := time.Now()
|
||||
var row models.WechatMpScanLogin
|
||||
@@ -202,7 +175,6 @@ func ConfirmOldestPendingScanLogin(bindType string, bindID, bindTid uint64) {
|
||||
})
|
||||
}
|
||||
|
||||
// PickScanLogin PC 端领取确认结果:CAS 把「已确认」置为「已领取」,防止重复领取
|
||||
func PickScanLogin(scene string) (*models.WechatMpScanLogin, error) {
|
||||
row, err := GetScanLogin(scene)
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user