JAVA调用阿里云发送短信

首先引入POM

  
        
            com.aliyun
            aliyun-java-sdk-core
            4.0.6
        
        
            com.aliyun
            aliyun-java-sdk-dysmsapi
            1.1.0
        
 

代码:



import com.alibaba.fastjson.JSON;
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;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

/**
 * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过
 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可)
 * 工程依赖了2个jar包(存放在工程的libs目录下)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 *
 * 备注:Demo工程编码采用UTF-8
 * 国际短信发送请勿参照此DEMO
 */
public class AliSmsUtil {
    private static final Logger logger = LoggerFactory.getLogger(AliSmsUtil.class);
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "********";//yourAccessKeyId
    static final String accessKeySecret = "********";//yourAccessKeySecret

    //模板ID 可去阿里云自行申请短信模板会生成自定义模板ID
    static final String template_code = "SMS_****";

    //卫龙龙天下
    public static SendSmsResponse sendVerificationCode(String phone,String code) throws ClientException {
        SendSmsResponse sendSmsResponse = null;
        //可自助调整超时时间
        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(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("*****");
        //可选:模板中的变量替换JSON串,如模板内容为尊敬的${name},请您尽快处理!
        Map map = new HashedMap();
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(template_code );
        map.put("code",code);
        request.setTemplateParam(JSON.toJSONString(map));
        //hint 此处可能会抛出异常,注意catch
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            logger.info("==========短信发送====返回码==>"+sendSmsResponse.getCode()+"返回信息==>"+sendSmsResponse.getMessage() );
        }catch (ClientException e){
            e.printStackTrace();
            logger.info("============>短信发送失败"+e.getMessage());
        }finally {
            return sendSmsResponse;
        }
    }

}

 调用方式 发送加redis存储 验证签名可以之定义 UserPhoneCode :

 @Autowired
 private RedisUtils redisUtils;


 String code = StringUtil.numRandom(4);
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = AliSmsUtil.sendVerificationCode(phone, code);
            String status = sendSmsResponse.getCode();
            if ("OK".equals(status)) {
                //将手机号和验证码存入redis,生存时间为1分钟
                redisUtils.setOrigin("UserPhoneCode:" + phone, code, 300);//5*60 5分钟
                log.info("发送验证码设定" + phone + " 有效期为5分钟  验证码:"+code);
            }else {
                throw new CommonException("验证码发送异常:"+sendSmsResponse.getMessage());
            }
        } catch (ClientException e) {
            e.printStackTrace();
            throw new CommonException("验证码发送异常");
        }
        return true;
    }

取验证码比对

 String getRedisCode = (String)redisUtils.getOrigin("UserPhoneCode:" + newPhone);
 log.info("修改手机号应用级别验证码对比: 输入:"+code+ "  redis获取验证码: "+getRedisCode);

你可能感兴趣的:(java,阿里云,开发语言)