Java 云片驗(yàn)證碼短信發(fā)送

1.獲取云片APIKEY

登錄云片官網(wǎng):www.yunpian.com 獲取APIKEY

2.查看API文檔

官網(wǎng)首頁 進(jìn)入API文檔頁面


短信分類.png

3.java配置

配置文件中添加

captcha:
      apikey: xxxxxx
      url: https://sms.yunpian.com/v2/sms/single_send.json
      text: 【XXX】親愛的%s,您的驗(yàn)證碼是%s。有效期為%s秒,請盡快驗(yàn)證
      time: 120

4.編寫bean,從配置文件中獲取對應(yīng)參數(shù)

@Component
@ConfigurationProperties(prefix = "spring.captcha")
public class CaptchaConfig {
    private String apikey;
    private String url;
    private String text;
    private String time;

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getApikey() {
        return apikey;
    }

    public void setApikey(String apikey) {
        this.apikey = apikey;
    }
}

5.控制類

@RestController
@RequestMapping("api")
@Api(value = "Message-Api", description = "短信發(fā)送相關(guān)API")
public class CaptchaRestController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private CaptchaConfig captchaConfig;

    /**
     * 發(fā)送短信驗(yàn)證碼
     *
     * @param request 請求參數(shù)
     */
    @RequestMapping(value = "/verification/get", method = RequestMethod.POST)
    @ApiOperation(notes = "發(fā)送短信驗(yàn)證碼", httpMethod = "POST", value = "發(fā)送短信驗(yàn)證碼")
    public Response<HashMap> sendCaptchaMessage(@RequestBody Request<CaptchaGetParam> request) {
        CaptchaGetParam param = request.getParam();
        Response<HashMap> response = new Response<>();
        String mobile = param.getPhone();
        if(!ValidatorUtil.validatorPhone(mobile)){
            response.setResult(ConstantDef.RESPONSE.FAIL);
            response.setMessage("請輸入正確的號碼!");
            response.setData(new HashMap());
            return response;
        }
        String captcha = SmsService.createRandom(Boolean.TRUE, 6);
        try {
            return smsService.sendCaptchaMessage(mobile, captcha);
        } catch (IOException e) {
            response.setResult(ConstantDef.RESPONSE.FAIL);
            response.setMessage("驗(yàn)證碼發(fā)送失??!");
            response.setData(new HashMap());
            return response;
        }

    }
}

6.實(shí)現(xiàn)類

@Service
public class SmsService {
    private static Logger logger = LoggerFactory.getLogger(SmsService.class);
    @Autowired
    private CaptchaConfig captchaConfig;

    public Response<HashMap> sendCaptchaMessage(String phone, String captcha) throws IOException {
        Response<HashMap> response = new Response<>();
        String message = String.format(captchaConfig.getText(), "用戶", captcha, captchaConfig.getTime());
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(captchaConfig.getUrl());
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        post.addParameter("apikey", captchaConfig.getApikey());
        post.addParameter("text", message);
        post.addParameter("mobile", phone);
        int status = httpclient.executeMethod(post);
        String info = new String(post.getResponseBody(), "UTF-8");
        logger.debug(info);
        if(status == 200){
            CacheManager.getInstance().putListener().put(phone, captcha, Long.parseLong(captchaConfig.getTime()));
            response.setResult(ConstantDef.RESPONSE.SUCCESS);
            response.setMessage("驗(yàn)證碼發(fā)送成功!");
            response.setData(new HashMap());
            return response;
        }else {
            JSONObject jsonObject= JSON.parseObject(info);
            response.setResult(ConstantDef.RESPONSE.FAIL);
            response.setMessage((String) jsonObject.get("detail"));
            response.setData(new HashMap());
            return response;
        }

    }


    /**
     * 創(chuàng)建指定數(shù)量的隨機(jī)字符串
     *
     * @param numberFlag 是否是數(shù)字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,699評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,290評論 6 342
  • 對的,還是GTD。 用了將近半年之后,我發(fā)現(xiàn)我到了瓶頸了! 每日都是按部就班的按照清單來工作,可是我發(fā)現(xiàn),我似乎將...
    熙寶愛吃飯閱讀 316評論 1 1
  • 限韓令讓一群萌妹看不到韓國歐巴帥氣的臉龐,奧運(yùn)會(huì)就讓一群女流氓看到了游泳、舉重、體操運(yùn)動(dòng)員的美好肉體……連我家小姑...
    d9e178c49b58閱讀 400評論 0 1

友情鏈接更多精彩內(nèi)容