Преглед изворни кода

add:新增微信公众号注册

zqbao пре 9 месеци
родитељ
комит
53c79fa3cf
4 измењених фајлова са 107 додато и 5 уклоњено
  1. 49 1
      controllers/wechat.go
  2. 3 4
      models/user_record.go
  3. 9 0
      routers/commentsRouter.go
  4. 46 0
      services/wechat/wechat.go

+ 49 - 1
controllers/wechat.go

@@ -167,7 +167,8 @@ func subscribe(openId string) {
 			newUserRecord.Headimgurl = bindUserRecord.Headimgurl
 		}
 	}
-	err = newUserRecord.Insert()
+	insertId, err := newUserRecord.Insert()
+	newUserRecord.UserRecordId = int(insertId)
 	if err != nil {
 		fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
 		return
@@ -248,3 +249,50 @@ func (this *WechatController) Login() {
 	br.Success = true
 	br.Ret = 200
 }
+
+// @Title 公众号绑定
+// @Description 公众号绑定
+// @Param	request	body request.WeChatLoginReq true "type json string"
+// @Success 200 {object} models.LoginResp
+// @router /subscribe [post]
+func (this *WechatController) Subscribe() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if err := recover(); err != nil {
+			fmt.Println(err)
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	var req request.WeChatLoginReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析失败"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.Code == "" {
+		br.Msg = "授权码不存在"
+		return
+	}
+	info, err := wechat.GetOpenId(req.Code)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	u := &models.UserRecord{
+		OpenId:  info.OpenId,
+		UnionId: info.UnionId,
+	}
+	_, err = u.Insert()
+	if err != nil {
+		br.Msg = "新增失败"
+		br.ErrMsg = "新增失败,Err:" + err.Error()
+		return
+	}
+	br.Msg = "获取成功"
+	br.Success = true
+	br.Ret = 200
+}

+ 3 - 4
models/user_record.go

@@ -7,7 +7,7 @@ import (
 )
 
 type UserRecord struct {
-	UserRecordId  int       `orm:"column(user_record_id);pk"`
+	UserRecordId  int       `orm:"pk"`
 	OpenId        string    `description:"用户openid,最大长度:32"`
 	UnionId       string    `description:"用户unionid,最大长度:64"`
 	Subscribe     int       `description:"是否关注"`
@@ -30,10 +30,9 @@ func (item *UserRecord) Update(cols []string) (err error) {
 	return
 }
 
-func (item *UserRecord) Insert() (err error) {
+func (item *UserRecord) Insert() (insertId int64, err error) {
 	o := orm.NewOrm()
-	recordId, err := o.Insert(item)
-	item.UserRecordId = int(recordId)
+	insertId, err = o.Insert(item)
 	return
 }
 

+ 9 - 0
routers/commentsRouter.go

@@ -277,4 +277,13 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:WechatController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:WechatController"],
+        beego.ControllerComments{
+            Method: "Subscribe",
+            Router: `/subscribe`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
 }

+ 46 - 0
services/wechat/wechat.go

@@ -1,9 +1,12 @@
 package wechat
 
 import (
+	"encoding/json"
 	"eta/eta_mini_api/models"
 	"eta/eta_mini_api/utils"
 	"fmt"
+	"io"
+	"net/http"
 	"time"
 
 	"github.com/silenceper/wechat/v2"
@@ -83,6 +86,14 @@ func GetUserInfo(openid string) (userInfo *user.Info, err error) {
 	return
 }
 
+// GetSession 获取用户详情
+// func GetSession(code string) (userInfo auth.ResCode2Session, err error) {
+// 	wechatClient := GetWxChat()
+// 	userClient := wechatClient.GetUser()
+// 	userInfo, err = authClient.Code2Session(code)
+// 	return
+// }
+
 // GetJsConfig 获取公众号jsConfig
 func GetJsConfig(signUrl string) (jsConf *js.Config, err error) {
 	wechatClient := GetWxChat()
@@ -90,3 +101,38 @@ func GetJsConfig(signUrl string) (jsConf *js.Config, err error) {
 	jsConf, err = j.GetConfig(signUrl)
 	return
 }
+
+type WxUserToken struct {
+	OpenId       string
+	UnionId      string
+	AccessToken  string
+	ExpiresIn    string
+	RefreshToken string
+	Scope        string
+}
+
+func GetOpenId(code string) (info *WxUserToken, err error) {
+
+	httpUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?
+		appid=%s&secret=%s&code=%s&grant_type=authorization_code`
+	httpUrl = fmt.Sprintf(httpUrl, utils.WX_APPID, utils.WX_APP_SECRET, code)
+
+	client := http.Client{}
+	wxReq, err := http.NewRequest("GET", httpUrl, nil)
+	if err != nil {
+		return
+	}
+	response, err := client.Do(wxReq)
+	if err != nil {
+		return
+	}
+	defer response.Body.Close()
+	body, err := io.ReadAll(response.Body)
+	if err != nil {
+		return
+	}
+	if err = json.Unmarshal(body, &info); err != nil {
+		return
+	}
+	return
+}