Jiguang sends SMS verification code

Note: Individuals cannot use this function, because personal applications will not be approved

Process introduction

Browse through the creation process in detail. The documentation introduces it in detail.
The parameters that need to be used to call the API afterward are:
APP KEY、MASTER SECRET
Jiguang SMS signature ID, Jiguang verification code SMS ID(Both of these are generated when creating SMS templates)
Jiguang SMS development document
insert image description here
SMS signature explanation :
insert image description here
creation process :
insert image description here

This article realizes sending text verification code SMS and verification code verification
The following is the API that needs to be used

insert image description here
insert image description here
insert image description here

Notice:
这里发生HTTP请求调用,需要采用 HTTP 基本认证的验证方式 做法为,HTTP Header 中加 Authorization: Header 名称是 "Authorization", 值是 base64 转换过的 "appKey:masterSecret"(中间有个冒号)。这两者可以在极光开发者服务的 Web 控制台[应用设置]-[应用信息]中查看。

insert image description here

Code

这里使用hutool工具包发送http请求
hutool sends Http request-HttpRequest
uses hutool toolkit to send HTTP request
depends on:

		<!--Hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.16</version>
        </dependency>

yaml configuration

#极光
jiguang:
  jpush:
    #极光开发APP KEY
    app-key: ""
    #极光开发MASTER SECRET
    master-secret: ""
    #极光短信签名ID
    message-sign-id: ""
    #极光验证码短信ID
    captcha-template-id: ""

Send SMS verification code:

/**
     * 发送手机号验证码
     *
     * @param phoneNumber 解密后的手机号
     * @return 是否成功
     */
    @Override
    public CommonResult<Boolean> sendCaptcha(String phoneNumber) {
    
    
        //判断今天短信验证发送次数是否合规
        if (!captchaInfoService.isCaptchaRequestAvailable(phoneNumber)) {
    
    
            return new CommonResult<>(HttpCode.WRONG_PARAM, "今日发送数量过多", false);
        }

        //发送短信验证码
        String msgId = sendCaptchaNetworkHandler(phoneNumber);
        if (msgId != null) {
    
    
            //设置Redis中对于手机号和msgId的记录
            setRedisRecord(phoneNumber, msgId);
            return new CommonResult<>(HttpCode.SUCCESS, "发送成功", true);
        } else {
    
    
            return new CommonResult<>(HttpCode.INTERNAL_ERROR, "发送失败", false);
        }

    }

    /**
     * 发送手机号验证码
     * 参考文档:https://docs.jiguang.cn/jsms/server/rest_api_jsms#功能说明
     */
    private String sendCaptchaNetworkHandler(String phoneNumber) {
    
    
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile", phoneNumber);
        jsonObject.put("sign_id", JPUSH_MESSAGE_SIGN_ID);
        jsonObject.put("temp_id", JPUSH_CAPTCHA_TEMPLATE_ID);

        //返回msg_id
        String result = HttpRequest.post("https://api.sms.jpush.cn/v1/codes")
                .basicAuth(JPUSH_APP_KEY, JPUSH_MASTER_SECRET)
                .body(jsonObject.toString())
                .timeout(20000)
                .execute().body();

        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson.containsKey(MESSAGE_ID_KEY)) {
    
    
            return resultJson.getString(MESSAGE_ID_KEY);
        } else {
    
    
            return null;
        }

    }

SMS verification code verification (Jiguang provides SMS verification code verification function, but you can also add a layer of redis verification, that is, when sending the verification code, it will be stored in redis and compared when you log in)

/**
     * 获取对应手机号在Redis中的key
     * 举例:CAPTCHA:19825031998:VALUE
     *
     * @return 手机号在Redis中的key
     */
    String getRecordKey(String phone) {
    
    
        return CAPTCHA_RECORD_KEY_PREFIX + phone + CAPTCHA_RECORD_KEY_SUFFIX;
    }

    /**
     * 判断验证码和手机号是否匹配
     * 参考文档: https://docs.jiguang.cn/jsms/server/rest_api_jsms#请求示例-2
     *
     * 因为极光提供了验证码验证api
     * 所以可以不用再在redis中添加对应的phoneNumber和captcha对,
     * 当然也可以写入redis并设置过期时间
     *
     * 如果写入redis则当做判断时可以判断两次,
     * 1.调用极光验证码验证api
     * 2.自己redis中是否有对应的captcha
     *
     * @param captcha     验证码
     * @param phoneNumber 手机号
     * @return 是否正确
     */
    @Override
    public CommonResult<Boolean> checkCaptcha(int captcha, String phoneNumber) {
    
    
        //获取Key
        String recordKey = getRecordKey(phoneNumber);
        //查询手机号对应的验证码ID
        Object queryResult = redisTemplate.opsForValue().get(recordKey);
        //如果为空,说明没有记录,直接返回
        if (queryResult == null) {
    
    
            return new CommonResult<>(HttpCode.WRONG_PARAM, "无发送记录", null);
        }
        //获取msgId的值(注:msg_id 为调用发送验证码 API 的返回值)
        String msgId = String.valueOf(queryResult);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", captcha);

        String result = HttpRequest.post("https://api.sms.jpush.cn/v1/codes/" + msgId + "/valid")
                .basicAuth(JPUSH_APP_KEY, JPUSH_MASTER_SECRET)
                .body(jsonObject.toString())
                .timeout(20000)
                .execute().body();

        JSONObject resultJson = JSONObject.parseObject(result);

        if (resultJson.containsKey(MESSAGE_IS_VALID_KEY)) {
    
    
            return new CommonResult<>(HttpCode.SUCCESS, "成功", resultJson.getBoolean(MESSAGE_IS_VALID_KEY));
        } else {
    
    
            return new CommonResult<>(HttpCode.INTERNAL_ERROR, "内部错误", null);
        }

    }

    @Override
    public Boolean isCaptchaRequestAvailable(String phoneNumber) {
    
    
        //获得每日发送的次数的Redis Key
        Object countQueryObject = redisTemplate.opsForHash().get(CAPTCHA_COUNT_MAP_KEY, phoneNumber);

        //如果是NULL,说明数据库里还没有这个数据,就允许发送
        if (countQueryObject == null) {
    
    
            return true;
        } else {
    
    
            //查询当前已经发送的次数
            int count = Integer.parseInt(String.valueOf(countQueryObject));
            //判断是否查出了最大次数
            return count <= CAPTCHA_MAX_REQUEST_PER_DAY;
        }

    }

See the complete code:
https://gitee.com/xunan29/sms-verification-redis

Guess you like

Origin blog.csdn.net/munangs/article/details/126801411