package service import ( "encoding/json" "errors" "fmt" "gas-cylinder-api/app/admin/model" "gas-cylinder-api/app/admin/service/dto" "gas-cylinder-api/conf" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "gogs.baozhida.cn/zoie/OAuth-core/pkg/utils" "gogs.baozhida.cn/zoie/OAuth-core/service" "gorm.io/gorm" "net/http" "time" ) type AppletCustomer struct { service.Service } func GetAppletCustomerId(c *gin.Context) string { customerId, exists := c.Get("customer_id") if !exists { return "" } return customerId.(string) } // GetPage 获取Customer列表 func (e *AppletCustomer) Login(c *dto.AppletCustomerLoginReq) (token, expiresAt string, err error) { var data model.Customer url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" appid := conf.ExtConfig.Applet.Appid appSecret := conf.ExtConfig.Applet.AppSecret url = fmt.Sprintf(url, appid, appSecret, c.Code) // 发起请求 res, _ := http.Get(url) // 成功后获取openId wxRes := dto.AppletCustomerLoginResp{} err = json.NewDecoder(res.Body).Decode(&wxRes) if err != nil || wxRes.Openid == "" { return token, expiresAt, errors.New("获取openid失败") } err = e.Orm.Where("principal_phone = ?", c.Phone).First(&data).Error id := data.Id if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { // 添加客户 for { var count int64 id = utils.GetUUID() var i int64 err = e.Orm.Model(&data).Where("id = ?", id).Count(&count).Error if err != nil { continue } if i == 0 { break } } err = e.Orm.Create(&model.Customer{ ProvCustomer: model.ProvCustomer{ Id: id, PrincipalPhone: c.Phone, }, Openid: wxRes.Openid, }).Error } else { return token, expiresAt, errors.New("获取个人信息失败") } } if data.Openid != wxRes.Openid { data.Openid = wxRes.Openid err = e.Orm.Save(&data).Error if err != nil { return token, expiresAt, errors.New("同步个人信息失败") } } token, expiresAt, _ = e.GeneratorToken(id) return token, expiresAt, nil } func (e *AppletCustomer) GeneratorToken(customerId string) (string, string, error) { // 创建一个我们自己的声明 var TokenExpireDuration = time.Second * 24 * 3600 * time.Duration(conf.ExtConfig.Applet.TokenExpire) expiresAt := time.Now().Add(TokenExpireDuration) c := model.CustomerClaims{ customerId, jwt.StandardClaims{ ExpiresAt: expiresAt.Unix(), // 过期时间 Issuer: "customer", // 签发人 }, } // 使用指定的签名方法创建签名对象 token := jwt.NewWithClaims(jwt.SigningMethodHS256, c) // 使用指定的secret签名并获得完整的编码后的字符串token tokenStr, err := token.SignedString(model.AppletCustomerSecret) return tokenStr, expiresAt.Format("2006-01-02 15:04:05"), err }