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]"}

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("${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));
        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
Copyright © 2020 Diuut. All Rights Reserved. | Catch Vogue by Catch Themes