@ApiOperation ( "短信发送接口" )
@PostMapping ( "/sendSms" )
public CommonResult< Object> sendSms ( @RequestBody Request< Phone> request) {
if ( request== null|| StringUtil. isBlank ( request. getData ( ) . getPhone ( ) ) ) {
return CommonResult. validateFailed ( ) ;
}
return couUserService. sendSms ( request. getData ( ) . getPhone ( ) ) ;
}
CommonResult< Object> sendSms ( String phone) ;
@Override
public CommonResult< Object> sendSms ( String phone) {
String code= RandomNumberGenerator. getRandomNumber ( ) ;
DefaultProfile profile = DefaultProfile. getProfile ( "cn-hangzhou" , keyId, secret) ;
IAcsClient client = new DefaultAcsClient ( profile) ;
CommonRequest req = new CommonRequest ( ) ;
req. setMethod ( MethodType. POST) ;
req. setDomain ( "dysmsapi.aliyuncs.com" ) ;
req. setVersion ( "2017-05-25" ) ;
req. setAction ( "SendSms" ) ;
req. putQueryParameter ( "RegionId" , "cn-hangzhou" ) ;
req. putQueryParameter ( "PhoneNumbers" , phone) ;
req. putQueryParameter ( "SignName" , "SignName" ) ;
req. putQueryParameter ( "TemplateCode" , smsTemplate) ;
req. putQueryParameter ( "TemplateParam" , "{\"code\":\"" + code+ "\"}" ) ;
CommonResponse response = null;
try {
response = client. getCommonResponse ( req) ;
} catch ( ClientException e) {
log. debug ( "短信发送异常:" + e. getMessage ( ) ) ;
return CommonResult. failed ( "短信发送客户端异常,发送短信失败!" ) ;
}
if ( ! response. getData ( ) . contains ( "OK" ) ) {
return CommonResult. failed ( "发送短信失败!" ) ;
}
if ( redisUtil. set ( phone, code, ( long ) 5000 ) ) {
return CommonResult. success ( code) ;
} else {
return CommonResult. failed ( "操作失败" ) ;
}
}
import java. util. Random;
public class RandomNumberGenerator {
public static String getRandomNumber ( ) {
String code = "" ;
Random random = new Random ( ) ;
for ( int i = 0 ; i < 6 ; i++ ) {
int r = random. nextInt ( 10 ) ;
code = code + r;
}
return code;
}
}