springboot集成阿里云短信验证码

1.添加pom.xml依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.4.6</version>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.1.0</version>
</dependency>

2.application.yml添加配置文件

#短信
sms:
  aliyun:
    accessKeyID: #keyID
    accessKeySecret: #KeySecret秘钥
    domain: dysmsapi.aliyuncs.com #固定
    regionId: cn-hangzhou #固定
    templateCode: #模板code
    signName: #签名名称

3.创建随机验证码工具类

public class RandomUtils {
	 
	private static final String[] ARR = {"0","1","2","3","4","5","6","7","8","9"};
    private static final Random random = new Random();
 
    /**
     * 生成指定长度随机数(数字)
     * @param length 长度
     * @return 验证码
     */
    public static String createRandomInt(int length){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(ARR.length);
            sb.append(ARR[index]);
        }
        return sb.toString();
    }
}

4.创建发送验证码工具类

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
@Component
public class SendSmsUtils {
	private static Logger log = LoggerFactory.getLogger(SendSmsUtils.class);

	//aliyuncs的参数
    private static String accessKeyID;

    private static String accessKeySecret;

    //短信api的请求地址  固定
    private static String domain;

    //指定地域名称 短信API的就是 cn-hangzhou 不能改变
    private static String regionId;

    //您的申请签名
    private static String signName;

    //你的模板
    private static String templateCode;

    /**
     * 发送短信接口
     *
     * @param phoneNum 手机号
     * @return 验证码
     */
    public static String sendSms(String phoneNum) {
    	String code = RandomUtils.createRandomInt(6);

        // 指定地域名称 短信API的就是 cn-hangzhou 不能改变  后边填写您的  accessKey 和 accessKey Secret
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建通用的请求对象
        CommonRequest request = new CommonRequest();
        // 指定请求方式
        request.setSysMethod(MethodType.POST);
        // 短信api的请求地址  固定
        request.setSysDomain(domain);
        //签名算法版本  固定
        request.setSysVersion("2017-05-25");
        //请求 API 的名称
        request.setSysAction("SendSms");
        //指定地域名称
        request.putQueryParameter("RegionId", regionId);
        // 要给哪个手机号发送短信  指定手机号
        request.putQueryParameter("PhoneNumbers", phoneNum);
        // 您的申请签名
        request.putQueryParameter("SignName", signName);
        // 您申请的模板 code
        request.putQueryParameter("TemplateCode", templateCode);

        Map<String, Object> params = new HashMap<>();
        //这里的key就是短信模板中的 ${xxxx}
        params.put("code", code);

        // 放入参数  需要把 map转换为json格式  使用fastJson进行转换
        request.putQueryParameter("TemplateParam", JSON.toJSONString(params));

        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info(JSON.parseObject(response.getData(), Map.class).get("Message").toString());
            if(response.getHttpResponse().isSuccess()) {
            	return code;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String getAccessKeyID() {
		return accessKeyID;
	}
    @Value("${sms.aliyun.accessKeyID}")
	public void setAccessKeyID(String accessKeyID) {
		SendSmsUtils.accessKeyID = accessKeyID;
	}

	public static String getAccessKeySecret() {
		return accessKeySecret;
	}
	@Value("${sms.aliyun.accessKeySecret}")
	public void setAccessKeySecret(String accessKeySecret) {
		SendSmsUtils.accessKeySecret = accessKeySecret;
	}

	public static String getDomain() {
		return domain;
	}
	@Value("${sms.aliyun.domain}")
	public void setDomain(String domain) {
		SendSmsUtils.domain = domain;
	}

	public static String getRegionId() {
		return regionId;
	}
	@Value("${sms.aliyun.regionId}")
	public void setRegionId(String regionId) {
		SendSmsUtils.regionId = regionId;
	}

	public static String getSignName() {
		return signName;
	}
	@Value("${sms.aliyun.signName}")
	public void setSignName(String signName) {
		SendSmsUtils.signName = signName;
	}

	public static String getTemplateCode() {
		return templateCode;
	}
	@Value("${sms.aliyun.templateCode}")
	public void setTemplateCode(String templateCode) {
		SendSmsUtils.templateCode = templateCode;
	}

}

注意事项:在application.yml中配置了accessKeyID等参数,想在一个工具类里面的静态方法使用,于是使用了静态变量。使用@Value注解获取值,如下:

@Value("${sms.aliyun.accessKeyID}")
private static String accessKeyID;

debug发现获取不到,为null。原因如下:

  • spring不允许/不支持把值注入到静态变量中;
  • Spring的@Value依赖注入是依赖set方法;
  • set方法是普通的对象方法;
  • static变量是类的属性,static没有set方法。

 解决办法,把@Value注解放到set方法上,去除set方法static关键字。如下:

//aliyuncs的参数
private static String accessKeyID;

@Value("${sms.aliyun.accessKeyID}")
public void setAccessKeyID(String accessKeyID) {
	SendSmsUtils.accessKeyID = accessKeyID;
}
public static String getAccessKeyID() {
	return accessKeyID;
}

 同时,工具类还需要交给spring管理,在类上添加注解@Component

5.测试

@GetMapping("sms")
public ResponseBo sms(String phone) {
    String code = SendSmsUtils.sendSms(phone);
    System.out.println(code);
    return ResponseBo.ok(code);
}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例,使用Vue实现阿里云短信验证码登录的代码: ``` <template> <div> <input type="tel" v-model="phone" placeholder="请输入手机号码"> <button @click="sendCode" :disabled="isSending">{{ buttonText }}</button> <input type="text" v-model="code" placeholder="请输入验证码"> <button @click="login" :disabled="!code || isLoggingIn">登录</button> </div> </template> <script> import { sendVerificationCode, loginWithVerificationCode } from '@/api/auth' export default { data() { return { phone: '', code: '', isSending: false, isLoggingIn: false, countdown: 60, buttonText: '获取验证码' } }, methods: { async sendCode() { if (!this.phone) { return this.$message.error('请输入手机号码') } this.isSending = true try { await sendVerificationCode(this.phone) this.countdown = 60 this.buttonText = `${this.countdown}秒后重新发送` const timer = setInterval(() => { this.countdown-- this.buttonText = `${this.countdown}秒后重新发送` if (this.countdown === 0) { clearInterval(timer) this.isSending = false this.buttonText = '获取验证码' } }, 1000) } catch (err) { this.isSending = false this.$message.error(err.message) } }, async login() { if (!this.code) { return this.$message.error('请输入验证码') } this.isLoggingIn = true try { await loginWithVerificationCode(this.phone, this.code) this.$message.success('登录成功') // 跳转到首页 } catch (err) { this.isLoggingIn = false this.$message.error(err.message) } } } } </script> ``` 在此示例中,我们使用了 `sendVerificationCode` 和 `loginWithVerificationCode` 两个方法来发送验证码和登录。您需要根据您自己的实际情况来实现这些方法,这些方法通常会与您的后端API进行交互。 此外,您需要在阿里云控制台中创建一个短信模板,并将其与您的应用程序集成。您需要使用阿里云提供的SDK来发送短信验证码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值