阿里云短信验证码SMS

前言

        将电话以及验证码存入redis,并设置过期时间

一.注册阿里云账号

       注册并登录阿里云账号。您可以前往阿里云官方网站(https://www.aliyun.com/),点击右上角的"登录"按钮,然后选择"注册"创建一个新账号或使用已有的账号登录。

二.开通阿里云短信服务

1.在将鼠标移到阿里云首页目录栏的"产品分类"中,这时会弹出许多阿里云产品,我们选择“云通信”类别下的 “短信服务”。如下图:

2. 点击免费开通,新人也可以在首页中点击免费试用,开通三个月一百条短信服务

 3.开通后点击国内消息,添加先签名,在添加的签名的基础上添加模板,要使签名和模板连接,添加签名后,两小时内阿里会审核,先等待一会吧 

4.开发文档,在首页的文档与社区中

 获取AccessKey ID 和 AccessKey Secret ,在阿里云改版后Secret只在第一次申请显示,请妥善保管

application.properties,将上面的AccessKey ID 和 AccessKey Secret 填入其中,我也连接的redis和nacos,将手机号和验证码存入redis

server.port=8120
spring.application.name=service-duanxin
aliyun.sms.regionId=default
aliyun.sms.accessKeyId=XXXXXXXXXXX
aliyun.sms.secret=XXXXXXXXXXXXXX



#???????? redis?
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.timeout=1800000
spring.redis.jedis.pool.max-active=20
spring.redis.jedis.pool.max-wait=1
spring.redis.jedis.pool.max-idle=5
spring.redis.jedis.pool.min-idle=0



#?? ??? mq ????


#?????? nacos?
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

config类 ,在config中一个短信配置类,一个swagger配置类

package com.lizheng.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author 笑起来跟猫似的先生
 * @ClassName ConstantPropertiesUtils
 * @description: TODO
 * @datetime 2023年 08月 02日 16:16
 * @version: 1.0
 */
@Component
public class ConstantPropertiesUtils implements InitializingBean {

    @Value("${aliyun.sms.regionId}")
    private String regionId;//区域
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;//短信的key
    @Value("${aliyun.sms.secret}")
    private String secret;//短信的密钥



    public static  String REGION_ID;//区域

    public static  String ACCESS_KEY_ID;//短信的key

    public static  String SECRET;//短信的密钥


    @Override
    public void afterPropertiesSet() throws Exception {
        REGION_ID=regionId;
        ACCESS_KEY_ID=accessKeyId;
        SECRET=secret;
    }
}
package com.lizheng.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author 笑起来跟猫似的先生
 * @ClassName SwaggerConfig
 * @description: TODO
 * @datetime 2023年 08月 01日 18:46
 * @version: 1.0
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket creatRestapi(){
        return new Docket(DocumentationType.SWAGGER_2).
                pathMapping("/").
                select().apis(RequestHandlerSelectors.basePackage("com.lizheng")).
                paths(PathSelectors.any()).
                build().apiInfo(new ApiInfoBuilder().title("SpringBoot整合Swagger").description("上班用").
                        version("1.0").contact(new Contact("lizheng","http://www.lizheng.com","lizheng@163.com")).
                        license("The Apache license").licenseUrl("http://www.lizheng.com").build());
    }
}

controller类 

package com.lizheng.controller;

import com.lizheng.result.Result;
import com.lizheng.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 笑起来跟猫似的先生
 * @ClassName SmsApiController
 * @description: TODO
 * @datetime 2023年 08月 02日 16:47
 * @version: 1.0
 */
@Api(tags = "短信测试")
@RestController
@RequestMapping("/api/sms")
@CrossOrigin //跨域
public class SmsApiController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("发送短信")
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){

        //code最终随机生成
        // 创建一个Random对象
        Random random = new Random();
        // 生成一个六位随机数
        String code = String.valueOf(random.nextInt(900000) + 100000);
        // 打印生成的随机数
        System.out.println("随机数:" + code);
        boolean send = smsService.send(phone,code);
        if (send){
            redisTemplate.opsForValue().set("duan_xin:"+phone,code,30, TimeUnit.DAYS);
            return Result.ok();
        }else {
            return Result.error().message("发送短信失败");
        }
    }


}

service

package com.lizheng.service;

import java.util.Map;

