// 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() }