go使用Gin框架利用阿里云实现短信验证码功能

时间:2021-08-09 07:45:16

第一步,调用阿里云Api发送短信并存入数据库或者是redis当中

阿里云短信平台网址
[https://api.aliyun.com/new#/?product=Dysmsapi&version=2017-05-25&api=SendSms&params={"RegionId":"cn-hangzhou","TemplateCode":"345","PhoneNumbers":"17633802772"}&tab=DEMO&lang=GO]

使用json配置文件

?
1
2
3
4
5
6
7
8
// 配置文件
 "sms": {
     "sign_name": "虚拟云餐厅",
     "template_code": "SMS_205471746",
     "app_key": "",
     "app_secret": "",
     "region_id": "cn-hangzhou"
 }

配置文件解析

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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层

?
1
2
3
4
5
//发送手机验证码
 engine.GET("/api/sendcode",mc.SendSmsCode )
 //手机号和短信登录
 engine.POST("/api/login_sms", mc.smsLogin)
 //删除验证码

发送短信

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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层

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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.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层

数据库表结构

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//验证码表结构
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"`
    }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
}

验证码登录

路由

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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层

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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层

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//查询语句
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
}

到此这篇关于go使用Gin框架利用阿里云实现短信验证码的文章就介绍到这了,更多相关go短信验证码内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/jmy2333/p/14012999.html