/**
 * @author 笑起来跟猫似的先生
 * @ClassName SmsService
 * @description: TODO
 * @datetime 2023年 08月 02日 16:48
 * @version: 1.0
 */

public interface SmsService {
    /**
     * 发送短信
     * @param phone
     * @param code
     * @return
     */
    public boolean send(String phone,String code);

    public boolean send(String phone, String code, Map<String,Object> paramMap);

}

serviceImpl

package com.lizheng.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.lizheng.config.ConstantPropertiesUtils;
import com.lizheng.service.SmsService;
import io.netty.util.Constant;
import com.aliyuncs.http.MethodType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 笑起来跟猫似的先生
 * @ClassName SmsServiceImpl
 * @description: TODO
 * @datetime 2023年 08月 02日 16:52
 * @version: 1.0
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Override
    public boolean send(String phone, String code) {
        if (StringUtils.isEmpty(phone)){
            return false;
        }
        //设置发短信的参数   整合阿里云短信服务
        DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_ID,
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.SECRET);

     /*   IAcsClient client = new DefaultAcsClient(profile);
        //设置固定参数
        CommonRequest  request= new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("");*/

        //设置发短信人的账户相关参数

        //发短信的客户端
        IAcsClient client = new DefaultAcsClient(profile);
        //设置相关的参数
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //发送的手机号
        request.putQueryParameter("PhoneNumbers",phone);
        //签名
        request.putQueryParameter("SignName","阿政的信息");
        //阿里云的模板[短信模板]
        request.putQueryParameter("TemplateCode","SMS_462395064");

        //声明map集合
        Map<String,Object> param= new HashMap<>();
        param.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));//验证码
        System.out.println("快成功了");
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            System.out.println("成功");
            return success;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public boolean send(String phone, String code, Map<String, Object> paramMap) {
        if(StringUtils.isEmpty(phone)){
            return false;
        }

        //设置发短信的参数   整合阿里云短信服务
        DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_ID,
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.SECRET);

     /*   IAcsClient client = new DefaultAcsClient(profile);
        //设置固定参数
        CommonRequest  request= new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("");*/

        //设置发短信人的账户相关参数

        //发短信的客户端
        IAcsClient client = new DefaultAcsClient(profile);
        //设置相关的参数
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //发送的手机号
        request.putQueryParameter("PhoneNumbers",phone);
        //签名
        request.putQueryParameter("SignName","阿政的信息");
        //阿里云的模板[短信模板]
        request.putQueryParameter("TemplateCode","SMS_282785560");

        //声明map集合
     /*   Map<String,Object> param= new HashMap<>();
        param.put("code",code);*/

        Gson gson= new Gson();
        String jsonParam = gson.toJson(paramMap);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(jsonParam));//验证码

        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();

            return success;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue可以使用阿里云短信验证码进行登录,以下是简单的步骤: 1. 在阿里云控制台申请短信服务,并获取Access Key ID和Access Key Secret。 2. 在Vue项目中安装aliyun-sdk依赖:`npm install aliyun-sdk --save`。 3. 在Vue项目中创建一个`aliyunSms.js`文件,用于发送短信验证码。 ```javascript import SMSClient from '@alicloud/sms-sdk' const accessKeyId = 'yourAccessKeyId' const secretAccessKey = 'yourSecretAccessKey' const phoneNumbers = 'yourPhoneNumber' const signName = 'yourSignName' const templateCode = 'yourTemplateCode' const sendSms = (code) => { const smsClient = new SMSClient({accessKeyId, secretAccessKey}) return smsClient.sendSMS({ PhoneNumbers: phoneNumbers, SignName: signName, TemplateCode: templateCode, TemplateParam: JSON.stringify({code}) }) } export default sendSms ``` 4. 在Vue组件中调用`aliyunSms.js`文件中的`sendSms`方法,并将生成的验证码发送到后端进行验证。 ```javascript import sendSms from '@/utils/aliyunSms' export default { data() { return { phone: '', code: '' } }, methods: { sendCode() { // 调用aliyunSms.js中的方法发送短信验证码 sendSms(this.code).then(res => { console.log(res) }).catch(err => { console.log(err) }) }, login() { // 将手机号和验证码发送到后端进行验证 this.$http.post('/login', { phone: this.phone, code: this.code }).then(res => { console.log(res) }).catch(err => { console.log(err) }) } } } ``` 以上是使用阿里云短信验证码进行登录的简单示例。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值