springboot3阿里云短信配置
1,导入依赖:
- <!-- 阿里云短信依赖 -->
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>dysmsapi20170525</artifactId>
- <version>4.2.0</version>
- </dependency>
复制代码 2,配置文件yml
- my:
- aliyun:
- accessKeyId: XXXX
- accessKeySecret: XXXX
- signName:
- templateCode: SMS_475130011
复制代码 3,示例代码:
- package com.jinhei.common.utils;
-
- import com.aliyun.dysmsapi20170525.Client;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
-
- @Component
- public class AliyunSmsUtil {
-
- @Value("${my.aliyun.accessKeyId}")
- private String accessKeyId;
- @Value("${my.aliyun.accessKeySecret}")
- private String accessKeySecret;
- @Value("${my.aliyun.signName}")
- private String signName;
- @Value("${my.aliyun.templateCode}")
- private String templateCode;
-
- /**
- * @param phone 电话
- * @param code 验证码
- * @return
- */
- public boolean sendSms(String phone,String code){
- try {
- Client client = createClient(accessKeyId, accessKeySecret);
-
- com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
- .setSignName(signName)
- .setTemplateCode(templateCode)
- .setPhoneNumbers(phone)
- .setTemplateParam("{"code":""+code+""}");
- com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
-
- client.sendSmsWithOptions(sendSmsRequest, runtime);
-
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 使用AK&SK初始化账号Client
- * @param accessKeyId
- * @param accessKeySecret
- * @return Client
- * @throws Exception
- */
- public Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
- com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
- // 必填,您的 AccessKey ID
- .setAccessKeyId(accessKeyId)
- // 必填,您的 AccessKey Secret
- .setAccessKeySecret(accessKeySecret);
- // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
- config.endpoint = "dysmsapi.aliyuncs.com";
- return new Client(config);
- }
-
-
- }
复制代码
阿里云配置信息:
|