阿里云发送验证码

毕设中用到的短信验证码服务,需要先去阿里云申请服务和验证码模板,我申请了三个模板。。。

阿里云发送验证码_第1张图片

/***阿里云发送验证码***/
	
	
    /**
     * 验证码长度
     */
    private final int codeLength = 6;

    /**
     * 阿里云发送验证码
     *
     * @param phoneNumbers 目标手机号码
     * @param code         验证码
     * @param templateCode 模板代码
     */
    public void sendSMS(String phoneNumbers, String code, String templateCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", PropertiesUtil.getProperty("accessKeyId"), PropertiesUtil.getProperty("accessSecret"));
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "生鲜超市app");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{'code':" + code.toString() + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);

            JSONObject jsonObject = JSONObject.parseObject(response.getData());
            String resCode = jsonObject.getString("Code");
            if ("OK".equals(resCode)) {
                System.out.println(phoneNumbers + "》》》发送验证码成功");
            } else {
                throw new CustomException(100, "发送验证码失败");
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
	
	/**
     * @return 验证码字符串
     * @see
     */
    public String getRandomCode() {

        Random rand = new Random();
        int a;
        String result = "";
        for (int j = 0; j < codeLength; j++) {
            a = Math.abs(rand.nextInt() % 9);
            result += String.valueOf(a);
        }
        return result;
    }

阿里云发送验证码_第2张图片

你可能感兴趣的:(java)