f
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"bdrp-server/app/main/model"
|
||||
"bdrp-server/common/xerr"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -104,6 +104,8 @@ func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthRe
|
||||
type AccessTokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
Openid string `json:"openid"`
|
||||
ErrCode int `json:"errcode,omitempty"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
}
|
||||
|
||||
// GetAccessToken 通过code获取access_token
|
||||
@@ -112,26 +114,46 @@ func (l *WxH5AuthLogic) GetAccessToken(code string) (*AccessTokenResp, error) {
|
||||
appSecret := l.svcCtx.Config.WechatH5.AppSecret
|
||||
|
||||
url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
|
||||
const (
|
||||
maxRetryTimes = 3
|
||||
httpTimeout = 5 * time.Second
|
||||
retryDelay = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
client := &http.Client{Timeout: httpTimeout}
|
||||
var lastErr error
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
for attempt := 1; attempt <= maxRetryTimes; attempt++ {
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
} else {
|
||||
body, readErr := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if readErr != nil {
|
||||
lastErr = readErr
|
||||
} else {
|
||||
var accessTokenResp AccessTokenResp
|
||||
if unmarshalErr := json.Unmarshal(body, &accessTokenResp); unmarshalErr != nil {
|
||||
lastErr = unmarshalErr
|
||||
} else {
|
||||
if accessTokenResp.ErrCode != 0 {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
|
||||
"微信接口返回错误: errcode=%d, errmsg=%s",
|
||||
accessTokenResp.ErrCode, accessTokenResp.ErrMsg)
|
||||
}
|
||||
if accessTokenResp.AccessToken == "" || accessTokenResp.Openid == "" {
|
||||
return nil, errors.New("微信接口返回数据不完整")
|
||||
}
|
||||
return &accessTokenResp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if attempt < maxRetryTimes {
|
||||
time.Sleep(time.Duration(attempt) * retryDelay)
|
||||
}
|
||||
}
|
||||
|
||||
var accessTokenResp AccessTokenResp
|
||||
if err = json.Unmarshal(body, &accessTokenResp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if accessTokenResp.AccessToken == "" || accessTokenResp.Openid == "" {
|
||||
return nil, errors.New("accessTokenResp.AccessToken为空")
|
||||
}
|
||||
|
||||
return &accessTokenResp, nil
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "请求微信access_token接口失败(重试%d次): %v", maxRetryTimes, lastErr)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user