可以免费测试的短信验证码接口接入

接入短信验证码之前必须要进行测试,不然接好之后,短信平台不给力,有的重新换平台,增加劳动量还会被老板骂,虽说现在大部分的短信平台都支持测试,但是还得亲自实践一番才能选择最适合自己企业的短信平台

 

此次介绍的验证码接口是以Java开发的,是一个标准http协议的接口,其他的语言都可以接入。

 

首先我们先测试一个速度,有些平台是有两种方式,比如以下介绍的(大多数平台都只有一种方式)

其一:功能测试。直接输入手机号码,发送即可,观看从提交到手机收到验证码所需的时间,判断此平台的验证码相应速度。

其二:接口测试。这是给开发者使用的一个测试环境,开发者在接入之前可以进行接口测试,如果满足自己企业的速度要求,在进行接入即可!

其中接口测试中提到key这个参数,这个参数是注册时自动生成的一个秘钥,查看地址位于首页。注:不同的平台的命名方式不同,展现的位置也是不一样的。

接入之前必须需要设定的几个参数(短信签名、配置模板、单个手机号码日发送量限制、账户每日发送量限制、预警通知联系人号码)

 

短信签名和短信,模板是短信验证码必填项,签名一般是2-6个字,为企业的简称或者是商标简称等,短信模板也就是发送给用户的内容模板。

 

配备完成之后可以进行验证码接口接入,这里分别从前端代码和后端代码提供参考

前端代码

<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
    <!-- 国内使用 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/amazeui/2.7.2/css/amazeui.min.css">
    <script type="text/javascript" charset="utf-8" src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="https://g.alicdn.com/sd/nch5/index.js?t=2015052012"></script>
    <!-- 若您的主要用户来源于海外,请替换使用下面的js资源 -->
    <!-- <script type="text/javascript" charset="utf-8" src="//aeis.alicdn.com/sd/nch5/index.js?t=2015052012"></script> -->
    <style>
        .am-form{
            padding: 10px;
        }
        ._nc .stage1 .slider{
            left: 0;
            right: 0;
        }
    </style>
</head>
<body>
 
<div class="am-form">
    <div class="am-form-group">
        <label for="tel">请输入手机号</label>
        <input type="text" class="" id="tel" placeholder="请输入手机号">
    </div>
 
    <div id="__nc" style="height: 70px">
        <div id="nc"></div>
    </div>
 
    <div class="am-form-group">
        <label for="code">请输入验证码</label>
        <input id="code" type="text" placeholder="请输入验证码">
    </div>
 
    <button type="button" class="am-btn am-btn-primary">提交</button>
</div>
 
<script>
    var nc_token = ["CF_APP_1", (new Date()).getTime(), Math.random()].join(':');
    var nc=NoCaptcha.init({
        renderTo: '#nc',
        appkey: 'CF_APP_1',
        scene: 'register',
        token: nc_token,
        trans: {"key1": "code200"},
        elementID: ["usernameID"],
        is_Opt: 0,
        language: "cn",
        timeout: 10000,
        retryTimes: 5,
        errorTimes: 5,
        inline:false,
        apimap: {
// 'analyze': '//a.com/nocaptcha/analyze.jsonp',
// 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
        },
        bannerHidden:false,
        initHidden:false,
        callback: function (data) {
            window.console && console.log(nc_token)
            window.console && console.log(data.csessionid)
            window.console && console.log(data.sig);
            var tel = $('#tel').val();
            $.ajax({
                url: "sendCode",
                type: "post",
                data: {
                    tel:tel
                },
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        alert("验证码已发送!", "green")
                    } else {
                        alert("发送失败,请稍后再试!");
                        nc.reset()
                    }
                },
                error: function () {
                    alert("系统繁忙,请稍后再试!", "red")
                }
            })
        },
        error: function (s) {
        }
    });
    NoCaptcha.setEnabled(true);
    nc.reset();//请务必确保这里调用一次reset()方法
 
    NoCaptcha.upLang('cn', {
        'LOADING':"加载中...",//加载
        'SLIDER_LABEL': "请向右滑动验证",//等待滑动
        'CHECK_Y':"验证通过",//通过
        'ERROR_TITLE':"非常抱歉,这出错了...",//拦截
        'CHECK_N':"验证未通过", //准备唤醒二次验证
        'OVERLAY_INFORM':"经检测你当前操作环境存在风险,请输入验证码",//二次验证
        'TIPS_TITLE':"验证码错误,请重新输入"//验证码输错时的提示
    });
