找回密码
 立即注册

springboot3阿里云短信配置 [复制链接]

admin 2025-10-22 21:20:17 39
springboot3阿里云短信配置

1,导入依赖:
  1. <!-- 阿里云短信依赖 -->
  2.         <dependency>
  3.             <groupId>com.aliyun</groupId>
  4.             <artifactId>dysmsapi20170525</artifactId>
  5.             <version>4.2.0</version>
  6.         </dependency>
复制代码
2,配置文件yml
  1. my:
  2.   aliyun:
  3.     accessKeyId: XXXX
  4.     accessKeySecret: XXXX
  5.     signName:
  6.     templateCode: SMS_475130011
复制代码
3,示例代码:
  1. package com.jinhei.common.utils;
  2. import com.aliyun.dysmsapi20170525.Client;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class AliyunSmsUtil {
  7.     @Value("${my.aliyun.accessKeyId}")
  8.     private String accessKeyId;
  9.     @Value("${my.aliyun.accessKeySecret}")
  10.     private String accessKeySecret;
  11.     @Value("${my.aliyun.signName}")
  12.     private String signName;
  13.     @Value("${my.aliyun.templateCode}")
  14.     private String templateCode;
  15.     /**
  16.      * @param phone 电话
  17.      * @param code 验证码
  18.      * @return
  19.      */
  20.     public boolean sendSms(String phone,String code){
  21.         try {
  22.             Client client = createClient(accessKeyId, accessKeySecret);
  23.             com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
  24.                     .setSignName(signName)
  25.                     .setTemplateCode(templateCode)
  26.                     .setPhoneNumbers(phone)
  27.                     .setTemplateParam("{"code":""+code+""}");
  28.             com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
  29.             client.sendSmsWithOptions(sendSmsRequest, runtime);
  30.             return true;
  31.         } catch (Exception e) {
  32.             e.printStackTrace();
  33.             return false;
  34.         }
  35.     }
  36.     /**
  37.      * 使用AK&SK初始化账号Client
  38.      * @param accessKeyId
  39.      * @param accessKeySecret
  40.      * @return Client
  41.      * @throws Exception
  42.      */
  43.     public  Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
  44.         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
  45.                 // 必填,您的 AccessKey ID
  46.                 .setAccessKeyId(accessKeyId)
  47.                 // 必填,您的 AccessKey Secret
  48.                 .setAccessKeySecret(accessKeySecret);
  49.         // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
  50.         config.endpoint = "dysmsapi.aliyuncs.com";
  51.         return new Client(config);
  52.     }
  53. }
复制代码

阿里云配置信息:
游客,如果您要查看本帖隐藏内容请回复


0 回复

发布新话题
搜索
返回顶部