First, the service access procedure
Second, no sense to verify the backhaul (business application integration)
- Access to the top as the official website, after registering an account login console, access the "no sense of verification" module, the subscription will be assigned a unique AppId, AppSecret.
- When the user slides through codes, generate a service authentication code
token
, the user's service request to bring the codestoken
, then the system call back service SDK to verifytoken
the validity.
|
| 用户业务请求 | ----> | 业务系统 | ----> | | 验证码服务
(请求带上验证码token) | (获取token,调用验证码接口) | | (校验token有效性) |
SDK provides the back-end as the top token to verify the legality of the current version supports JAVA, PHP version, C # version, Python version.
return data validation token api
Field name | type of data | description |
---|---|---|
success | Boolean | Success, true / false |
msg | String | Error Messages |
ip | String | When the token is generated, the client's ip |
code | String | Error code |
Error code Description
code | description |
---|---|
1001 | Wrong APPID |
1002 | Signature error, please check whether correct APPID and APPSECRET |
1003 | illegal or token has expired (token one-time use and is valid for only two minutes) |
1004 | Parameter error, please check the consistent use of the back-end and front-end page whether APPID |
1005 | When an incoming verifyToken ip, verification is not through, ip and operational request generated token that is inconsistent ip |
Third, the back-end implementation
# CaptchaResponse.py (第三方)
class CaptchaResponse:
result = False
serverStatus = ""
def __init__(self, result, serverStatus):
self.result = result
self.serverStatus = serverStatus
def setResult(self, result):
self.result = result
def setServerStatus(self, serverStatus):
self.serverStatus = serverStatus
# CaptchaClient.py (第三方)
from urllib import request
import hashlib
import json
from new.CaptchaResponse import CaptchaResponse
class CaptchaClient:
requestUrl = "https://cap.dingxiang-inc.com/api/tokenVerify"
timeout = 2
response = None
def __init__(self, appId, appSecret):
self.appId = appId
self.appSecret = appSecret
def setTimeOut(self, timeOut):
self.timeout = timeOut
def setCaptchaUrl(self, url):
self.requestUrl = url
def checkToken(self, token):
print(len(token) > 1024)
captchaResponse = CaptchaResponse(False, "")
"""
if (self.appId == "" or (self.appId is None) or self.appSecret == ""
or (self.appSecret is None) or token == "" or (token is None)
or not (len(token) > 1024)):
"""
if (self.appId == "" or (self.appId is None) or self.appSecret == ""
or (self.appSecret is None) or token == "" or (token is None)
or not (len(token) > 205)):
captchaResponse.setServerStatus("参数错误")
return captchaResponse.__dict__
arr = token.split(":")
print(arr)
constId = ""
if len(arr) == 2:
constId = arr[1]
str_key = self.appSecret + arr[0] + self.appSecret
sign = hashlib.md5(str(str_key).encode("utf8")).hexdigest()
req_url = self.requestUrl + '?appKey=' + self.appId + '&token=' + arr[
0] + '&constId=' + constId + "&sign=" + sign
try:
# self.response = urllib2.urlopen(req_url, timeout=self.timeout)
self.response = request.urlopen(req_url, timeout=self.timeout)
# self.response = requests.get(req_url, timeout=self.timeout)
print(self.response.code)
if self.response.code == 200:
result = self.response.read()
result = json.loads(result)
captchaResponse.setServerStatus("SERVER_SUCCESS")
captchaResponse.setResult(result["success"])
else:
captchaResponse.setResult(True)
captchaResponse.setServerStatus("server error: status=" + str(self.response.code))
return captchaResponse.__dict__
except Exception as e:
captchaResponse.setResult(True)
captchaResponse.setServerStatus("server error:" + e)
return captchaResponse.__dict__
finally:
self.close(self.response)
def close(self, response):
try:
if response != None:
response.close()
del response
except Exception as e:
print("close response error:" + e.message)
# TokenDemo.py(自定义测试)
from new.CaptchaClient import CaptchaClient
APP_ID = '693d3ef199e411d0ed62cb2a87d8bdde'
APP_SECRET = '5eea7b131502eece01409d8bd358f0d5'
if __name__ == '__main__':
captchaClient = CaptchaClient(APP_ID, APP_SECRET)
captchaClient.setTimeOut(2)
# 设置超时时间,默认2秒
# captchaClient.setCaptchaUrl("http://cap.dingxiang-inc.com/api/tokenVerify")
# 特殊情况可以额外指定服务器,默认情况下不需要设置
# 只能使用一次
token = 'token:11159D5F8D540AA73D207C5FF53EAD7906F1A01D3D9D63E044F1DBE3CE6FB117ECB81B1038A6755D455A0059164BC0D61462F6D0E55910FA0E27B1BF7F8FDA610512217CBC50B81B3A3DDDD2F0F06CD8:5df10ea2jLv7WP9YbNEIfgn3xFpmnRAMb818FAu1'
print(len(token))
response = captchaClient.checkToken(token)
print(response)
# print("serverStatus", response['serverStatus'])
# 确保验证状态是SERVER_SUCCESS,SDK中有容错机制,在网络出现异常的情况会返回通过
# print(response['result'])
if response.get('result') and response.get('serverStatus') == 'SERVER_SUCCESS':
# token验证通过,继续其他流程
print('成功')
pass
else:
# token验证失败,业务系统可以直接阻断该次请求或者继续弹验证码
print("失败")
pass
Fourth, the front-end application
General Parameters
There are a number of initialization parameter, which appId
is required.
parameter name | Mandatory | Types of | Explanation |
---|---|---|---|
appId | Yes | String | Currently, the only identification of the application |
type | no | String | Type, there is only one option basic , the default value basic . |
style | no | String | Style, The options are (default),embed , , four kinds of specific results can be found online Demo .inline popup oneclick |
inlineFloatPosition | no | String | Layer floating position only when the style value is inline valid, the options are up (by default), down two kinds, specific effects can be found online Demo . |
oneClickFloatPosition | no | string | Layer floating position only when style the value is oneclick valid, there are options up , when the style value oneclick does not pass this parameter, a pop-up defaults. |
width | no | Number | Controls (slider) width, in pixels, default is 300 . |
language | no | String | Language, options are cn (default, Chinese), en (English). |
success | no | Function | Verification successful callback function, it will pass a parameter, the value of this authentication token:constId , the access scheme needs to return this value in subsequent verification. Note: This callback function contains no sense of validation is successful and slide the validation is successful. |
fail | no | Function | Verification callback function fails, it will pass in a parameter, the value of the error message. |
method
Examples of a method comprising the following codes:
reload()
Reset the current codesExample:
myCaptcha.reload()
show()
Displays the current codes.style
Aspopup
the codes are hidden by default, requires access scheme according to the logical page callsshow()
a method to display it.Example:
myCaptcha.show()
hide()
Hide the current codeExample:
myCaptcha.hide()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{# 验证码滑块#}
<script src="https://cdn.dingxiang-inc.com/ctu-group/captcha-ui/index.js"></script>
<style>
.f {
height: 500px;
}
.tan {
width: 600px;
margin: 0 auto;
line-height: 500px;
font: normal 60px 微软雅黑;
text-align: center;
}
.tan:hover {
border-radius: 5px;
border: 1px black solid;
box-shadow: 4px 6px WindowFrame;
}
</style>
</head>
<body>
<div id="c1"></div>
<div class="f">
<div id="btn-popup" class="tan">弹出</div>
</div>
</body>
<script>
var myCaptcha = _dx.Captcha(document.getElementById('c1'), {
{#appId: 'appId', //appId,在控制台中“应用管理”或“应用配置”模块获取#}
appId: '693d3ef199e411d0ed62cb2a87d8bdde',
style: 'popup', // 类型
success: function (token) {
console.log('token:', token);
myCaptcha.hide();
setTimeout(function () {
myCaptcha.reload();
}, 1000);
},
fail: function (error) {
console.log(error);
myCaptcha.reload();
},
});
document.getElementById('btn-popup').onclick = function () {
myCaptcha.show();
}
</script>
</html>