Ali cloud messaging services to achieve access to the phone code

             I get the phone in a domain registration code requirements found in the few online codes can be used directly, and the overall chaotic, while updating the time is relatively long, the opening of local Ali cloud messaging services are a little deviation. So, own a whole finishing process for reference only.

            In order to achieve the first mobile phone to send text messages to verify code verification, to have an interface, so you need to open Ali cloud messaging service, as follows:

               1. Log Ali cloud

                      Ali cloud official website: https://www.aliyun.com/

                      Ali cloud need to have an account, apply for registration, after successful login into the console, and then locate the SMS service.

                        

 

 

              2. Create a signature and templates

                    Came SMS service home page, click Management Console, select the "domestic news" and see right there is the signature management and template management, conduct and create a signature template

                    

 

 

                     Add a signature template as shown, the signature can be the name or function of the site or use of the system can not be too concise, six words above, I've just learned not to test me, oh. It will be used later, and then click OK again and display review. Under normal circumstances three minutes later audit is completed.

                  

 

 

                  To add a template, the template name which is SMS foremost in brackets [] name, usually App name or site name. Template content according to their preferences to the same review as shown below.

 

                  

 

 

         3. Start the actual development, here are tools like code that calls the API:  

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;
public class SendCode {
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "";
    static final String accessKeySecret = "";
    public static SendSmsResponse sendSms(String phone,String code,String templateCode) throws ClientException {
        //可自助调整超时时间
        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("你的签名");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);//短信模板
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\""+code+"\"}");
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");
        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }
}

             需要你改的只有accessKeyId,accessKeySecret和你的签名名称。accessKeyId,accessKeySecret点击头像选中“accessKeyId”点击就会看到,签名就是你申请通过的签名。

 

                                       

 

               4.后台服务调用工具类,可以根据自己的业务逻辑进行更改,这里给出我使用SSM框架在UserController中调用的代码:

                                

@RequestMapping(value = "/sendcode",method = RequestMethod.GET)
    @ResponseBody
    public String sendcode (HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String phone = request.getParameter("phone");
        String code = request.getParameter("code");
        try {
            SendCode.sendSms(phone, code,"你的模板CODE");  
            //调用短信发送接口,三个参数,手机号,验证码,短信模板
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "{\"success\":true,\"flag\":true}";
    }

              5.前端根据自己的实际需要以及喜欢的样式进行开发,这里给出我自己的代码:

    <!--处理发送手机验证码  -->
    <script type="text/javascript">
    var InterValObj; //timer变量,控制时间
    var count = 120; //间隔函数,1秒执行
    var curCount;//当前剩余秒数
    var code = ""; //验证码
    var codeLength = 6;//验证码长度
    function sendMessage() {
        curCount = count;
        var phone=$("#phone").val();//手机号码
        if(phone != ""){
             //产生验证码
            for (var i = 0; i < codeLength; i++) {
                code += parseInt(Math.random() * 9).toString();
            } 
            //设置button效果,开始计时
            $("#btnSendCode").attr("disabled", "true");
            $("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
            InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次
        //向后台发送处理数据
            $.ajax({
                url:'<%=basePath%>user/sendcode',
                type:'GET',
                data:"phone=" + phone + "&code=" + code,
                dataType:'json',
                success:function(json){
                    if(json.flag){
                        alert("发送成功,请注意查收!");
                    }else{
                        alert("发送失败,请重新发送!");
                    }
                },
                error:function(){
                    alert('请求超时或系统出错!');
                }
            });
        }else{
            alert("手机号码不能为空!");
        }
    }
    //timer处理函数
    function SetRemainTime() {
        if (curCount == 0) {                
            window.clearInterval(InterValObj);//停止计时器
            $("#btnSendCode").removeAttr("disabled");//启用按钮
            $("#btnSendCode").val("重新发送验证码");
            code = ""; //清除验证码。如果不清除,过时间后,输入收到的验证码依然有效    
        }
        else {
            curCount--;
            $("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
        }
    }
    
    //处理注册
    function adduser() {
        var checkcode=$("#checkcode").val();
        var username=$("#username").val();
        var phone=$("#phone").val();
        var password=$("#password").val();
        if(checkcode==code){
            $.ajax({
                url:'<%=basePath%>user/addUser',
                type: "POST",
                data:"phone=" + phone + "&username=" + username +"&password=" + password,
                dataType:'json',
                success:function(json){
                    if(json.flag){
                        alert("恭喜你,注册成功!");
                        location.reload();
                    }
                },
                error:function(){
                    alert('请求超时或系统出错!');
                }
            });    
        }
        else{
          alert("注册失败,验证码错误!");
        }
    }
 </script>

                我这里是设置的获取验证码后120秒倒计时并且无法点击,120秒过后Button变成“重新获取”并且可被点击。代码除了工具类自己做了修改,其他纯原创,仅供参考!

               

 

 

 

Guess you like

Origin www.cnblogs.com/yuqingya/p/12013752.html