package service import ( "context" "encoding/json" "fmt" "net/http" "net/url" "time" ) const weChatCode2SessionURL = "https://api.weixin.qq.com/sns/jscode2session" // WeChatClient 调用微信接口获取 session/openid。 type WeChatClient struct { appID string appSecret string client *http.Client } type WeChatSession struct { OpenID string `json:"openid"` UnionID string `json:"unionid"` SessionKey string `json:"session_key"` } type weChatSessionResponse struct { WeChatSession ErrCode int `json:"errcode"` ErrMsg string `json:"errmsg"` } // WeChatError 表示微信接口级错误。 type WeChatError struct { Code int Msg string } func (e *WeChatError) Error() string { return fmt.Sprintf("wechat error: code=%d msg=%s", e.Code, e.Msg) } func NewWeChatClient(appID, appSecret string, client *http.Client) *WeChatClient { if client == nil { client = &http.Client{ Timeout: 5 * time.Second, } } return &WeChatClient{ appID: appID, appSecret: appSecret, client: client, } } func (c *WeChatClient) Code2Session(ctx context.Context, code string) (*WeChatSession, error) { query := url.Values{} query.Set("appid", c.appID) query.Set("secret", c.appSecret) query.Set("js_code", code) query.Set("grant_type", "authorization_code") req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s", weChatCode2SessionURL, query.Encode()), nil) if err != nil { return nil, fmt.Errorf("build wechat request: %w", err) } resp, err := c.client.Do(req) if err != nil { return nil, fmt.Errorf("call wechat api: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("wechat api unexpected status: %s", resp.Status) } var raw weChatSessionResponse if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil { return nil, fmt.Errorf("decode wechat response: %w", err) } if raw.ErrCode != 0 { return nil, &WeChatError{Code: raw.ErrCode, Msg: raw.ErrMsg} } return &raw.WeChatSession, nil }