1,在相关的app应用目录中创建geetest.py 文件,文件内容如下:
1 import sys 2 import random 3 import json 4 import requests 5 import time 6 from hashlib import md5 7 8 if sys.version_info >= (3,): 9 xrange = range 10 11 VERSION = "3.0.0" 12 13 14 # 极验验证模块 15 class GeetestLib(object): 16 FN_CHALLENGE = "geetest_challenge" 17 FN_VALIDATE = "geetest_validate" 18 FN_SECCODE = "geetest_seccode" 19 20 GT_STATUS_SESSION_KEY = "gt_server_status" 21 22 API_URL = "http://api.geetest.com" 23 REGISTER_HANDLER = "/register.php" 24 VALIDATE_HANDLER = "/validate.php" 25 JSON_FORMAT = False 26 27 def __init__(self, captcha_id, private_key): 28 self.private_key = private_key 29 self.captcha_id = captcha_id 30 self.sdk_version = VERSION 31 self._response_str = "" 32 33 def pre_process(self, user_id=None, new_captcha=1, JSON_FORMAT=1, client_type="web", ip_address=""): 34 """ 35 验证初始化预处理. 36 //TO DO arrage the parameter 37 """ 38 status, challenge = self._register(user_id, new_captcha, JSON_FORMAT, client_type, ip_address) 39 self._response_str = self._make_response_format(status, challenge, new_captcha) 40 return status 41 42 def _register(self, user_id=None, new_captcha=1, JSON_FORMAT=1, client_type="web", ip_address=""): 43 pri_responce = self._register_challenge(user_id, new_captcha, JSON_FORMAT, client_type, ip_address) 44 if pri_responce: 45 if JSON_FORMAT == 1: 46 response_dic = json.loads(pri_responce) 47 challenge = response_dic["challenge"] 48 else: 49 challenge = pri_responce 50 else: 51 challenge = " " 52 if len(challenge) == 32: 53 challenge = self._md5_encode("".join([challenge, self.private_key])) 54 return 1, challenge 55 else: 56 return 0, self._make_fail_challenge() 57 58 def get_response_str(self): 59 return self._response_str 60 61 def _make_fail_challenge(self): 62 rnd1 = random.randint(0, 99) 63 rnd2 = random.randint(0, 99) 64 md5_str1 = self._md5_encode(str(rnd1)) 65 md5_str2 = self._md5_encode(str(rnd2)) 66 challenge = md5_str1 + md5_str2[0:2] 67 return challenge 68 69 def _make_response_format(self, success=1, challenge=None, new_captcha=1): 70 if not challenge: 71 challenge = self._make_fail_challenge() 72 if new_captcha: 73 string_format = json.dumps( 74 {'success': success, 'gt': self.captcha_id, 'challenge': challenge, "new_captcha": True}) 75 else: 76 string_format = json.dumps( 77 {'success': success, 'gt': self.captcha_id, 'challenge': challenge, "new_captcha": False}) 78 return string_format 79 80 def _register_challenge(self, user_id=None, new_captcha=1, JSON_FORMAT=1, client_type="web", ip_address=""): 81 if user_id: 82 register_url = "{api_url}{handler}?gt={captcha_ID}&user_id={user_id}&json_format={JSON_FORMAT}&client_type={client_type}&ip_address={ip_address}".format( 83 api_url=self.API_URL, handler=self.REGISTER_HANDLER, captcha_ID=self.captcha_id, user_id=user_id, 84 new_captcha=new_captcha, JSON_FORMAT=JSON_FORMAT, client_type=client_type, ip_address=ip_address) 85 else: 86 register_url = "{api_url}{handler}?gt={captcha_ID}&json_format={JSON_FORMAT}&client_type={client_type}&ip_address={ip_address}".format( 87 api_url=self.API_URL, handler=self.REGISTER_HANDLER, captcha_ID=self.captcha_id, 88 new_captcha=new_captcha, JSON_FORMAT=JSON_FORMAT, client_type=client_type, ip_address=ip_address) 89 try: 90 response = requests.get(register_url, timeout=2) 91 if response.status_code == requests.codes.ok: 92 res_string = response.text 93 else: 94 res_string = "" 95 except: 96 res_string = "" 97 return res_string 98 99 def success_validate(self, challenge, validate, seccode, user_id=None, gt=None, data='', userinfo='', 100 JSON_FORMAT=1): 101 """ 102 正常模式的二次验证方式.向geetest server 请求验证结果. 103 """ 104 if not self._check_para(challenge, validate, seccode): 105 return 0 106 if not self._check_result(challenge, validate): 107 return 0 108 validate_url = "{api_url}{handler}".format( 109 api_url=self.API_URL, handler=self.VALIDATE_HANDLER) 110 query = { 111 "seccode": seccode, 112 "sdk": ''.join(["python_", self.sdk_version]), 113 "user_id": user_id, 114 "data": data, 115 "timestamp": time.time(), 116 "challenge": challenge, 117 "userinfo": userinfo, 118 "captchaid": gt, 119 "json_format": JSON_FORMAT 120 } 121 backinfo = self._post_values(validate_url, query) 122 if JSON_FORMAT == 1: 123 backinfo = json.loads(backinfo) 124 backinfo = backinfo["seccode"] 125 if backinfo == self._md5_encode(seccode): 126 return 1 127 else: 128 return 0 129 130 def _post_values(self, apiserver, data): 131 response = requests.post(apiserver, data) 132 return response.text 133 134 def _check_result(self, origin, validate): 135 encodeStr = self._md5_encode(self.private_key + "geetest" + origin) 136 if validate == encodeStr: 137 return True 138 else: 139 return False 140 141 def failback_validate(self, challenge, validate, seccode): 142 """ 143 failback模式的二次验证方式.在本地对轨迹进行简单的判断返回验证结果. 144 """ 145 if not self._check_para(challenge, validate, seccode): 146 return 0 147 validate_result = self._failback_check_result( 148 challenge, validate, ) 149 return validate_result 150 151 def _failback_check_result(self, challenge, validate): 152 encodeStr = self._md5_encode(challenge) 153 if validate == encodeStr: 154 return True 155 else: 156 return False 157 158 def _check_para(self, challenge, validate, seccode): 159 return (bool(challenge.strip()) and bool(validate.strip()) and bool(seccode.strip())) 160 161 def _md5_encode(self, values): 162 if type(values) == str: 163 values = values.encode() 164 m = md5(values) 165 return m.hexdigest()
2,在对应的app应用下的 view.py 文件中,编写代码:
1 from rest_framework.views import APIView 2 from .geetest import GeetestLib #导入极验的的类 3 # 极验验证码登录验证 4 from utils.make_code import make_login_token # 生成随机数的函数 5 from new_pay.settings import APP_ID, APP_KEY # 极验验证的 APP_ID 和 APP_KEY 6 from django.http import HttpResponse 7 8 9 from django.core.cache import cache 10 11 12 class VerifyCode(APIView): 13 permission_classes = [] 14 15 def get(self, request): 16 user_id = make_login_token(length=6) 17 gt = GeetestLib(APP_ID, APP_KEY) #将极验官网的 APP_ID和APP_KEY 传入极验的类中 18 status = gt.pre_process(user_id) 19 cache.set(gt.GT_STATUS_SESSION_KEY, status) # 将相关数据存入cache中 20 cache.set('user_id', user_id) 21 # request.session[gt.GT_STATUS_SESSION_KEY] = status 22 # request.session["user_id"] = user_id 23 data = gt.get_response_str() 24 return HttpResponse(data) 25 26 def post(self, request): 27 """校验验证码""" 28 gt = GeetestLib(APP_ID, APP_KEY) 29 challenge = request.data.get(gt.FN_CHALLENGE, '') 30 validate = request.data.get(gt.FN_VALIDATE, '') 31 seccode = request.data.get(gt.FN_SECCODE, '') 32 # status = request.session[gt.GT_STATUS_SESSION_KEY] 33 # user_id = request.session["user_id"] 34 status = cache.get(gt.GT_STATUS_SESSION_KEY) # 从缓存中取出数据校验 35 user_id = cache.get('user_id') 36 if status: 37 result = gt.success_validate(challenge, validate, seccode, user_id) 38 else: 39 result = gt.failback_validate(challenge, validate, seccode) 40 return Response(result) 41
3,结束!