parent
1a348c5560
commit
6c7fb48b83
3 changed files with 427 additions and 358 deletions
@ -0,0 +1,66 @@ |
||||
package org.springblade.modules.business.sms; |
||||
|
||||
import com.alibaba.fastjson.JSONObject; |
||||
import com.aliyun.dysmsapi20170525.models.SendSmsRequest; |
||||
import com.aliyun.dysmsapi20170525.models.SendSmsResponse; |
||||
import com.aliyuncs.CommonRequest; |
||||
import com.aliyuncs.CommonResponse; |
||||
import com.aliyuncs.DefaultAcsClient; |
||||
import com.aliyuncs.exceptions.ClientException; |
||||
import com.aliyuncs.profile.DefaultProfile; |
||||
import com.aliyuncs.profile.IClientProfile; |
||||
import org.springframework.beans.factory.annotation.Value; |
||||
import org.springframework.stereotype.Component; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
@Component |
||||
public class SmsService { |
||||
|
||||
// 阿里云的Access Key ID和Access Key Secret
|
||||
@Value("${sms.access-key}") |
||||
private static String ACCESS_KEY_ID; |
||||
@Value("${sms.secret-key}") |
||||
private static String ACCESS_KEY_SECRET; |
||||
// 短信签名和模板ID
|
||||
// 短信签名,替换成你在阿里云控制台设置的签名
|
||||
@Value("${sms.sign-name}") |
||||
private static String SIGN_NAME; |
||||
@Value("${sms.template-id1}") |
||||
private static String TEMPLATE_CODE; // 短信模板ID,替换成你在阿里云控制台设置的模板ID
|
||||
|
||||
|
||||
public static void sendSms(String phoneNumber, String name) throws ClientException { |
||||
try { |
||||
// 设置发送短信的相关参数
|
||||
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET); |
||||
DefaultAcsClient client = new DefaultAcsClient(profile); |
||||
|
||||
CommonRequest request = new CommonRequest(); |
||||
|
||||
// 设置短信模板的参数
|
||||
Map<String, String> templateParam = new HashMap<>(); |
||||
templateParam.put("name", name); // 这里的 "code" 是短信模板中的占位符
|
||||
|
||||
request.putQueryParameter("PhoneNumbers", phoneNumber); //手机号
|
||||
request.putQueryParameter("SignName", ""); //申请的签名名称
|
||||
request.putQueryParameter("TemplateCode", ""); //模板名称
|
||||
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(templateParam)); //验证码
|
||||
|
||||
|
||||
// 发送短信请求
|
||||
CommonResponse response = client.getCommonResponse(request); |
||||
|
||||
if (response.getHttpResponse().isSuccess()) { |
||||
System.out.println("短信发送成功!"); |
||||
} else { |
||||
System.out.println("短信发送失败."); |
||||
} |
||||
|
||||
} catch (ClientException e) { |
||||
e.printStackTrace(); |
||||
System.out.println("短信发送异常: " + e.getMessage()); |
||||
} |
||||
} |
||||
} |
||||
Loading…
Reference in new issue