Browse Source

1、完成模拟资金账户
2、添加linux打包脚本
3、添加腾讯定位信息获取

chendeng 2 years ago
parent
commit
5d4259c65a
10 changed files with 170 additions and 19 deletions
  1. 3 0
      build.bat
  2. 7 1
      configFiles/config.yaml
  3. 138 13
      controllers/user.go
  4. 1 0
      go.mod
  5. 2 0
      go.sum
  6. 3 2
      main.go
  7. 2 2
      models/user.go
  8. 7 1
      repository/user.go
  9. 1 0
      router.go
  10. 6 0
      server/user.go

+ 3 - 0
build.bat

@@ -0,0 +1,3 @@
+set GOARCH=amd64
+set GOOS=linux
+go build

+ 7 - 1
configFiles/config.yaml

@@ -1,3 +1,9 @@
 dbstr: root:111111@tcp(127.0.0.1:3306)/sxdb?charset=utf8mb4&parseTime=True&loc=Local
 appid: wx7f672f173c907e10
-appSecret: b02eba52eef930a07c6d5f9d7895cdda
+appSecret: b02eba52eef930a07c6d5f9d7895cdda
+encrypt: 0x5c4Ac697C62c20808105134FA2036900B1f8AFDE
+map_key: MC2BZ-UJWWG-63RQS-QCNXJ-VZF4H-CBB23
+map_sk: H25D26Yd5IRvmnvVtbJjcAVYdmzHkEy4
+ip138_token: ad3306c76dca90c73929549a2b98eb27
+port: 8999
+mode: debug

+ 138 - 13
controllers/user.go

