golang怎么使用Gin框架实现短信验证码功能,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。使用JSON配置文件// 配置文件 "
golang怎么使用Gin框架实现短信验证码功能,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
使用JSON配置文件
// 配置文件 "sms": { "sign_name": "虚拟云餐厅", "template_code": "SMS_205471746", "app_key": "", "app_secret": "", "region_id": "cn-hangzhou" }
配置文件解析
func ParseConfig(path string) (*Config, error) {file, err := os.Open(path)if err != nil {panic(err)}defer file.Close()newReader := bufio.NewReader(file)decoder := json.NewDecoder(newReader)err = decoder.Decode(&config)if err != nil {panic(err)}return config, nil}
编写路由controller层
//发送手机验证码 engine.GET("/api/sendcode",mc.SendSmsCode ) //手机号和短信登录 engine.POST("/api/login_sms", mc.smsLogin) //删除验证码
发送短信
func (mc *MemBerController) SendSmsCode(context *gin.Context) {phone, err := context.GetQuery("phone")if !err {context.JSON(200, map[string]interface{}{"code": 0,"message": "手机号不存在",})return}ms:=Service.MemberService{}isSend := ms.Sendcode(phone)//调用service层方法发送验证码if isSend {context.JSON(200, map[string]interface{}{"code":1,"msg":"发送成功",})}else {context.JSON(200, map[string]interface{}{"code": 0,"msg": "发送失败",})}}
service层
func (msi * MemberService)Sendcode(phone string) bool {//随机产生一个验证码code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))smsConfig := config.GetConfig().Sms//调用阿里云短信接口发送短信 //client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "<accessKeyId>", "<accessSecret>") client, err := dysmsapi.NewClientWithAccessKey(smsConfig.RegionId, smsConfig.AppKey, smsConfig.AppSecret)if err != nil {panic(err)}request := dysmsapi.CreateSendSmsRequest()//request属性设置request.Scheme = "https"request.SignName = smsConfig.SignNamerequest.TemplateCode = smsConfig.TemplateCode request.PhoneNumbers = phone //使用json字符串发送验证码par, err := json.Marshal(map[string]interface{}{"code": code,})//设置验证码request.TemplateParam = string(par)response, err := client.SendSms(request)fmt.Println( response)if err != nil {err.Error()return false}//检查返回结果,并判断发生状态if response.Code != "OK" { smsCode := model.SmsCode{Phone: phone, Code: code, BizId: response.BizId, CreateTime: time.Now().Unix()} //插入数据库操作memberDao := dao.MemberDao{util.DdEngie}insertCode := memberDao.InsertCode(smsCode)return insertCode>0return true}return true}
Dao层
数据库表结构
//验证码表结构type SmsCode struct { Id int64 `xORM:"pk autoincr" json:"id"` Phone string `xorm:"varchar(11)" json:"phone"` BizId string `xorm:"varchar(30)" json:"biz_id"` Code string `xorm:"varchar(4)" json:"code"` CreateTime int64 `xorm:"bigint" json:"create_time"`}//用户表结构//用户类 type Member struct { Id int64 `xorm:"pk autoincr "json:"id"` UserName string `xorm:"varchar(20) "json:"user_name"` Mobile string `xorm:"varchar(11)" json:"mobile"` PassWord string `xorm:"varchar(255)" json:"password"` ReGISterTime int64 `xorm:"bigint" json:"register_time"` Avatar string `xorm:"varchar(255)" json:"avatar"` Balance float64 `xorm:"double" json:"balance"` IsActive int8 `xorm:"tinyint" json:"is_active"` City string `xorm:"varchar(10)" json:"city"` }
type MemberDao struct {* util.Orm}//插入数据func (md *MemberDao) InsertCode(sms model.SmsCode) int64 {one, err := md.InsertOne(&sms)if err != nil {panic(err)}return one}//插入用户func (md *MemberDao) InsertMember(member model.Member) int64 {result, err := md.InsertOne(&member)if err != nil {util.Error(err.Error())}return result}
验证码登录
路由
engine.POST("/api/login_sms", mc.smsLogin)//短信登录func (mc *MemBerController) smsLogin(context *gin.Context) { var smsParam param.SmsLoginParam //解析请求参数 // type SmsLoginParam struct {// Phone string `json:"phone"`// Code string `json:"code"` // }err := util.Decode(context.Request.Body, &smsParam)if err != nil {util.Failed(context, "参数解析错误")return}//完成手机加短信的登录方法us := Service.MemberService{}member := us.SmsLogin(smsParam)if member != nil {util.Success(context, member)return}util.Failed(context, "登录失败")}
service层
func (msi *MemberService) SmsLogin(param param.SmsLoginParam) *model.Member { dao := dao.MemberDao{} //查询封装的验证码表结构sms := dao.ValidateSmsCode(param.Phone, param.Code) //判断时间if sms == nil || time.Now().Unix()-sms.CreateTime > 300 {return nil} //查询用户member := dao.QueryByPhone(param.Phone)if member != nil {return nil}user := model.Member{}user.UserName = param.Phoneuser.Mobile = param.Phoneuser.RegisterTime = time.Now().Unix() user.Id = dao.InsertMember(user) //返回用户return &user}
dao层
//查询语句func (md *MemberDao) ValidateSmsCode(phone string, code string) *model.SmsCode {var sms model.SmsCodeif err := md.Where(" phone = ? and code = ? ", phone, code).Find(&sms); err != nil {util.Error(err.Error())}return &sms}func (md *MemberDao) QueryByPhone(phone string) interface{} {var sms model.Membererr := md.Where("phone=?", phone).Find(&sms)if err != nil {util.Error(err.Error())}return sms}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注编程网GO频道,感谢您对编程网的支持。
--结束END--
本文标题: golang怎么使用Gin框架实现短信验证码功能
本文链接: https://lsjlt.com/news/299474.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-05
2024-04-05
2024-04-05
2024-04-04
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0