package services import ( "errors" "fmt" "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi" "github.com/jinzhu/gorm" "lzyd-user-api/common" "lzyd-user-api/models" "lzyd-user-api/utils" ) /** [Mysql]根据手机号及用户输入的验证码去查询数据 */ func GetValidSms(db *gorm.DB, mobile, code string, smsType int) models.ValidSms { var sms models.ValidSms sql := `SELECT sms_id, mobile_phone, valid_code, sms_type, create_at FROM lzyd_sms_valid WHERE mobile_phone = ? AND valid_code = ? AND sms_type = ? ORDER BY create_at DESC LIMIT 1` db.Raw(sql, mobile, code, smsType).Find(&sms) //fmt.Println(1111,sms) return sms } /** [Mysql]根据手机号及用户输入的验证码去查询是否存在用户 */ func GetValidSmsUser (db *gorm.DB, mobile string) models.SmsUser { var smsU models.SmsUser sql := `SELECT mobile_phone,is_delete FROM lzyd_user WHERE mobile_phone = ? AND is_delete = 0` db.Raw(sql, mobile).Find(&smsU) fmt.Println(smsU) return smsU } /** 根据手机号与类型匹配最近的一条短信记录 */ func GetLastValidSms(db *gorm.DB, mobile string, smsType int) models.ValidSms { var sms models.ValidSms sql := "SELECT `sms_id`, valid_code, create_at FROM lzyd_sms_valid WHERE mobile_phone = ? AND sms_type = ? ORDER BY create_at DESC LIMIT 1" db.Raw(sql, mobile, smsType).Find(&sms) return sms } /** 获取每天发送短信的总量 */ func CountOfToday(db *gorm.DB, tableName string) int64 { var count int64 sql := fmt.Sprintf("SELECT COUNT(`sms_id`) FROM %s WHERE create_at > UNIX_TIMESTAMP(CAST(SYSDATE() AS DATE))", tableName) db.Raw(sql).Count(&count) return count } /** 调用模板发送短信 */ func SendSingleSms(mobile string, typ int) (string, error) { random := utils.GenRandomCode() client, err := dysmsapi.NewClientWithAccessKey(common.RegionId, common.AccessKeyId, common.AccessSecret) if err != nil { return "", err } request := dysmsapi.CreateSendSmsRequest() request.Scheme = "http" request.PhoneNumbers = mobile request.SignName = common.SignName request.TemplateCode = common.SmsTemplateCodeMap[typ] request.TemplateParam = "{\"code\": \"" + random + "\"}" response, err := client.SendSms(request) if err != nil { return "", err } if response.Code == "OK" && response.Message == "OK" { return random, nil } return "", errors.New(response.Message) }