Browse Source

优化代码

Administrator 2 years ago
parent
commit
b1bbcc136c
7 changed files with 180 additions and 93 deletions
  1. 69 41
      configs/config.go
  2. 17 7
      configs/config.yaml
  3. 8 7
      data/dao/Userdao.go
  4. 40 0
      router/PayRouter.go
  5. 6 6
      router/UserRouter.go
  6. 38 30
      share/json.go
  7. 2 2
      user/UserRouter.go

+ 69 - 41
configs/config.go

@@ -1,10 +1,14 @@
 package configs
 
 import (
+	"crypto/rsa"
 	"fmt"
 	"github.com/go-redis/redis/v8"
 	_ "github.com/go-sql-driver/mysql"
+	"github.com/spf13/cast"
 	"github.com/spf13/viper"
+	"github.com/wechatpay-apiv3/wechatpay-go/utils"
+	"log"
 	"os"
 	"xorm.io/xorm"
 )
@@ -13,46 +17,48 @@ var (
 	Config  *viper.Viper
 	Engine  *xorm.Engine
 	RedisDb *redis.Client
+	WxPay   WxPayConfig
 )
 
-type User struct {
-	Id            int64  `xorm:"'id'" json:"id"`
-	Username      string `xorm:"'username'" json:"username"`
-	Password      string `xorm:"'password'" json:"password"`
-	Creation_time int    `xorm:"'creation_time'" json:"creation_Time"`
-	Login_time    int    `xorm:"'login_time'" json:"login_Time"`
-	Status        int    `xorm:"'status'" json:"status"`
-	Role_id       int    `xorm:"'role_id'" json:"role_id"`
-	Phone         string `xorm:"'phone'" json:"phone"`
-	Email         string `xorm:"'email'" json:"email"`
-	Name          string `xorm:"'name'" json:"name"`
-	Avatar        string `xorm:"'avatar'" json:"avatar"`
-	RecommendCode string `xorm:"'recommend_code'" json:"recommend_code"`
-}
-
-func (receiver User) String() string {
-	return fmt.Sprintf("User{Id:%d, Username:%s, Password:%s, Creation_time:%d, Login_time:%d, Status:%d, Role_id:%d, Phone:%s, Email:%s, Name:%s, Avatar:%s, RecommendCode:%s}", receiver.Id, receiver.Username, receiver.Password, receiver.Creation_time, receiver.Login_time, receiver.Status, receiver.Role_id, receiver.Phone, receiver.Email, receiver.Name, receiver.Avatar, receiver.RecommendCode)
-}
-
-type Role struct {
-	Id        int    `xorm:"'id'" json:"id"`
-	Role_name string `xorm:"'role_name'" json:"role_Name"`
-}
-type Role_authority struct {
-	Authority_id int `xorm:"'authority_id'" json:"authority_id"`
-	Role_id      int `xorm:"'role_id'" json:"role_id"`
-}
-type Authority struct {
-	Id             int    `xorm:"'id'" json:"id"`
-	Authority_name string `xorm:"'authority_name'" json:"authority_Name"`
-	Authority_path string `xorm:"'authority_path'" json:"authority_Path"`
-}
-type MysqlData struct {
-	User           `xorm:"extends"`
-	Role           `xorm:"extends"`
-	Role_authority `xorm:"extends"`
-	Authority      `xorm:"extends"`
-}
+//type User struct {
+//	Id            int64  `xorm:"'id'" json:"id"`
+//	Username      string `xorm:"'username'" json:"username"`
+//	Password      string `xorm:"'password'" json:"password"`
+//	Creation_time int    `xorm:"'creation_time'" json:"creation_Time"`
+//	Login_time    int    `xorm:"'login_time'" json:"login_Time"`
+//	Status        int    `xorm:"'status'" json:"status"`
+//	Role_id       int    `xorm:"'role_id'" json:"role_id"`
+//	Phone         string `xorm:"'phone'" json:"phone"`
+//	Email         string `xorm:"'email'" json:"email"`
+//	Name          string `xorm:"'name'" json:"name"`
+//	Avatar        string `xorm:"'avatar'" json:"avatar"`
+//	RecommendCode string `xorm:"'recommend_code'" json:"recommend_code"`
+//}
+//
+//func (receiver User) String() string {
+//	return fmt.Sprintf("User{Id:%d, Username:%s, Password:%s, Creation_time:%d, Login_time:%d, Status:%d, Role_id:%d, Phone:%s, Email:%s, Name:%s, Avatar:%s, RecommendCode:%s}", receiver.Id, receiver.Username, receiver.Password, receiver.Creation_time, receiver.Login_time, receiver.Status, receiver.Role_id, receiver.Phone, receiver.Email, receiver.Name, receiver.Avatar, receiver.RecommendCode)
+//}
+//
+//type Role struct {
+//	Id        int    `xorm:"'id'" json:"id"`
+//	Role_name string `xorm:"'role_name'" json:"role_Name"`
+//}
+//type Role_authority struct {
+//	Authority_id int `xorm:"'authority_id'" json:"authority_id"`
+//	Role_id      int `xorm:"'role_id'" json:"role_id"`
+//}
+//type Authority struct {
+//	Id             int    `xorm:"'id'" json:"id"`
+//	Authority_name string `xorm:"'authority_name'" json:"authority_Name"`
+//	Authority_path string `xorm:"'authority_path'" json:"authority_Path"`
+//}
+//
+//type MysqlData struct {
+//	User           `xorm:"extends"`
+//	Role           `xorm:"extends"`
+//	Role_authority `xorm:"extends"`
+//	Authority      `xorm:"extends"`
+//}
 
 func ConfigInit() {
 	//获取项目的执行路径
@@ -84,10 +90,10 @@ func ConfigInit() {
 
 	Config = config
 	fmt.Println("xorm 数据库orm框架初始化成功")
+	PayConfigInit()
 }
 func ConfigInitByUrl(configUrl string) {
 	//获取项目的执行路径
-
 	config := viper.New()
 
 	config.AddConfigPath(configUrl + "\\configs") //设置读取的文件路径
@@ -108,11 +114,33 @@ func ConfigInitByUrl(configUrl string) {
 		Password: "",                                                                       // Redis密码,如果没有则为空字符串
 		DB:       0,                                                                        // 使用默认DB
 	})
-	//开启debug模式
 
 	Config = config
 	fmt.Println("xorm 数据库orm框架初始化成功")
 }
