本篇文章小编给大家分享一下go使用Gin框架利用阿里云实现短信验证码功能代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
第一步,调用阿里云Api发送短信并存入数据库或者是redis当中
阿里云短信平台网址:https://api.aliyun.com/new#/
使用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", "", " ") 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.SignName request.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>0 return 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.Phone user.Mobile = param.Phone user.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.SmsCode if 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.Member err := md.Where("phone=?", phone).Find(&sms) if err != nil { util.Error(err.Error()) } return sms }