python dajngo+vue 钉钉三方登录群机器人验证码
django+vue实现钉钉群机器人验证码
又是忙碌的一天,今天给大家带来的教程是使用钉钉群机器人发送随机验证码,
在vue中输入然后在后端进行判断并返回相应的返回值,首先我们去看官方文档
然后开始操作
我们需要django+vue跨域 点击查看
一、创建钉钉群机器人
首先明确一点,钉钉自定义机器人早就不支持在手机端创建了,所以打开你的pc端或者mac端的钉钉客户端,在需要机器人的聊天群界面,点击智能群助手
需要注意的是,在安全设置一栏里,我们选择加签的方式来验证,在此说明一下,钉钉机器人的安全策略有三种,第一种是使用关键字,就是说你推送的消息里必须包含你创建机器人时定义的关键字,如果不包含就推送不了消息,第二种就是使用加密签名,第三种是定义几个ip源,非这些源的请求会被拒绝,综合来看还是第二种又安全又灵活。
创建成功后,系统会分配给你一个webhook地址,这个地址需要保存一下,地址中有唯一的accesstoken
ok,那么怎么利用这个地址让你的机器人推送消息呢?查看官方文档
二、测试发送信息
发现文档居然还是python2.0的版本,好吧,我们自己来翻译成3.0
在项目下新建包utils/dindin.py
import time import hmac import hashlib import base64 import urllib.parse import requests, json # 导入依赖库# https://oapi.dingtalk.com/robot/send?access_token=e2e7db9c547beff2f8f93ee06fec87c1a354594045d49fbf30669d7e05b23c38timestamp = str(round(time.time() * 1000)) #这里的secret是我们cp备份的 secret = 'SECc96a44d409036efafe8645c659a551e3ad3ad15bdfd8a408b6254927a2d0d1ca' secret_enc = secret.encode('utf-8') string_to_sign = '{}\n{}'.format(timestamp, secret) string_to_sign_enc = string_to_sign.encode('utf-8') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = urllib.parse.quote(base64.b64encode(hmac_code)) print(sign) # eu4Q16kFubncXuZprXxwRuvDx3Yh/roFWEPn0T5MRPo%3D # print(timestamp) # print(sign)headers = {'Content-Type': 'application/json'} # 定义数据类型 #这里webhook是我们创建成功后 webhook地址 webhook = 'https://oapi.dingtalk.com/robot/send?access_token=e2e7db9c547beff2f8f93ee06fec87c1a354594045d49fbf30669d7e05b23c38×tamp=' + timestamp + "&sign=" + sign# 定义要发送的数据 # "at": {"atMobiles": "['"+ mobile + "']" def dindin_post(text):data = {"msgtype": "text","text": {"content": text},"isAtAll": True}res = requests.post(webhook, data=json.dumps(data), headers=headers) # 发送post请求print(res.text)dindin_post(134235)
测试发送成功
三、创建user(app)
user/models.py
from django.contrib.auth.models import AbstractUser from django.db import models from utils.basemodel import Base# Create your models here.# 用户表 class User(AbstractUser):username = models.CharField(max_length=32, unique=True)password = models.CharField(max_length=132)email = models.CharField(max_length=32, null=True, blank=True)class Meta:db_table = "用户"def __str__(self):return self.username
我们这里重写了django自带的用户表,所以要在settings中重新定义
AUTH_USER_MODEL = 'user.User'
user/views.py
# 解密 from django.contrib.auth.hashers import check_password, make_password # 返回HttpResponse from django.http import HttpResponse # 解码 from django.utils.baseconv import base64 # 返回Response from rest_framework.response import Response # from rest_framework.views import APIView from .models import * import time import hmac import base64 from hashlib import sha256 import urllib import json import requests from utils.dindin import dindin_post import random from rest_framework.permissions import AllowAny import jwt from mydjango import settings# 注册 class RegisterAPIView(APIView):permission_classes = (AllowAny,)def post(self, request):# 获取信息username = request.data.get("username")password = request.data.get("password")try:# 存储数据User.objects.create(username=username, password=make_password(password))return Response({"msg": "ok", "code": 200})except Exception as e:print("user.view--16", e)return Response({"msg": "no", "code": 400})# 登录 class LoginAPIView(APIView):permission_classes = (AllowAny,)def post(self, request):# 获取信息username = request.data.get("username")password = request.data.get("password")user_obj = User.objects.filter(username=username).first()# 判断密码if user_obj:if check_password(password, user_obj.password):# jwt加密encode_jwt = jwt.encode({"uid": user_obj.id}, settings.SECRET_KEY, algorithm='HS256')print(encode_jwt)return Response({"msg": "ok", "code": 200, "token": encode_jwt})else:return Response({"msg": "no", "code": 400})else:return Response({"msg": "no", "code": 400})# 发送验证码 class VerificationAPIView(APIView):permission_classes = (AllowAny,)def get(self, request):# 生成随机验证码6位code = '%06d' % random.randint(0, 999999)# 存储到sessionrequest.session["code"] = code # 存储的也是 key-value 键值对request.session.set_expiry(120) # 设置 session 存活期 单位是秒# 调用钉钉接口 发送验证码dindin_post(code)return Response({"msg": "ok", "code": 200})# 校验验证码 class IsVerificationAPIView(APIView):permission_classes = (AllowAny,)def get(self, request):verification = request.GET.get("verification")code = request.session.get("code")print(code)if verification == code:return Response({"msg": "ok", "code": 200})else:return Response({"msg": "no", "code": 400})
配置子路由user/urls.py
from django.urls import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import * from rest_framework.routers import SimpleRouter, DefaultRouter from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token# ... the rest of your URLconf goes here ... urlpatterns = [# 定义超链接路由# re_path('^static/upload/(?P<path>.*)$',serve,{'document_root':'/static/upload/'}),path('register/', RegisterAPIView.as_view()), # 注册path('mylogin/', LoginAPIView.as_view()), # 登录自定义tokenpath('dindin_url/', DingDingAPIView.as_view()), # 钉钉三方登录路由path('dindin_back/', DingBackApiView.as_view()), # 三方登录回调地址path('verification/', VerificationAPIView.as_view()), # 发送验证码接口path('isverification/', IsVerificationAPIView.as_view()), # 判断验证码接口path('login/', obtain_jwt_token), # 全局token,登录视图 使用djangorestframework-jwt==1.11.0]
配置主路由django/urls.py
from django.urls import path, re_path, includeurlpatterns = [path('user/', include('user.urls')) ]
三、前端vue构建登录注册页面
src/http/apis.js
/* eslint-disable */ // 用户登录 import {get, post, put, del} from './index' export const postRegister = (params, headers) => post("/user/register/", params, headers) export const getVerification = (params, headers) => get("/user/verification/", params, headers) export const getisVerification = (params, headers) => get("/user/isverification/", params, headers) export const postLogin = (params, headers) => post("/user/login/", params, headers) export const postDinDin = (params, headers) => post("/user/dindin_url/", params, headers)
注册页面src/components/register.vue
<template><div><center><h1>用户注册</h1></center><a-form-item label="用户名" v-bind="formlayout"><a-input ref="userNameInput" v-model="username" placeholder="Basic usage"><a-icon slot="prefix" type="user"/><a-tooltip slot="suffix" title="Extra information"><a-icon type="info-circle" style="color: rgba(0,0,0,.45)"/></a-tooltip></a-input></a-form-item><a-form-item label="密码" v-bind="formlayout"><a-input prefix="*" suffix="" v-model="password"/></a-form-item><a-form-item v-bind="buttonlayout"><a-button type="primary" @click="submit">注册</a-button></a-form-item></div> </template><script type="text/javascript">import {postRegister} from "../http/apis";export default {data() {return {username: "",password: "",//表单样式formlayout: {//标签labelCol: {xs: {span: 10},sm: {span: 8}},//文本框wrapperCol: {xs: {span: 10},sm: {span: 3}}},//按钮样式buttonlayout: {//按钮wrapperCol: {xs: {span: 24,offset: 0},sm: {span: 16, offset: 8}}}}},//自定义方法methods: {submit: function () {let params = {username: this.username,password: this.password,}postRegister(params).then(res => {console.log(res)if (res.code == 200) {this.$router.push('/login')} else {alert("失败")}}).catch(err => {console.log(err)})}}};</script><style type="text/css"></style>
登录页面src/components/login.vue
<template><div><center><h1>用户登录</h1></center><a-form-item label="用户名" v-bind="formlayout"><a-input ref="userNameInput" v-model="username" placeholder="Basic usage"><a-icon slot="prefix" type="user"/><a-tooltip slot="suffix" title="Extra information"><a-icon type="info-circle" style="color: rgba(0,0,0,.45)"/></a-tooltip></a-input></a-form-item><a-form-item label="密码" v-bind="formlayout"><a-input prefix="*" suffix="" v-model="password"/></a-form-item><a-form-item label="验证码" v-bind="formlayout"><a-input v-model="verification" @blur="isVerification"/><span v-if="isverification">验证码错误</span><a-button type="primary" @click="clickVerification">点击发送验证码</a-button></a-form-item><a-form-item v-bind="buttonlayout"><a-button type="primary" @click="submit">登录</a-button><img style="margin-left:20px;cursor:pointer;" @click="dingding" src="http://localhost:8000/static/dingding.png"/></a-form-item></div> </template><script type="text/javascript">import {getisVerification, getVerification, postDinDin, postLogin} from "../http/apis";export default {data() {return {selected: "",startdate: "",dinDinUrl: "",username: "",password: "",verification: "",isverification: false,//表单样式formlayout: {//标签labelCol: {xs: {span: 24},sm: {span: 8}},//文本框wrapperCol: {xs: {span: 24},sm: {span: 3}}},//按钮样式buttonlayout: {//按钮wrapperCol: {xs: {span: 24,offset: 0},sm: {span: 16, offset: 8}}}}},//自定义方法methods: {//判断验证码isVerification() {getisVerification({verification: this.verification}).then(res => {console.log(res)if (res.code == 200) {this.isverification = false} else {this.isverification = true}}).catch(err => {console.log(err)})},//发送钉钉验证码clickVerification() {getVerification().then(res => {console.log(res)}).catch(err => {console.log(err)})},//钉钉登录dingding: function () {postDinDin().then(res => {console.log(res)this.dinDinUrl = res.dindin_url//打开新窗口跳转到此地址window.open(res.dindin_url)})},submit: function () {// let just = true;// just = this.isVerification() & just;if (this.isverification === false) {let params = {username: this.username,password: this.password,}//登录postLogin(params).then(res => {console.log(res)if (res.token) {localStorage.setItem("token", res.token)localStorage.setItem("username", res.username)localStorage.setItem("id", res.id)} else {alert("登录失败")}}).catch(err => {console.log(err)})} };</script><style type="text/css"></style>
src/router/index.js
import Vue from 'vue' import Router from 'vue-router' import register from '@/components/register' import login from '@/components/login'Vue.use(Router)var routes = [{path:'/register',name:'register',component:register},{path:'/login',name:'login',component:login},]export default new Router({routes:routes,mode:'history' /*hash*/ })
python dajngo+vue 钉钉三方登录群机器人验证码相关推荐
- 2022.9.17 vue、element-ui实现登录获取手机验证码,进行手机号校验、验证码CD60秒
一.实现效果: 1.直接点击,不为空校验 2.输入手机号格式不正确时 3.获取完验证码进行读秒 二.页面html <el-formclass="phone-form"ref= ...
- vue项目web前端登录页数字验证码 登录流程
1.创建code.js文件夹下面是js代码 function GVerify(options) {console.log(); // 创建一个图形验证码对象,接收options对象为参数this.co ...
- Python钉钉报警及Zabbix集成钉钉报警
钉钉报警设置 创建群机器人 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手. 很多已经做案例的人,却不知道如何去学习更加高深的知识. 那 ...
- 钉钉企业机器人outgoing功能实现(超详细)
第一次做,遇到了很多问题,都不知道从何开始,主要是没一个清晰的思路 ,闲话不多说,直入主题 目录 1.创建企业机器人 1.1钉钉创建团队 1.2创建企业机器人 1.3登陆钉钉开放平台 1.4钉钉企业机 ...
- 用钉钉接收zabbix告警
现在很多企业都在使用钉钉,如果用钉钉接收zabbix告警会不会很方便呢,而且钉钉现在有一个群机器人,使调用api异常简单 添加钉钉群机器人 选择自定义机器人 输入机器人名字 获取API 上传zabbi ...
- A072_前台登录_三方登录
目录 内容介绍 1. 前台登录-账号登录 1.1.前台登录 1.2.axios携带token-common.js 1.3.axios后置处理后台拦截错误-common.js 1.4.前台登录拦截-co ...
- Python实现微信自动拉群机器人
微信群的用户添加逻辑是 -- 当群人数达到100人后,用户无法再通过扫描群二维码加入,只能让用户先添加群内联系人微信,再由联系人把用户拉进来.这样,联系人员的私人微信会添加大量陌生人,给其带来不必要的 ...
- 兄弟们,就是干 微信三方登录绝对干货
微信第三方登录绝对干货 课程介绍 1. 用户登录-账号登录;(掌握) 2. 三方登录概述;(理解) 3. 三方登录协议-Oauth2.0;(了解) 4. 三方登录选择-微信三方登录;(掌握) ...
- 企业微信机器人脚本python_Python 操控企业微信群机器人
目标 企业微信群机器人常用来作为通知工具,群发消息给群内成员,充当小助手的角色.但若按照官方 API 文档来构建请求,也确实不太方便.本文通过 Python 第三方库来控制企业微信群机器人发送消息. ...
最新文章
- 华为北大等打造的Transformer竟在CV上超过CNN
- ca证书 linux 导入_CA搭建与证书申请
- Android加速度传感器
- 【youcans 的 OpenCV 例程 200 篇】112. 滤波反投影重建图像
- Qt学习笔记-简单的UDP广播包聊天室
- 牛客练习赛9 F - 珂朵莉的约数
- 电子政务互联互通软件平台的体系架构
- 嘘——2021还没对象?你的虚拟女友已上线。
- 【SpringCloud系列】 分布式事务-LCN
- 新版Google工具栏(For Firefox)发布
- Oracle两行数据相减
- python熊猫图案_熊猫备忘单–适用于数据科学的Python
- 深度操作系统deepin 20.9 正式发布!
- STM32F103ZET6开发板实现跑马灯实验
- 【教程】小米手机Android 7.0+抓取HTTPS请求安装Charles证书主要流程
- 工控触摸屏IC读卡一体机
- stm32入门开发板选野火还是正点原子好,哪个的视频讲到好一点?
- 前端面试系列-输入url后全过程页面渲染机制DOM生成过程
- Surface 3 重做系统官方步骤
- 高级信息系统项目管理师资料分享