第一步,調(diào)用阿里云Api發(fā)送短信并存入數(shù)據(jù)庫或者是redis當(dāng)中
阿里云短信平臺網(wǎng)址
[https://api.aliyun.com/new#/?product=Dysmsapiversion=2017-05-25api=SendSmsparams={"RegionId":"cn-hangzhou","TemplateCode":"345","PhoneNumbers":"17633802772"}tab=DEMOlang=GO]
使用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層
//發(fā)送手機(jī)驗(yàn)證碼
engine.GET("/api/sendcode",mc.SendSmsCode )
//手機(jī)號和短信登錄
engine.POST("/api/login_sms", mc.smsLogin)
//刪除驗(yàn)證碼
發(fā)送短信
func (mc *MemBerController) SendSmsCode(context *gin.Context) {
phone, err := context.GetQuery("phone")
if !err {
context.JSON(200, map[string]interface{}{
"code": 0,
"message": "手機(jī)號不存在",
})
return
}
ms:=Service.MemberService{}
isSend := ms.Sendcode(phone)//調(diào)用service層方法發(fā)送驗(yàn)證碼
if isSend {
context.JSON(200, map[string]interface{}{
"code":1,
"msg":"發(fā)送成功",
})
}else {
context.JSON(200, map[string]interface{}{
"code": 0,
"msg": "發(fā)送失敗",
})
}
}
service層
func (msi * MemberService)Sendcode(phone string) bool {
//隨機(jī)產(chǎn)生一個(gè)驗(yàn)證碼
code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
smsConfig := config.GetConfig().Sms
//調(diào)用阿里云短信接口發(fā)送短信
//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屬性設(shè)置
request.Scheme = "https"
request.SignName = smsConfig.SignName
request.TemplateCode = smsConfig.TemplateCode
request.PhoneNumbers = phone
//使用json字符串發(fā)送驗(yàn)證碼
par, err := json.Marshal(map[string]interface{}{
"code": code,
})
//設(shè)置驗(yàn)證碼
request.TemplateParam = string(par)
response, err := client.SendSms(request)
fmt.Println( response)
if err != nil {
err.Error()
return false
}
//檢查返回結(jié)果,并判斷發(fā)生狀態(tài)
if response.Code != "OK" {
smsCode := model.SmsCode{Phone: phone, Code: code, BizId: response.BizId, CreateTime: time.Now().Unix()}
//插入數(shù)據(jù)庫操作
memberDao := dao.MemberDao{util.DdEngie}
insertCode := memberDao.InsertCode(smsCode)
return insertCode>0
return true
}
return true
}
Dao層
數(shù)據(jù)庫表結(jié)構(gòu)
//驗(yàn)證碼表結(jié)構(gòu)
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"`
}
//用戶表結(jié)構(gòu)
//用戶類
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
}
//插入數(shù)據(jù)
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
}
驗(yàn)證碼登錄
路由
engine.POST("/api/login_sms", mc.smsLogin)
//短信登錄
func (mc *MemBerController) smsLogin(context *gin.Context) {
var smsParam param.SmsLoginParam
//解析請求參數(shù)
// type SmsLoginParam struct {
// Phone string `json:"phone"`
// Code string `json:"code"`
// }
err := util.Decode(context.Request.Body, smsParam)
if err != nil {
util.Failed(context, "參數(shù)解析錯(cuò)誤")
return
}
//完成手機(jī)加短信的登錄方法
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{}
//查詢封裝的驗(yàn)證碼表結(jié)構(gòu)
sms := dao.ValidateSmsCode(param.Phone, param.Code)
//判斷時(shí)間
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
}
到此這篇關(guān)于go使用Gin框架利用阿里云實(shí)現(xiàn)短信驗(yàn)證碼的文章就介紹到這了,更多相關(guān)go短信驗(yàn)證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- django項(xiàng)目中使用云片網(wǎng)發(fā)送短信驗(yàn)證碼的實(shí)現(xiàn)
- Google Kaptcha 框架實(shí)現(xiàn)登錄驗(yàn)證碼功能(SSM 和 SpringBoot)
- Django 生成登陸驗(yàn)證碼代碼分享
- SpringMvc使用GoogleKaptcha生成驗(yàn)證碼
- Django驗(yàn)證碼的生成與使用示例
- python django 實(shí)現(xiàn)驗(yàn)證碼的功能實(shí)例代碼
- Django自定義插件實(shí)現(xiàn)網(wǎng)站登錄驗(yàn)證碼功能