轉載自:https://www.cnblogs.com/zyyhxbs/p/11814942.html
一, 注冊防水牆
1.快速入門文檔
https://cloud.tencent.com/document/product/1110/36839
2.注冊 AppID 和 AppSecret
3.記錄AppID 和 AppSecret
二, 實現功能
1.准備一個觸發的元素,並綁定一個點擊事件
<button class="login_btn" id="TencentCaptcha" @click="get_verify">登錄</button>
2.get_verify
get_verify() {
// 首先用戶名和密碼不能為空 if (!this.username || !this.password) { this.$message.error('用戶名和密碼均不能為空!'); return; } // 首先從后端獲取appId this.$axios.get(`${this.$settings.Host}/users/verify/`).then( response => { // 拿到了appId,構建驗證碼對象 let appId = response.data; let self = this; // 這里其實是給這個元素綁定了一個事件 let tct = new TencentCaptcha(document.getElementById("TencentCaptcha"), appId, function (res) { // 驗證碼的回調函數 if (res.ret === 0) { // 票據 let ticket = res.ticket; let randstr = res.randstr; self.check_verify(ticket, randstr) } } ); // 顯示驗證碼 tct.show() } ).catch(error => { this.$message.error("獲取驗證碼出錯!請聯系管理員!") }) },
3.后端提供appID的代碼
# url: /users/verify/ aid = 'xxxxx' AppSecretKey = 'xxxxx**' class VerifyAPIView(APIView): def get(self, request): return Response(aid, status=status.HTTP_200_OK)
4.check_verify
check_verify(ticket, randstr) {
// 將ticket,randstr發送到后端進行驗證 this.$axios.post(`${this.$settings.Host}/users/verify/`, { 'ticket': ticket, 'randstr': randstr }).then(response => { if (response.status === 200) { // 校驗成功, 進行登錄,這里調用之前寫好的登錄方法 this.login_handler() } else { this.$message.error("校驗失敗!") } }).catch(error => { this.$message.error("校驗驗證碼出錯!請聯系管理員!") }) }
5.后端校驗驗證碼
# 需要安裝reuqests包 def post(self, request): Ticket = request.data.get('ticket') Randstr = request.data.get('randstr') # 上線后這里要進行修改,改為動態獲取請求的ip UserIP = '123.112.18.146' ret = requests.get('https://ssl.captcha.qq.com/ticket/verify', params={ 'aid': aid, 'AppSecretKey': AppSecretKey, 'Ticket': Ticket, 'Randstr': Randstr, 'UserIP': UserIP }) dic = ret.json() if dic and dic.get('response') == '1': return Response('校驗成功!', status=status.HTTP_200_OK) return Response(dic.get('err_msg'), status=status.HTTP_400_BAD_REQUEST)