kobe6258 3 bulan lalu
induk
melakukan
8df8f5037a

+ 114 - 2
common/component/wechat/wechat_client.go

@@ -1,6 +1,7 @@
 package wechat
 
 import (
+	"bytes"
 	"encoding/json"
 	"eta/eta_mini_ht_api/common/component/config"
 	logger "eta/eta_mini_ht_api/common/component/log"
@@ -10,13 +11,16 @@ import (
 	"eta/eta_mini_ht_api/common/utils/client"
 	"fmt"
 	"io"
+	"io/ioutil"
+	"net/http"
 	"net/url"
 	"sync"
 )
 
 const (
-	baseURL = "https://api.weixin.qq.com"
-	codeAPI = "/sns/jscode2session"
+	baseURL        = "https://api.weixin.qq.com"
+	codeAPI        = "/sns/jscode2session"
+	accessTokenApi = "/cgi-bin/token"
 )
 const (
 // WeChatServerError 微信服务器错误时返回返回消息
@@ -147,6 +151,23 @@ func code2url(appID, secret, code string) (string, error) {
 
 	return url.String(), nil
 }
+func accessToken2url(appID, secret string) (string, error) {
+
+	url, err := url.Parse(baseURL + accessTokenApi)
+	if err != nil {
+		return "", err
+	}
+
+	query := url.Query()
+
+	query.Set("appid", appID)
+	query.Set("secret", secret)
+	query.Set("grant_type", "client_credential")
+
+	url.RawQuery = query.Encode()
+
+	return url.String(), nil
+}
 
 type WxUserInfo struct {
 	OpenId       string `json:"openid"`
@@ -157,6 +178,97 @@ type WxUserInfo struct {
 	ErrMsg       string
 }
 
+type QRCodeRequest struct {
+	Path      string `json:"path"`
+	Width     int    `json:"width,omitempty"`
+	AutoColor bool   `json:"auto_color,omitempty"`
+	LineColor struct {
+		R int `json:"r"`
+		G int `json:"g"`
+		B int `json:"b"`
+	} `json:"line_color,omitempty"`
+	IsHyaline bool `json:"is_hyaline,omitempty"`
+}
+
+func (cli *Client) GenerateQRCode(code, path string) ([]byte, error) {
+	wechatConf, ok := config.GetConfig(contants.WECHAT).(*config.WechatConfig)
+	if !ok {
+		return nil, exception.New(exception.WeChatIllegalRequest)
+	}
+	accessToken, err := getAccessToken(wechatConf.GetAppid(), wechatConf.GetSecret(), code)
+	if err != nil {
+		return nil, err
+	}
+	api := fmt.Sprintf("%s%s?access_token=%s", baseURL, "/cgi-bin/wxaapp/createwxaqrcode", accessToken)
+	reqBody := QRCodeRequest{
+		Path:      path,
+		Width:     430,
+		AutoColor: true,
+		LineColor: struct {
+			R int `json:"r"`
+			G int `json:"g"`
+			B int `json:"b"`
+		}{
+			R: 0,
+			G: 0,
+			B: 0,
+		},
+		IsHyaline: false,
+	}
+
+	jsonData, err := json.Marshal(reqBody)
+	if err != nil {
+		return nil, err
+	}
+
+	resp, err := http.Post(api, "application/json", bytes.NewBuffer(jsonData))
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode != 200 {
+		body, _ := ioutil.ReadAll(resp.Body)
+		return nil, fmt.Errorf("failed to generate QR code: %s", body)
+	}
+
+	qrCodeBytes, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return nil, err
+	}
+
+	return qrCodeBytes, nil
+}
+
+func getAccessToken(appid, secret, code string) (string, error) {
+	api, err := accessToken2url(appid, secret)
+	if err != nil {
+		return "", exception.New(exception.WeChatIllegalRequest)
+	}
+	resp, err := http.Get(api)
+	if err != nil {
+		return "", err
+	}
+	defer resp.Body.Close()
+
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return "", err
+	}
+
+	var result map[string]interface{}
+	err = json.Unmarshal(body, &result)
+	if err != nil {
+		return "", err
+	}
+
+	if accessToken, ok := result["access_token"].(string); ok {
+		return accessToken, nil
+	}
+
+	return "", fmt.Errorf("failed to get access token: %s", string(body))
+}
+
 // Login 小程序登录
 func (cli *Client) GzhLogin(code string) (wxUser WxUser, err error) {
 	if code == "" {

+ 4 - 0
common/exception/exc_enums.go

@@ -99,6 +99,8 @@ const (
 	WechatUserInfoFailed
 	WeChatCodeEmpty
 	WeChatIllegalRequest
+	WeChatConfigError
+	WeChatQRCodeFailed
 )
 const (
 	ReportErrCode int = iota + 50000 // iota 自动递增,从 1 开始
@@ -245,6 +247,8 @@ var ErrorMap = map[int]string{
 	WeChatResponseError:  "解析微信响应数据失败",
 	WeChatCodeEmpty:      "微信获取用户信息,code不能为空",
 	WeChatIllegalRequest: "不合法的微信请求",
+	WeChatConfigError:    "微信配置获取失败",
+	WeChatQRCodeFailed:   "二维码生成失败",
 	//研报
 	GetPublishedRandListFailed:   "获取已发布研报列表失败",
 	GetPermissionListFailed:      "获取品种列表失败",

+ 23 - 0
controllers/sys/sys_controller.go

@@ -1,7 +1,9 @@
 package sys
 
 import (
+	"encoding/base64"
 	"eta/eta_mini_ht_api/common/contants"
+	"eta/eta_mini_ht_api/common/exception"
 	"eta/eta_mini_ht_api/controllers"
 	configService "eta/eta_mini_ht_api/service/sys"
 )
@@ -49,3 +51,24 @@ func (s *SysController) GetConfig(config string) {
 		return
 	})
 }
+
+// GetQRCode  获取微信二维码
+// @Summary 获取微信二维码
+// @Description 获取微信二维码
+// @Success 200 {object} controllers.BaseResponse
+// @router /getQRCode [get]
+func (s *SysController) GetQRCode(code string) {
+	controllers.Wrap(&s.BaseController, func() (result *controllers.WrapData, err error) {
+		result = s.InitWrapData("获取二维码失败")
+		path := "https://appchannel.htfutures.com:18086/channelqrcode/main/index.html#/regisApp?channelId=[4]10091"
+		qrCode, err := configService.GetQRCode(code, path)
+		if err != nil {
+			err = exception.NewWithException(exception.WeChatQRCodeFailed, err.Error())
+			s.FailedResult("获取二维码失败", result)
+			return
+		}
+		s.SuccessResult("获取二维码成功", base64.StdEncoding.EncodeToString(qrCode), result)
+		return
+	})
+
+}

+ 11 - 0
routers/commentsRouter.go

@@ -287,6 +287,17 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/sys:SysController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/sys:SysController"],
+        beego.ControllerComments{
+            Method: "GetQRCode",
+            Router: `/getQRCode`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(
+				param.New("code"),
+			),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:AccountController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:AccountController"],
         beego.ControllerComments{
             Method: "CheckUserStatus",

+ 15 - 0
service/sys/sys_config.go → service/sys/sys_config_service.go

@@ -2,6 +2,7 @@ package sys
 
 import (
 	logger "eta/eta_mini_ht_api/common/component/log"
+	"eta/eta_mini_ht_api/common/component/wechat"
 	"eta/eta_mini_ht_api/domian/config"
 )
 
@@ -11,6 +12,16 @@ const (
 	ConfigTypeByte = "byte"
 )
 
+var (
+	wechatClient *wechat.Client
+)
+
+func wx() *wechat.Client {
+	if wechatClient == nil {
+		wechatClient = wechat.GetInstance()
+	}
+	return wechatClient
+}
 func GetStrConfig(configId int) (value string, err error) {
 	var configVal interface{}
 	configVal, err = config.GetConfigValue(configId, ConfigTypeStr)
@@ -43,3 +54,7 @@ func GetByteConfig(configId int) (value string, err error) {
 	value = configVal.(string)
 	return
 }
+
+func GetQRCode(code, path string) (weird []byte, err error) {
+	return wx().GenerateQRCode(code, path)
+}

+ 12 - 0
service/user/user_service.go

@@ -56,6 +56,7 @@ type UserProfile struct {
 	RiskLevel       string `json:"riskLevel"`
 	RiskLevelStatus string `json:"riskLevelStatus"`
 	UserName        string `json:"userName"`
+	AccountStatus   string `json:"accountStatus"`
 }
 
 func CheckUserRiskMatchStatus(userId int) (riskLevel string, userRiskLevelStatus string, err error) {
@@ -225,7 +226,18 @@ func GetUserProfile(userId int) (userProfile UserProfile, err error) {
 		}
 		return
 	}
+	OfficialUser, err := userService.GetUserByTemplateUserId(userId)
+	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+		logger.Error("获取用户信息失败:%v", err)
+		err = exception.New(exception.OfficialUserFoundError)
+		return
+	}
 	userProfile = convertUserDTOToProfile(userDTO)
+	if errors.Is(err, gorm.ErrRecordNotFound) {
+		userProfile.AccountStatus = "unopen"
+		return
+	}
+	userProfile.AccountStatus = OfficialUser.AccountStatus
 	return
 }
 func GetAnalystDetail(userId int, analystId int) (analystDetail AnalystDetail, err error) {