@@ -1,20 +1,25 @@
 package controllers
 
 import (
+	"crypto/md5"
+	"encoding/hex"
 	"encoding/json"
+	"fmt"
+	"github.com/gin-gonic/gin"
+	"github.com/spf13/viper"
 	"io"
+	"io/ioutil"
 	"log"
 	"math/rand"
 	"net/http"
+	"sort"
+	"strings"
 	"the12animal/configFiles"
 	"the12animal/errorcode"
 	"the12animal/models"
 	"the12animal/server"
 	"the12animal/timedata"
 	"time"
-
-	"github.com/gin-gonic/gin"
-	"github.com/spf13/viper"
 )
 
 type UserController struct {
@@ -27,10 +32,12 @@ type UserController struct {
 }
 
 type consumercodeReq struct {
-	Code     string `json:"code"`
-	NickName string `json:"nick_name"`
-	PicUrl   string `json:"pic_url"` //头像路由
-	Phone    string `json:"phone"`   //头像路由
+	Code      string  `json:"code"`
+	NickName  string  `json:"nick_name"`
+	PicUrl    string  `json:"pic_url"` //头像路由
+	Phone     string  `json:"phone"`   //头像路由
+	Latitude  float64 `json:"latitude"`
+	Longitude float64 `json:"longitude"`
 }
 
 func (U *UserController) Init() {
@@ -68,7 +75,7 @@ func (U *UserController) RunResurrection(g *gin.Context) {
 	}
 
 	openid := g.GetHeader("token")
-	resurrectionCount := U.C.GetResurrectionCount(openid)
+	resurrectionCount := U.C.GetResurrectionCount(openid) - 1
 	resurrectionConfig := U.Resurrection
 	var resurrectionJson []float32
 	json.Unmarshal([]byte(resurrectionConfig), &resurrectionJson)
@@ -94,6 +101,25 @@ func (U *UserController) RunResurrection(g *gin.Context) {
 	g.JSON(200, back)
 }
 
+func (U *UserController) ClearResurrectionCount(g *gin.Context) {
+	openid := g.GetHeader("token")
+	resurrectionCount := U.C.GetResurrectionCount(openid)
+	var resurrectionJson []float32
+	json.Unmarshal([]byte(U.Resurrection), &resurrectionJson)
+
+	if resurrectionCount-1 < len(resurrectionJson) {
+		errRequest(g, "未达到清空条件", 1)
+		return
+	}
+
+	U.C.ClearResurrection(openid)
+	back := BackData{}
+
+	back.Code = 0
+	back.Data = ""
+	g.JSON(200, back)
+}
+
 type resurrectionData struct {
 	Count        int    `json:"resurrection_count"`
 	Resurrection string `json:"resurrection"`
@@ -122,7 +148,7 @@ func (U *UserController) Login(g *gin.Context) {
 	code, msg, wxMsg := U.wxLogin(req.Code)
 	if code == 0 {
 		encrypt := &models.Encrypt{}
-		phoneNumber := encrypt.DecryptData("0x5c4Ac697C62c20808105134FA2036900B1f8AFDE", req.Phone)
+		phoneNumber := encrypt.DecryptData(viper.GetString("encrypt"), req.Phone)
 		back := BackData{}
 		nothas := U.C.UserHasOrNot(wxMsg.Openid)
 		var (
@@ -130,7 +156,22 @@ func (U *UserController) Login(g *gin.Context) {
 			errorcode int
 		)
 		if nothas {
-			addr1, addr2 := U.getClientAddr(g.ClientIP())
+			//addr1, addr2 := U.getClientAddr(g.ClientIP())
+			var addr1 = ""
+			var addr2 = ""
+			if req.Latitude != -999999999 {
+				addr1, addr2 = U.getLocationAddr(req.Latitude, req.Longitude)
+			}
+
+			if addr1 == "" {
+				addr1, addr2 = U.getClientAddr(g.ClientIP())
+			}
+
+			if addr1 == "" {
+				//如果定位和IP地址都无法获得,则判定位域外
+				addr1 = "域外"
+			}
+
 			user, errorcode = U.C.NewLoginRecord3(req.NickName, req.PicUrl, wxMsg.Openid, phoneNumber, wxMsg.SessionKey, addr1, addr2)
 		} else {
 			user, errorcode = U.C.LoginRecord3(req.NickName, req.PicUrl, wxMsg.Openid, phoneNumber, wxMsg.SessionKey)
@@ -150,6 +191,89 @@ func (U *UserController) Login(g *gin.Context) {
 	}
 }
 
+type TencentMapResponse struct {
+	Status  int    `json:"status"`
+	Message string `json:"message"`
+	Result  struct {
+		Address          string `json:"address"`
+		AddressComponent struct {
+			Province string `json:"province"`
+			City     string `json:"city"`
+		} `json:"address_component"`
+	} `json:"result"`
+}
+
+func (U *UserController) getLocationAddr(latitude float64, longitude float64) (string, string) {
+	mapKey := viper.GetString("map_key")
+	mapSk := viper.GetString("map_sk")
+	url := "https://apis.map.qq.com/ws/geocoder/v1"
+	tencentData := TencentMapResponse{}
+	// 构建签名
+	params := map[string]string{
+		"key":      mapKey,
+		"location": fmt.Sprintf("%f,%f", latitude, longitude),
+	}
+	sign := signRequest("/ws/geocoder/v1", params, mapSk)
+
+	// 发送HTTP请求
+	requestURL := fmt.Sprintf("%s?%s&sig=%s", url, buildQueryString(params), sign)
+	response, err := http.Get(requestURL)
+	if err != nil {
+		fmt.Println("Failed to make HTTP request:", err)
+		return "", ""
+	}
+	defer response.Body.Close()
+
+	body, err := ioutil.ReadAll(response.Body)
+	if err != nil {
+		fmt.Println("Failed to read response body:", err)
+		return "", ""
+	}
+
+	//fmt.Println(string(body))
+	err = json.Unmarshal(body, &tencentData)
+	if err != nil {
+		return "", ""
+	}
+
+	province := replaceAddr(tencentData.Result.AddressComponent.Province)
+	city := replaceAddr(tencentData.Result.AddressComponent.City)
+	return province, city
+}
+
+func replaceAddr(data string) string {
+	data1 := strings.Replace(data, "省", "", -1)
+	data2 := strings.Replace(data1, "市", "", -1)
+	return data2
+}
+
+func signRequest(url string, params map[string]string, secretKey string) string {
+	keys := make([]string, 0, len(params))
+	for k := range params {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+
+	var kvPairs []string
+	for _, k := range keys {
+		v := params[k]
+		kvPairs = append(kvPairs, k+"="+v)
+	}
+	joinedParams := strings.Join(kvPairs, "&")
+
+	str := url + "?" + joinedParams + secretKey
+	hash := md5.Sum([]byte(str))
+	return hex.EncodeToString(hash[:])
+}
+
+func buildQueryString(params map[string]string) string {
+	var kvPairs []string
+	for k, v := range params {
+		kvPairs = append(kvPairs, k+"="+v)
+	}
+	return strings.Join(kvPairs, "&")
+}
+
 type jsoninfo struct {
 	Ret  string    `json:"ret"`
 	Ip   string    `json:"ip"`
@@ -157,8 +281,9 @@ type jsoninfo struct {
 }
 
 func (U *UserController) getClientAddr(ipstring string) (string, string) {
-	req, err := http.NewRequest("GET", "https://api.ip138.com/ip/?ip="+ipstring+"&datatype=jsonp", nil)
-	req.Header.Add("token", viper.GetString("addrGetToken"))
+	url := "https://api.ip138.com/ip/?ip=" + ipstring + "&datatype=jsonp"
+	req, err := http.NewRequest("GET", url, nil)
+	req.Header.Add("token", viper.GetString("ip138_token"))
 	C := http.Client{}
 	resp, err := C.Do(req)
 	defer resp.Body.Close()
@@ -394,7 +519,7 @@ func (U *UserController) AdminLogin(g *gin.Context) {
 		errRequest(g, "参数错误", errorcode.PARAMETERERROR)
 		return
 	}
-	if req.Account != "adminuser" || req.Passwd != "hjf16511826666" {
+	if req.Account != "adminuser" || req.Passwd != "jsbsl52666888" {
 		errRequest(g, "账号或密码错误", errorcode.PASSWDERROR)
 		return
 	}

+ 1 - 0
go.mod

@@ -3,6 +3,7 @@ module the12animal
 go 1.16
 
 require (
+	github.com/fatih/structs v1.1.0
 	github.com/fsnotify/fsnotify v1.6.0
 	github.com/gin-gonic/gin v1.8.1
 	github.com/spf13/viper v1.14.0

+ 2 - 0
go.sum

@@ -240,6 +240,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
 github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
 github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
 github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
+github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
+github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
 github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
 github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps=
 github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=

+ 3 - 2
main.go

@@ -1,6 +1,7 @@
 package main
 
 import (
+	"github.com/spf13/viper"
 	"the12animal/configFiles"
 	"the12animal/controllers"
 	"the12animal/models"
@@ -20,10 +21,10 @@ func init() {
 }
 
 func main() {
-	gin.SetMode(gin.ReleaseMode)
+	gin.SetMode(viper.GetString("mode"))
 	r := gin.New()
 	loadRouter(r)
-	r.Run()
+	r.Run("0.0.0.0:" + viper.GetString("port"))
 }
 
 func initController() {

+ 2 - 2
models/user.go

@@ -13,9 +13,9 @@ type User struct {
 	Addr1             string    `gorm:"type:varchar(100)" json:"addr1"`
 	Addr2             string    `gorm:"type:varchar(100)" json:"addr2"`
 	RegisterTime      time.Time `gorm:"type:datetime" json:"register_time"`
+	ResurrectionCount int       `gorm:"type:int;default:1" json:"resurrection_count"`
+	Balance           float32   `gorm:"type:decimal(11,2);default:1000.55" json:"balance"`
 	Sex               int       `json:"sex"`
-	Balance           float32   `json:"balance"`
-	ResurrectionCount int       `json:"resurrection_count"`
 	Resurrection      string    `gorm:"-" json:"resurrection"`
 	LuckUser          bool      `gorm:"-" json:"luck_user"`
 	TodayGameTimes    int       `gorm:"-" json:"today_game_times"`

+ 7 - 1
repository/user.go

@@ -40,9 +40,15 @@ func (U *UserRepository) CreatUser(temp *models.User) *models.User {
 	return temp
 }
 func (U *UserRepository) UpdateUser(temp *models.User) {
-	if err := U.UserDB.SQL.MyDB.Where("id=?", temp.Id).Updates(temp).Error; err != nil {
+	//userMap := structs.Map(temp)
+	result := U.UserDB.SQL.MyDB.Where("id=?", temp.Id).Updates(temp)
+	//sql := result.Statement.SQL.String()
+	//log.Println(sql)
+	if err := result.Error; err != nil {
+		log.Println("==err==", err)
 	}
 }
+
 func (U *UserRepository) GetNotices() []*models.GameNotice {
 	data := make([]*models.GameNotice, 0)
 	if err := U.UserDB.SQL.MyDB.Model(&models.GameNotice{}).Find(&data).Error; err != nil {

+ 1 - 0
router.go

@@ -19,6 +19,7 @@ func loadRouter(engine *gin.Engine, middler ...gin.HandlerFunc) *gin.Engine {
 		game.POST("/login", userController_.Login)
 		game.POST("/balance", userController_.LoginCheck, userController_.Balance)
 		game.POST("/resurrection", userController_.LoginCheck, userController_.RunResurrection)
+		game.POST("/clear_resurrection", userController_.LoginCheck, userController_.ClearResurrectionCount)
 		game.POST("/get_resurrection", userController_.LoginCheck, userController_.GetResurrection)
 		game.POST("/gamemsg", userController_.LoginCheck, userController_.GameMessage2)
 		game.POST("/start", userController_.LoginCheck, userController_.GameStart)

+ 6 - 0
server/user.go

@@ -70,6 +70,12 @@ func (U *UserServer) AddResurrection(Openid string) {
 	U.UserSer.UpdateUser(data)
 }
 
+func (U *UserServer) ClearResurrection(Openid string) {
+	data := U.UserSer.GetUserMsg(Openid)
+	data.ResurrectionCount = 1
+	U.UserSer.UpdateUser(data)
+}
+
 func (U *UserServer) LoginRecord3(NickName, PicUrl, Openid, Phone, SessionKey string) (*models.User, int) {
 
 	data := U.UserSer.GetUserMsg(Openid)