You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.8 KiB
65 lines
1.8 KiB
package wx
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
)
|
|
|
|
var wechatErrors = map[int]string{
|
|
-1: "微信服务器系统繁忙",
|
|
40001: "获取 access_token 时 AppSecret 错误,或者 access_token 无效。请开发者认真比对 AppSecret 的正确性,或查看是否正在为恰当的公众号调用接口",
|
|
40002: "不合法的凭证类型",
|
|
41004: "缺少 secret 参数",
|
|
40013: "不合法的 AppID ,请开发者检查 AppID 的正确性,避免异常字符,注意大小写",
|
|
40125: "请检查 secret 的正确性,避免异常字符,注意大小写",
|
|
40029: "js_code无效",
|
|
40164: "调用接口的IP地址不在白名单中",
|
|
40226: "微信检测到您的账号属于高风险等级用户",
|
|
45011: "微信服务器繁忙,请稍候再试",
|
|
50004: "禁止使用 token 接口",
|
|
50007: "账号已冻结",
|
|
61024: "第三方平台 API 需要使用第三方平台专用 token",
|
|
}
|
|
|
|
type Result struct {
|
|
Errmsg string `json:"errmsg"` // 错误信息
|
|
Errcode int `json:"errcode,omitempty"` // 错误码
|
|
}
|
|
|
|
func (r *Result) Err() error {
|
|
if r.Errcode == 0 {
|
|
return nil
|
|
}
|
|
msg, ok := wechatErrors[r.Errcode]
|
|
if !ok {
|
|
msg = r.Errmsg
|
|
}
|
|
return errors.New(msg)
|
|
}
|
|
|
|
func httpGet[T any](ctx context.Context, url string, query map[string]string) (*T, error) {
|
|
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if query != nil && len(query) > 0 {
|
|
qs := req.URL.Query()
|
|
for key, val := range query {
|
|
qs.Set(key, val)
|
|
}
|
|
req.URL.RawQuery = qs.Encode()
|
|
}
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
var result T
|
|
err = json.NewDecoder(res.Body).Decode(&result)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &result, nil
|
|
}
|
|
|