maven :中的 pom.xml添加

<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.6</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>

/******  上面的是JAR包  *******/

package com.atguigu.crud.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

public class ALYmessage {
//产品名称:云通信短信API产品,开发者无需替换
static final String product=”Dysmsapi”;
//产品域名,开发者无需替换
static final String domain = “dysmsapi.aliyuncs.com”;

// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找),下面举个例子
static final String accessKeyId = “accessKeyId”;
static final String accessKeySecret = “accessKeySecret”;

//短信控制台中的签名和模板的ID
static final String signName =”XXXX”;
static final String templateCode =”SMS_XXXXXXXXX”;

/**
* 阿里云短信验证
* @param phonenumber 手机号码
* @param code 4~6位的验证码
* @return
* @throws ClientException
*/
public static SendSmsResponse sendSms(String phonenumber,String code) throws ClientException{
//可自助调整超时时间
System.setProperty(“sun.net.client.defaultConnectTimeout”, “10000”);
System.setProperty(“sun.net.client.defaultReadTimeout”, “10000”);
//初始化acsClient,暂不支持region化
IClientProfile profile=DefaultProfile.getProfile(“cn-hangzhou”, accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint(“cn-hangzhou”, “cn-hangzhou”, product, domain);
IAcsClient acsClient=new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request=new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(phonenumber);
//必填:短信签名-可在短信控制台中找到举个例子
request.setSignName(signName);
//必填:短信模板id-可在短信控制台中找到,是id不是名字,举个例子
request.setTemplateCode(templateCode);
//可选:模板中的变量替换JSON串,如模板内容为”亲爱的${name},您的验证码为${code}”时,此处的值为–必填,与模板相对应
//request.setTemplateParam(“{\”name\”:\”Tom\”, \”code\”:\”123\”}”);
request.setTemplateParam(“{\”code\”:\””+code+”\”}”);
SendSmsResponse sendSmsResponse=acsClient.getAcsResponse(request);
return sendSmsResponse;
}
}

/*************/

public Map<String,Object> testShow(@RequestBody Map<String,Object> reqbody) throws ClientException{
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyyMMddHHmmssS”);

//获取 100000~999999 中的随机数
int flag = new Random().nextInt(899999)+100000;

//获取时间格式没有其他符号只有数字
String dateNowStr = sdf.format(d);

//转换为字符串
String code=flag +””;

//调用封装好的代码,进行发送短信
SendSmsResponse response = ALYmessage.sendSms(reqbody.get(“phonenumber”).toString(),code);

//返回成功

if(response.getCode() != null && response.getCode().equals(“OK”)) {
reqbody.put(“type”, “ok”);
return reqbody;
}
reqbody.put(“type”, “fail”);
return reqbody;
}

版权声明:本文为wang1222原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/wang1222/p/10594526.html