yzk_wechat_event/apps/jqr/serializers.py

75 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import base64
from rest_framework import serializers
from libs.weworkapi.callback.WXBizMsgCrypt3 import WXBizMsgCrypt, Prpcrypt
from utils.tools import sha1_encoder, get_attribute, camel_to_snake
import xml.etree.cElementTree as ET
class WechatPublicTokenSerializer(serializers.Serializer):
msg_signature = serializers.CharField()
echostr = serializers.CharField()
timestamp = serializers.CharField()
nonce = serializers.CharField()
def validate(self, attrs):
corp = self.context.get('corp')
token = corp.token
corpid = corp.corpid
encoding_aes_key = corp.encodingaeskey
msg_signature = attrs.get('msg_signature')
echostr = attrs.get('echostr')
timestamp = attrs.get('timestamp')
nonce = attrs.get('nonce')
# # 1将token、timestamp、nonce, echostr四个参数进行字典序排序
# arr = [token, timestamp, nonce, echostr]
# arr.sort()
# # 2将三个参数字符串拼接成一个字符串进行sha1加密
# data = "".join(arr)
# # 3开发者获得加密后的字符串可与 signature 对比,标识该请求来源于微信
# encode_str = sha1_encoder(data)
wxcpt = WXBizMsgCrypt(token, encoding_aes_key, corpid)
ret, echostr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
if ret != 0:
return {}
attrs['echostr'] = echostr.decode()
return attrs
class WechatEncryptSerializer(serializers.Serializer):
ToUserName = serializers.CharField(write_only=True)
Encrypt = serializers.CharField(write_only=True)
AgentID = serializers.CharField(write_only=True)
def create(self, data):
corp = self.context.get('corp')
encoding_aes_key = corp.encodingaeskey
encrypt = data.get('Encrypt')
xmltext = self.decrypt(encrypt, encoding_aes_key)
data = self.parse_xml(xmltext)
print(data)
return {}
def decrypt(self, encrypt, encoding_key):
try:
key = base64.b64decode(encoding_key + "=")
prpcrypt = Prpcrypt(key)
corpid = ''
res, decrypt = prpcrypt.decrypt(encrypt, corpid)
if res != 0:
return
decrypt = decrypt.decode()
return decrypt
except Exception as e:
print(e)
def parse_xml(self, xmltext):
xml_tree = ET.fromstring(xmltext)
data = {}
for child in xml_tree:
tag = child.tag
key = camel_to_snake(tag)
data[key] = get_attribute(xml_tree.find(key), 'text')
return data