SpringBoot整合阿里云短信发送

jupiter
2023-05-02 / 0 评论 / 332 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年05月02日,已超过410天没有更新,若内容或图片失效,请留言反馈。

0.业务场景

短信发送验证码实现注册,登录...

1.开通阿里云短信服务

去到阿里云官方网址:https://www.aliyun.com/ 选择短信服务,在这里能获取到我们需要的4个参数,分别是accessKeyId、accessKeySecret、短信签名、模板code。

2.整合进SpringBoot-方法一(推荐方法二)

2.1导入依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.3.3</version>
</dependency>

2.2 封装成工具类或者服务类

package top.inat.shop.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @program: server
 * @ClassName AliMessageUtil
 * @description: 验证码工具类
 * @author: jupiter
 * @create: 2023-04-23 10:17
 * @Version 1.0
 **/

@Component
public class AliMessageUtil {
    /**
     * 需要配置的参数
     */
    // 阿里云的id和秘钥 从个人中心进行创建
    private static final String accessKeyId="XXXXXXXX";
    private static final String secret="XXXXXXXX";
    //申请的阿里云的签名名称
    private static final String SignName="smile佳"; 
    //申请的阿里云的短信模板code
    private static final String TemplateCode = "SMS_147439706";


    /**
     * 生成6位数字验证码函数
     */
    public static String generateVerifiCode() {
            int n = 6;
            StringBuilder code = new StringBuilder();
            Random ran = new Random();
            for (int i = 0; i < n; i++) {
                code.append(Integer.valueOf(ran.nextInt(10)).toString());
            }
            return code.toString();
        }

    /**
     * 通过阿里云短信发送验证码
     * @param code     验证码
     * @param phone     手机号
     * @return
     */
    public static boolean sendMsmVerifyCode(String phone,String code) {
        //default 地域节点,默认就好  后面是 阿里云的 id和秘钥
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 组装请求对象
        SendSmsRequest request = new SendSmsRequest();

        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName",SignName);
        request.putQueryParameter("TemplateCode", TemplateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
  • 进行测试
 @Test
void aliMessageTest(){
    String code = AliMessageUtil.generateVerifiCode();
    System.out.println("生成的验证码为:"+code);
    String phone = "18673918533";
    boolean sendRes = AliMessageUtil.sendMsmVerifyCode(phone,code);
    System.out.println("短信发送结果:"+sendRes);
}

2.3 运行结果

生成的验证码为:196573
{"Message":"OK","RequestId":"97D16831-6EB8-5300-AF5F-25EC86638C26","Code":"OK","BizId":"405312082956966726^0"}
短信发送结果:true

image-20230502001050082

2.整合进SpringBoot-方法二

2.1导入依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>2.0.9</version>
</dependency>

<!-- fastjson 打印详细的发送返回的结果用的,只看发送成功失败的话可以去掉 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.35</version>
</dependency>

2.2 封装成工具类或者服务类

package top.inat.shop.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @program: server
 * @ClassName AliMessageUtil
 * @description: 验证码工具类
 * @author: jupiter
 * @create: 2023-04-23 10:17
 * @Version 1.0
 **/

@Component
public class AliMessageUtil {
    /**
     * 需要配置的参数
     */
    private static final String accessKeyId="LTAI5t7Lg3SECa8JSvyYrhoj";//这里修改为个人中心生成的AccessKey ID
    private static final String accessKeySecret="AXeyeLFKUU8MkgUSnTj2qTLqnZv2rL";//这里修改为个人中心生成的AccessKey Secret
    private static final String SignName="smile佳"; //申请的阿里云的签名名称
    private static final String TemplateCode = "SMS_147439706"; ////申请的阿里云的短信模板code


    /**
     * 生成6位数字验证码
     */
    public static String generateVerifiCode() {
            int n = 6;
            StringBuilder code = new StringBuilder();
            Random ran = new Random();
            for (int i = 0; i < n; i++) {
                code.append(Integer.valueOf(ran.nextInt(10)).toString());
            }
            return code.toString();
        }

    /**
     * 通过阿里云短信发送验证码
     * @param code     验证码
     * @param phone     手机号
     * @return
     */
    public static boolean sendMsmVerifyCode(String phone,String code) throws Exception {

        Config config = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret).setEndpoint( "dysmsapi.aliyuncs.com");
        Client client = new Client(config);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(SignName);
        request.setTemplateCode(TemplateCode);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        SendSmsResponse response = client.sendSms(request);
        SendSmsResponseBody body = response.getBody();
        System.out.println(JSON.toJSONString(body));//不用fastjson打印结果就注释掉这一行
        if("OK".equals(body.getCode())){
            return true;
        }

        return false;
    }
}
  • 进行测试
 @Test
void aliMessageTest(){
    String code = AliMessageUtil.generateVerifiCode();
    System.out.println("生成的验证码为:"+code);
    String phone = "18673918533";
    boolean sendRes = AliMessageUtil.sendMsmVerifyCode(phone,code);
    System.out.println("短信发送结果:"+sendRes);
}

2.3 运行结果

生成的验证码为:196573
{"Message":"OK","RequestId":"97D16831-6EB8-5300-AF5F-25EC86638C26","Code":"OK","BizId":"405312082956966726^0"}
短信发送结果:true

image-20230502001050082

参考资料

  1. SpringBoot整合阿里云短信服务详细过程(保证初学者也能实现)
  2. SpringBoot集成阿里云短信服务发送短信
  3. 阿里云——Java实现手机短信验证码功能
0

评论 (0)

打卡
取消