-func GoGormConfigInit() {
 
+type WxPayConfig struct {
+	MchID                      string
+	MchCertificateSerialNumber string
+	MchAPIv3Key                string
+	PrivateKey                 *rsa.PrivateKey
+}
+
+func (w WxPayConfig) String() string {
+	return fmt.Sprintf("MchID:%s, MchCertificateSerialNumber:%s, MchAPIv3Key:%s",
+		w.MchID, w.MchCertificateSerialNumber, w.MchAPIv3Key)
+}
+
+// PayConfigInit 微信支付配置
+func PayConfigInit() {
+	WxPay.MchID = cast.ToString(Config.Get("pay.wx.mchID"))
+	WxPay.MchCertificateSerialNumber = cast.ToString(Config.Get("pay.wx.mchCertificateSerialNumber"))
+	WxPay.MchAPIv3Key = cast.ToString(Config.Get("pay.wx.mchAPIv3Key"))
+	var err error
+	WxPay.PrivateKey, err = utils.LoadPrivateKeyWithPath(cast.ToString(Config.Get("pay.wx.mchPrivateKeyPath")))
+	if err != nil {
+		//load merchant private key error =>加载商户私钥错误
+		log.Fatal("load merchant private key error")
+	}
+	fmt.Println("wx_pay 微信支付配置初始化成功")
 }

+ 17 - 7
configs/config.yaml

@@ -1,9 +1,19 @@
 mysql:
-    host: localhost
-    port: "3306"
-    user: root
-    password: "root"
-    database: virtual_mall
+  host: localhost
+  port: "3306"
+  user: root
+  password: "root"
+  database: virtual_mall
 redis:
-    host: localhost
-    port: "6379"
+  host: localhost
+  port: "6379"
+pay:
+  wx:
+    # 商户号
+    mchID: "1"
+    # 商户证书序列号
+    mchCertificateSerialNumber: "2"
+    # 商户APIv3密钥
+    mchAPIv3Key: "3"
+    # 密钥路径
+    mchPrivateKeyPath: "/path/to/merchant/apiclient_key.pem"

+ 8 - 7
data/dao/Userdao.go

@@ -3,14 +3,15 @@ package dao
 import (
 	"crypto/md5"
 	"demo/configs"
+	"demo/data/domain"
 	"demo/share"
 	"fmt"
 	"math/big"
 	"strconv"
 )
 
-func Logins(username, password, t string) (configs.User, error) {
-	user := configs.User{}
+func Logins(username, password, t string) (domain.User, error) {
+	user := domain.User{}
 	var err error
 	fmt.Println("username", username, "password", password)
 	hash := md5.New()
@@ -28,7 +29,7 @@ func Logins(username, password, t string) (configs.User, error) {
 	if err == nil {
 		return user, err
 	}
-	return configs.User{}, err
+	return domain.User{}, err
 }
 func SendSms(matched bool, username string) string {
 	mins := big.NewInt(100000)
@@ -45,7 +46,7 @@ func SendSms(matched bool, username string) string {
 	return randomNum.String()
 }
 
-func SaveNewUser(user configs.User) (configs.User, error) {
+func SaveNewUser(user domain.User) (domain.User, error) {
 	insert, err := configs.Engine.Table("user").Insert(user)
 	if err != nil {
 		return user, err
@@ -58,7 +59,7 @@ func SaveNewUser(user configs.User) (configs.User, error) {
 	return user, nil
 }
 func GetUserByPhoneOrEmail(phone, email string) (bool, error) {
-	var user = configs.User{}
+	var user = domain.User{}
 	_, err := configs.Engine.Select("id").Where("phone = ?", phone).Or("email = ?", email).Get(&user)
 	if err != nil {
 		fmt.Println("err:", err)
@@ -86,8 +87,8 @@ func Md5_KKC(str string) string {
 	return fmt.Sprintf("%x", hash.Sum(nil))
 }
 
-func SetName(id int, newName string) (configs.User, error) {
-	user := configs.User{}
+func SetName(id int, newName string) (domain.User, error) {
+	user := domain.User{}
 	_, err := configs.Engine.Table("user").Where("id = ?", id).Get(&user)
 	if err != nil {
 		return user, err

+ 40 - 0
router/PayRouter.go

@@ -0,0 +1,40 @@
+package router
+
+import (
+	"context"
+	"demo/configs"
+	"github.com/wechatpay-apiv3/wechatpay-go/core"
+	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
+	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
+	"log"
+)
+
+func main() {
+	ctx := context.Background()
+	// 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
+	opts := []core.ClientOption{
+		option.WithWechatPayAutoAuthCipher(configs.WxPay.MchID, configs.WxPay.MchCertificateSerialNumber, configs.WxPay.PrivateKey, configs.WxPay.MchAPIv3Key),
+	}
+	client, err := core.NewClient(ctx, opts...)
+	if err != nil {
+		log.Fatalf("new wechat pay client err:%s", err)
+	}
+	// 以 Native 支付为例
+	svc := native.NativeApiService{Client: client}
+	// 发送请求
+	resp, result, err := svc.Prepay(ctx,
+		native.PrepayRequest{
+			Appid:       core.String("wxd678efh567hg6787"),
+			Mchid:       core.String("1900009191"),
+			Description: core.String("Image形象店-深圳腾大-QQ公仔"),
+			OutTradeNo:  core.String("1217752501201407033233368018"),
+			Attach:      core.String("自定义数据说明"),
+			NotifyUrl:   core.String("https://www.weixin.qq.com/wxpay/pay.php"),
+			Amount: &native.Amount{
+				Total: core.Int64(100),
+			},
+		},
+	)
+	// 使用微信扫描 resp.code_url 对应的二维码,即可体验Native支付
+	log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
+}

+ 6 - 6
router/UserRouter.go

@@ -125,7 +125,7 @@ func GetUserInfo(c *gin.Context) {
 		c.JSON(200, CreateResultError(401, "用户未登录"))
 		return
 	}
-	var userInfo = configs.User{}
+	var userInfo = domain.User{}
 	_, err = configs.Engine.Table("user").Where("id = ?", claims["iss"]).Get(&userInfo)
 	if err != nil {
 		c.JSON(200, CreateResultError(401, "用户未登录"))
@@ -220,7 +220,7 @@ func VerificationCode(c *gin.Context) {
 
 func login(c *gin.Context) {
 	data := share.GetJsonAnyParam(c)
-	var user configs.User
+	var user domain.User
 	var err error
 	username, _ := data("username")
 	password, _ := data("password")
@@ -371,12 +371,12 @@ func register(c *gin.Context) {
 	}
 
 	timestamp := time.Now().Unix()
-	user := configs.User{
+	user := domain.User{
 		Username:      cast.ToString(username),
 		Password:      cast.ToString(password),
-		Creation_time: int(timestamp),
-		Status:        0,
-		Role_id:       2,
+		CreationTime:  timestamp,
+		Status:        "0",
+		RoleId:        2,
 		Phone:         cast.ToString(phone),
 		Email:         cast.ToString(username),
 		Name:          cast.ToString(username),

+ 38 - 30
share/json.go

@@ -2,7 +2,6 @@ package share
 
 import (
 	"crypto/rand"
-	"demo/configs"
 	"errors"
 	"fmt"
 	"github.com/dgrijalva/jwt-go"
@@ -75,37 +74,46 @@ func ParseToken(tokenString string) (jwt.MapClaims, error) {
 		return nil, err
 	}
 }
-func JwtMiddleware() gin.HandlerFunc {
-	return func(c *gin.Context) {
-		tokenString := c.GetHeader("auth-sign")
-		if tokenString == "" {
-			c.JSON(401, gin.H{"message": "缺少token"})
-			c.Abort()
-			return
-		}
-
-		token, err := ParseToken(tokenString)
 
-		if err != nil {
-			c.JSON(401, gin.H{"message": "无效令牌"})
-			c.Abort()
-			return
-		}
-		users := make([]configs.MysqlData, 0)
-		bools, err := configs.Engine.Table("user").Join("INNER", "role", "role.id = user.role_id").Join("INNER", "role_authority", "role_authority.authority_id = role.id").Join("INNER", "authority", "authority.id = role_authority.authority_id").Where("authority.authority_path=?", c.Request.URL.Path).Where("user.id = ?", token["iss"]).Exist(&users)
-		if err == nil {
-			fmt.Println(bools)
-			if bools {
-				c.Next()
-			} else {
-				c.JSON(200, gin.H{"message": "权限不足"})
-				c.Abort()
-				return
-			}
-		}
+//权限判断,废弃
+//func JwtMiddleware() gin.HandlerFunc {
+//	return func(c *gin.Context) {
+//		tokenString := c.GetHeader("auth-sign")
+//		if tokenString == "" {
+//			c.JSON(401, gin.H{"message": "缺少token"})
+//			c.Abort()
+//			return
+//		}
+//
+//		token, err := ParseToken(tokenString)
+//
+//		if err != nil {
+//			c.JSON(401, gin.H{"message": "无效令牌"})
+//			c.Abort()
+//			return
+//		}
+//		users := make([]configs.MysqlData, 0)
+//		bools, err := configs.Engine.Table("user").
+//			Join("INNER", "role", "role.id = user.role_id").
+//			Join("INNER", "role_authority", "role_authority.authority_id = role.id").
+//			Join("INNER", "authority", "authority.id = role_authority.authority_id").
+//			Where("authority.authority_path=?", c.Request.URL.Path).
+//			Where("user.id = ?", token["iss"]).
+//			Exist(&users)
+//		if err == nil {
+//			fmt.Println(bools)
+//			if bools {
+//				c.Next()
+//			} else {
+//				c.JSON(200, gin.H{"message": "权限不足"})
+//				c.Abort()
+//				return
+//			}
+//		}
+//
+//	}
+//}
 
-	}
-}
 func RandomInt(min, max *big.Int) *big.Int {
 	// 读取密码学安全的随机比特
 	byteLen := (max.BitLen() + 7) / 8

+ 2 - 2
user/UserRouter.go

@@ -68,7 +68,7 @@ package user
 //
 //func login(c *gin.Context) {
 //	data := share.GetJsonAnyParam(c)
-//	var user configs.User
+//	var user domain.User
 //	var err error
 //	username, _ := data("username")
 //	password, _ := data("password")
@@ -219,7 +219,7 @@ package user
 //	}
 //
 //	timestamp := time.Now().Unix()
-//	user := configs.User{
+//	user := domain.User{
 //		Username:      cast.ToString(username),
 //		Password:      cast.ToString(password),
 //		Creation_time: int(timestamp),