Files
ai_academy/internal/im/wecom/proactive_client.go
T
runny f43fbef5db
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
feat(企微签到):逻辑:员工使用企微扫码后直接跳出签到页面,在签到页面对该课程进行点击签到!
规则:1.签到要校验是否为培训当天签到,如果不是当天扫码签到则进行友好提示;2. 签到需提供员工工号及随机时间戳(超过签到二维码有效期后需重新扫码签到);3.签到二维码每5分钟自动更新一次(更新后之前扫码签到自动作废需重新扫码);
补充说明:1.签到页面需展示该签到课程相关信息;2.展示签到倒计时还有多久过期,过期后需重新扫码进行优化提示;3.签到后提示签到成功!自动登录进入平台系统并进入该课程详情页面
2026-11-25 11:02:48 +08:00

238 lines
7.6 KiB
Go

// ProactiveClient pushes messages to WeCom (企业微信) users without a prior
// incoming message, via the self-built application message API
// (/cgi-bin/message/send). Unlike WebhookAdapter — whose SendReply answers an
// incoming message — this client is driven by the training scheduler to
// deliver scheduled reminders (outbox pattern in tr_notifications).
//
// Reference: https://developer.work.weixin.qq.com/document/path/90236
package wecom
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
neturl "net/url"
"strings"
"sync"
"time"
"unicode/utf8"
)
// maxMarkdownBytes is the WeCom markdown content limit; longer content is
// rejected by the API with errcode 40058-style errors.
const maxMarkdownBytes = 2048
// ProactiveClient sends application messages to WeCom users by userid.
// Credentials mirror the webhook-mode IM channel (corp_id / agent_secret /
// corp_agent_id), so operators maintain one set of credentials per tenant.
type ProactiveClient struct {
corpID string
agentSecret string
corpAgentID int
apiBaseURL string
// Token cache — WeCom tokens expire in 7200 seconds (2 hours); cached
// with a safety margin, same as WebhookAdapter.
tokenMu sync.Mutex
tokenCache string
tokenExpAt time.Time
}
// NewProactiveClient creates a proactive push client. apiBaseURL may be empty
// for the public cloud endpoint; a custom value must pass the same SSRF
// checks as the webhook adapter (private deployments add the host to
// SSRF_WHITELIST).
func NewProactiveClient(corpID, agentSecret string, corpAgentID int, apiBaseURL string) (*ProactiveClient, error) {
if corpID == "" || agentSecret == "" {
return nil, fmt.Errorf("wecom proactive client requires corp_id and agent_secret")
}
if apiBaseURL == "" {
apiBaseURL = defaultAPIBaseURL
}
apiBaseURL = strings.TrimRight(apiBaseURL, "/")
if err := validateEndpointURL(apiBaseURL, defaultAPIBaseURL, "https"); err != nil {
return nil, fmt.Errorf("invalid api_base_url: %w", err)
}
return &ProactiveClient{
corpID: corpID,
agentSecret: agentSecret,
corpAgentID: corpAgentID,
apiBaseURL: apiBaseURL,
}, nil
}
// SendMarkdown sends one markdown message to the listed WeCom userids in a
// single message/send call (touser joined with "|"). An empty list is a no-op.
func (c *ProactiveClient) SendMarkdown(ctx context.Context, userIDs []string, content string) error {
if len(userIDs) == 0 {
return nil
}
accessToken, err := c.getAccessToken(ctx)
if err != nil {
return fmt.Errorf("get access token: %w", err)
}
content = truncateUTF8Bytes(content, maxMarkdownBytes)
payload := map[string]interface{}{
"touser": strings.Join(userIDs, "|"),
"msgtype": "markdown",
"agentid": c.corpAgentID,
"markdown": map[string]string{"content": content},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal payload: %w", err)
}
sendURL := fmt.Sprintf("%s/cgi-bin/message/send?access_token=%s", c.apiBaseURL, accessToken)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, sendURL, bytes.NewReader(payloadBytes))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("send message: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("decode response: %w", err)
}
if result.ErrCode != 0 {
return fmt.Errorf("wecom api error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
return nil
}
// wecomOAuthAuthorizeBase 企微网页授权入口(公开固定地址,不走 apiBaseURL ——
// 后者可被私有化部署改写,而 OAuth 授权页始终由微信侧提供)。
const wecomOAuthAuthorizeBase = "https://open.weixin.qq.com/connect/oauth2/authorize"
// BuildOAuthAuthorizeURL 企微网页授权链接(snsapi_base 静默免登,培训扫码签到用):
// 学员在企微内置浏览器打开后无感授权,302 回 redirect_uri 并携带 code 与 state。
func (c *ProactiveClient) BuildOAuthAuthorizeURL(redirectURI, state string) string {
return fmt.Sprintf(
"%s?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s&agentid=%d#wechat_redirect",
wecomOAuthAuthorizeBase,
neturl.QueryEscape(c.corpID),
neturl.QueryEscape(redirectURI),
neturl.QueryEscape(state),
c.corpAgentID,
)
}
// GetOAuthUserID 网页授权 code 换用户身份(GET /cgi-bin/auth/getuserinfo):
// snsapi_base 静默授权即可拿到 userid;code 由企微保证一次性(5 分钟有效)。
func (c *ProactiveClient) GetOAuthUserID(ctx context.Context, code string) (string, error) {
accessToken, err := c.getAccessToken(ctx)
if err != nil {
return "", fmt.Errorf("get access token: %w", err)
}
userURL := fmt.Sprintf("%s/cgi-bin/auth/getuserinfo?access_token=%s&code=%s",
c.apiBaseURL, accessToken, neturl.QueryEscape(code))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, userURL, nil)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request oauth userinfo: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
UserID string `json:"userid"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode oauth userinfo: %w", err)
}
if result.ErrCode != 0 {
// 42001/40014 token 过期类错误清缓存,让下次调用重新获取。
if result.ErrCode == 42001 || result.ErrCode == 40014 {
c.tokenMu.Lock()
c.tokenCache = ""
c.tokenExpAt = time.Time{}
c.tokenMu.Unlock()
}
return "", fmt.Errorf("wecom oauth api error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
if result.UserID == "" {
return "", fmt.Errorf("wecom oauth api returned empty userid")
}
return result.UserID, nil
}
// getAccessToken retrieves the WeCom access token with caching.
func (c *ProactiveClient) getAccessToken(ctx context.Context) (string, error) {
c.tokenMu.Lock()
defer c.tokenMu.Unlock()
if c.tokenCache != "" && time.Now().Before(c.tokenExpAt) {
return c.tokenCache, nil
}
tokenURL := fmt.Sprintf("%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
c.apiBaseURL, c.corpID, c.agentSecret)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request access token: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"` // seconds
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode token response: %w", err)
}
if result.ErrCode != 0 {
return "", fmt.Errorf("get token error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
c.tokenCache = result.AccessToken
// Cache with 5-minute safety margin
ttl := time.Duration(result.ExpiresIn) * time.Second
if ttl > 5*time.Minute {
ttl -= 5 * time.Minute
}
c.tokenExpAt = time.Now().Add(ttl)
return c.tokenCache, nil
}
// truncateUTF8Bytes clips s to at most limit bytes without splitting a rune.
func truncateUTF8Bytes(s string, limit int) string {
if len(s) <= limit {
return s
}
var b strings.Builder
n := 0
for _, r := range s {
size := utf8.RuneLen(r)
if size <= 0 || n+size > limit {
break
}
b.WriteString(string(r))
n += size
}
return b.String()
}