Site Overlay

阿里云短信服务SmsUtil

需求

手机验证码短信发送

导入依赖,此处使用的阿里云的提供的短信服务,所需详细api见阿里云短信服务

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

配置文件 ********.yml,在开通短信服务的页面按照帮助获取

sms:
  accessKeyId: LTAI*********KAkB
  accessSecret: oK89*************zbUKJ3
  SignName: DiuutWeb
  TemplateCode: SMS_*******727
  param: {"code":"[value]"}
# 如果显示param读取失败,把大括号替换成单引号 
# param: '"code":"[value]"'

SmsUtil工具类,使用时@Autowired引入即可自动注入调用并使用

/**
 * @Author Diuut
 * @Date 2020/4/7  12:25
 */
@Component
public class SmsUtil {
    @Value("${sms.accessKeyId}")
    private String accessKeyId;

    @Value("${sms.accessSecret}")
    private String accessKeySecret;

    @Value("${sms.SignName}")
    private String SignName;

    @Value("${sms.TemplateCode}")
    private String TemplateCode;

    @Value("${sms.param}")
    private String paramTemplate;

    public CommonResponse sendSms(String phone, String param) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", SignName);
        request.putQueryParameter("TemplateCode", TemplateCode);
        request.putQueryParameter("TemplateParam", paramTemplate.replace("[value]", param));
        //上面如果大括号替换成了单引号,此处要在参数两头加上大括号。"{"+value+"}"
        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
            return response;
        } catch (ServerException e) {
            e.printStackTrace();
            return null;
        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }
    }
}

发表回复

您的电子邮箱地址不会被公开。

A beliving heart is your magic My heart
欢迎来到Diuut的个人博客,这里是我的一些零零碎碎的知识汇总,希望有能帮到你的内容。 | 蜀ICP备2021011635号-1 | Copyright © 2024 Diuut. All Rights Reserved.