整合redis并完成短信验证服务

  1. 添加依赖

            com.tencentcloudapi
            tencentcloud-sdk-java
            3.1.509

            org.springframework.boot
            spring-boot-starter-data-redis

  1. 修改配置文件添加redis配置
redis:
    key:
      prefix:
        authCode: "protal:authCode"
      expire:
        authCode: 12000 # 验证码过期时间
    jedis:
      pool:
        # 最大连接数
        max-active: 8
        # 最大等待时间
        max-wait: -1ms
        # 连接池最大空闲数
        max-idle: 8
        # 最小空闲数
        min-idle: 0
        # 连接超时时间
    timeout: 3000ms
    host: 192.168.215.137
    port: 6379
    database: 0
  1. 完成短信发送功能和短信验证码验证这里用的腾讯云

controller层

package com.macro.mall.tiny.controller;

import com.macro.mall.tiny.common.CommonResult;
import com.macro.mall.tiny.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author 崔令雨
 * @date 2022/5/19 9:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/sso")
@Api("用户控制")
public class UmsMemberController {
    @Autowired
    private UmsMemberService memberService;

    @PostMapping("getCode/{phone}")
    @ApiOperation("短息获取")
    public CommonResult getCode(@PathVariable String phone) {
        if (StringUtils.isEmpty(phone)) {
            return CommonResult.failed("手机号为空");
        }
        String code = memberService.getCode(phone);
        if (StringUtils.isEmpty(code)) {
            return CommonResult.failed("生成验证码失败");
        }
        return CommonResult.success(code);

    }

    @PostMapping("messageAuthentication/{code}/{phone}")
    public CommonResult messageAuthentication(@PathVariable String code,
                                                    @PathVariable String phone) {

        if (StringUtils.isEmpty(code)) {
            return CommonResult.failed("验证码为空");
        }
        if (StringUtils.isEmpty(phone)) {
            return CommonResult.failed("手机号为空");
        }

        boolean flag = memberService.messageAuthentication(code, phone);

        if (!flag) {
            return CommonResult.failed("验证码错误");
        }
        return CommonResult.success(null);
    }

}

service层
package com.macro.mall.tiny.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.macro.mall.tiny.common.CommonResult;
import com.macro.mall.tiny.mbg.mapper.UmsMemberMapper;
import com.macro.mall.tiny.service.RedisService;
import com.macro.mall.tiny.service.UmsMemberService;
import com.mysql.cj.x.protobuf.MysqlxExpr;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

//导入可选配置类
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;

// 导入对应SMS模块的client
import com.tencentcloudapi.sms.v20210111.SmsClient;

// 导入要请求接口对应的request response类
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;

/**
 * @author 崔令雨
 * @date 2022/5/19 9:15
 * @Version 1.0
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    @Resource
    private UmsMemberMapper umsMemberMapper;

    @Resource
    private RedisService redisService;
    @Value("${spring.redis.key.prefix.authCode}")
    private String PREFIX_AUTHCODE;
    @Value("${spring.redis.key.expire.authCode}")
    private Long EXPIRE_AUTHCODE;

    @Override
    public String getCode(String phone) {
        try {
            /* 必要步骤:
             * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
             * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
             * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
             * 以免泄露密钥对危及你的财产安全。
             * SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi */
            Credential cred = new Credential("AKID1sXx8HF0Wn9IFxQgjX4OVO1PYVEl8IE9",
                    "jEWZOzNXS8vVnrgIiwxkJfmfJyPbaMvF");

            // 实例化一个http选项,可选,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            // 设置代理(无需要直接忽略)
            // httpProfile.setProxyHost("真实代理ip");
            // httpProfile.setProxyPort(真实代理端口);
            /* SDK默认使用POST方法。
             * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */
            httpProfile.setReqMethod("POST");
            /* SDK有默认的超时时间,非必要请不要进行调整
             * 如有需要请在代码中查阅以获取最新的默认值 */
            httpProfile.setConnTimeout(60);
            /* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            /* 非必要步骤:
             * 实例化一个客户端配置对象,可以指定超时时间等配置 */
            ClientProfile clientProfile = new ClientProfile();
            /* SDK默认用TC3-HMAC-SHA256进行签名
             * 非必要请不要修改这个字段 */
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            /* 实例化要请求产品(以sms为例)的client对象
             * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
             * 你可以直接查询SDK源码确定接口有哪些属性可以设置
             * 属性可能是基本类型,也可能引用了另一个数据结构
             * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
            SendSmsRequest req = new SendSmsRequest();

            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
             * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
             * 基本类型的设置:
             * 帮助链接:
             * 短信控制台: https://console.cloud.tencent.com/smsv2
             * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */

            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */
            // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
            String sdkAppId = "1400677751";
            req.setSmsSdkAppId(sdkAppId);

            /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */
            // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
            String signName = "无心java公众号";
            req.setSignName(signName);

            /* 模板 ID: 必须填写已审核通过的模板 ID */
            // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
            String templateId = "1400573";
            req.setTemplateId(templateId);

            /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */
            String code = RandomUtil.randomNumbers(4);

            String[] templateParamSet = {code};
            req.setTemplateParamSet(templateParamSet);

            /* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
             * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */
            phone = "+86" + phone;
            String[] phoneNumberSet = {phone};
            req.setPhoneNumberSet(phoneNumberSet);

            /* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
            String sessionContext = "";
            req.setSessionContext(sessionContext);

            /* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */
            String extendCode = "";
            req.setExtendCode(extendCode);

            /* 国际/港澳台短信 SenderId(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手] */
            String senderid = "";
            req.setSenderId(senderid);

            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
             * 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */
            SendSmsResponse res = client.SendSms(req);

            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(res));

            // 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
            // System.out.println(res.getRequestId());

            /* 当出现以下错误码时,快速解决方案参考
             * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
             */
            String key = PREFIX_AUTHCODE + phone;
            redisService.set(key, code);
            redisService.expire(key, EXPIRE_AUTHCODE);
            return code;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public boolean messageAuthentication(String code, String phone) {
        String key = PREFIX_AUTHCODE + "+86" + phone;

        String phoneCode = redisService.get(key);
        return code.equals(phoneCode);
    }
}

  1. 错误总结:
  2. 因为这里用腾讯云短信服务的时候在手机号前边增加了+86而我的rediskey拼接了这个手机号所以导致后面从验证码取出的时候导致key不一样验证失败 (本人犯的一个小错误)

Original: https://www.cnblogs.com/cuiwnd/p/16287798.html
Author: 01cui
Title: 整合redis并完成短信验证服务

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/715323/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球