196 lines
4.9 KiB
Go
196 lines
4.9 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
)
|
|
|
|
const weChatCode2SessionURL = "https://api.weixin.qq.com/sns/jscode2session"
|
|
const weChatAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
|
|
const weChatGetWXACodeURL = "https://api.weixin.qq.com/wxa/getwxacode"
|
|
|
|
// 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"`
|
|
}
|
|
|
|
type weChatAccessTokenResponse struct {
|
|
AccessToken string `json:"access_token"`
|
|
ExpiresIn int `json:"expires_in"`
|
|
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
|
|
}
|
|
|
|
func (c *WeChatClient) GetAccessToken(ctx context.Context) (string, error) {
|
|
query := url.Values{}
|
|
query.Set("grant_type", "client_credential")
|
|
query.Set("appid", c.appID)
|
|
query.Set("secret", c.appSecret)
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s", weChatAccessTokenURL, query.Encode()), nil)
|
|
if err != nil {
|
|
return "", fmt.Errorf("build access token request: %w", err)
|
|
}
|
|
|
|
resp, err := c.client.Do(req)
|
|
if err != nil {
|
|
return "", fmt.Errorf("call wechat access token api: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("wechat access token api unexpected status: %s", resp.Status)
|
|
}
|
|
|
|
var raw weChatAccessTokenResponse
|
|
if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
|
|
return "", fmt.Errorf("decode access token response: %w", err)
|
|
}
|
|
if raw.ErrCode != 0 {
|
|
return "", &WeChatError{Code: raw.ErrCode, Msg: raw.ErrMsg}
|
|
}
|
|
if raw.AccessToken == "" {
|
|
return "", fmt.Errorf("wechat access token missing")
|
|
}
|
|
return raw.AccessToken, nil
|
|
}
|
|
|
|
type getWXACodeRequest struct {
|
|
Path string `json:"path"`
|
|
Width int `json:"width,omitempty"`
|
|
AutoColor bool `json:"auto_color"`
|
|
IsHyaline bool `json:"is_hyaline"`
|
|
}
|
|
|
|
type weChatAPIErrorResponse struct {
|
|
ErrCode int `json:"errcode"`
|
|
ErrMsg string `json:"errmsg"`
|
|
}
|
|
|
|
func (c *WeChatClient) GetWXACode(ctx context.Context, path string, width int) ([]byte, error) {
|
|
accessToken, err := c.GetAccessToken(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
body, err := json.Marshal(getWXACodeRequest{
|
|
Path: path,
|
|
Width: width,
|
|
AutoColor: false,
|
|
IsHyaline: true,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("marshal getwxacode request: %w", err)
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(
|
|
ctx,
|
|
http.MethodPost,
|
|
fmt.Sprintf("%s?access_token=%s", weChatGetWXACodeURL, url.QueryEscape(accessToken)),
|
|
bytes.NewReader(body),
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build getwxacode request: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := c.client.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("call wechat getwxacode api: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
payload, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read getwxacode response: %w", err)
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("wechat getwxacode api unexpected status: %s", resp.Status)
|
|
}
|
|
|
|
var apiErr weChatAPIErrorResponse
|
|
if err := json.Unmarshal(payload, &apiErr); err == nil && apiErr.ErrCode != 0 {
|
|
return nil, &WeChatError{Code: apiErr.ErrCode, Msg: apiErr.ErrMsg}
|
|
}
|
|
|
|
return payload, nil
|
|
}
|