</script>
</body>
</html>

后端代码

HttpSession session = req.getSession();
    // TODO 验证码有效时间
    session.setMaxInactiveInterval(600);
    try {
      Integer num = RandNumber.getNum();
      // TODO 发送验证码通道
      Sendsms.Send(num, phone);
      session.setAttribute(phone, num);
      return R.ok();
    } catch (Exception e) {
      e.printStackTrace();
      logger.error(e.getMessage());
      return R.error("fasle");
    }
import java.io.Exception;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
 
public class Sendsms {
 
  private static String Url = "https://vip.veesing.com/smsApi/verifyCode";
 
  // 发送短信验证码
  public static void Send(Integer num, String mobile) {
    try {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(Url);
    client.getParams().setContentCharset("UTF-8");
    method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
    NameValuePair[] data = { 
        new NameValuePair("appId", "*********"),
        new NameValuePair("appKey", "**********"), 
        new NameValuePair("templateId", "*******"), 
        new NameValuePair("mobile", "*******"),
        new NameValuePair("variables", "*******") 
        };
    method.setRequestBody(data);
    client.executeMethod(method);
    String submitResult = method.getResponseBodyAsString();
    System.out.println(submitResult);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
}
HttpSession session = req.getSession();
    String yzm = String.valueOf(session.getAttribute(username));
    logger.info(yzm);
    if (yzm == null) {
      return R.error("验证码错误");
    }
    if (yzm != null && !verifycode.equals(yzm)) {
      return R.error("验证码错误");
    }

 

随后附上短信验证码demo

package com.veesing.test; 

import java.io.IOException; 

import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.HttpException; 
import org.apache.commons.httpclient.NameValuePair; 
import org.apache.commons.httpclient.methods.PostMethod; 
import com.alibaba.fastjson.JSONObject; 
import com.veesing.utils.Config; 

/** 
 * 短信验证码 
 * @author MWH 
 * 
 */ 
public class SmsCodeTest { 
    public static void main(String[] args) { 
        // 获取连接 
        HttpClient client = new HttpClient(); 
        // 短信验证码API接口地址 
        PostMethod method = new PostMethod("https://vip.veesing.com/smsApi/verifyCode"); 
        // 设置编码 
        client.getParams().setContentCharset("UTF-8"); 
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=utf-8"); 
        // 手机号码,一次只能提交一个手机号码 
        String phone = "15080929435"; 
        //模板ID(如没有模板ID请先在平台上新增并提交验证码模板,审核通过即可使用) 
        String templateId = "36"; 
        // 验证码变量(随机数) 
        Integer num = (int)((Math.random()*9+1)*1000); 
        String variables = num.toString(); 
        System.out.println("验证码是:"+variables); 
        // 拼接参数 
        NameValuePair[] data = {  
                new NameValuePair("appId", Config.appid),  
                new NameValuePair("appKey", Config.appkey), 
                new NameValuePair("phone", phone),  
                new NameValuePair("templateId", templateId),  
                new NameValuePair("variables", variables) }; 
        method.setRequestBody(data); 
        try { 
            client.executeMethod(method); 
            String result = method.getResponseBodyAsString(); 
            // 返回结果 
            System.out.println(result); 
            JSONObject jsonObject = JSONObject.parseObject(result); 
            // 返回2000则发送成功(逻辑操作请根据接口文档返回参数自行判断) 
            if (jsonObject.get("returnStatus").equals("2000")) { 
                System.out.println("成功!"); 
            } else { 
                System.out.println("失败!"); 
            } 
            // 释放连接 
            method.setRequestHeader("Connection", "close");   
            method.releaseConnection(); 
        } catch (HttpException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值