first commit

This commit is contained in:
jefferyzhao
2025-07-31 17:39:37 +08:00
commit 9565e29ae0
24 changed files with 701 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

8
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 数据源本地存储已忽略文件
/dataSources/
/dataSources.local.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/

18
.idea/enterprise-wechat-payment-push.iml generated Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="Flask">
<option name="enabled" value="true" />
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Jinja2" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/enterprise-wechat-payment-push.iml" filepath="$PROJECT_DIR$/.idea/enterprise-wechat-payment-push.iml" />
</modules>
</component>
</project>

3
1.py Normal file
View File

@ -0,0 +1,3 @@
from utils import *
from FuiouPay import H5Main
add_payment({'pay_amount': 0.01, 'id': '520103200111013211', 'sh': '0001000F7152040', 'base_company': '1', 'name': '王治轶', 'transaction_id': '2024112022001473261446621310', 'payment_items': '承包金', 'pay_type': '支付宝支付'},)

53
FuiouPay.py Normal file
View File

@ -0,0 +1,53 @@
import json
from datetime import datetime
import requests
from Crypto.PublicKey import RSA
import base64
from Crypto.Cipher import PKCS1_v1_5
# 使用公钥加密
def rsa_long_encrypt(public_key,msg, length=100):
"""
单次加密串的长度最大为 (key_size/8)-11
1024bit的证书用100 2048bit的证书用 200
"""
pub_key = RSA.importKey(open(public_key).read())
# pub_key = RSA.importKey(open('E:/YinJian/银建支付对接维护说明/富友/fy-enterprise-wechat-payment-push/pub_key.pem').read())
pubobj = PKCS1_v1_5.new(pub_key)
res = []
for i in range(0, len(msg), length):
res.append(pubobj.encrypt(msg[i:i + length].encode('GBK')))
return base64.b64encode(b"".join(res)).decode('GBK')
class H5Main:
def __init__(self, sub_mchnt_cd):
self.mchnt_cd = "0001000F7152279"
self.sub_mchnt_cd = sub_mchnt_cd
self.url = 'https://aggpcpay.fuioupay.com/aggh5Gate.fuiou'
self.notify_url = "http://web.jiyuankeshang.com/api4/paymentCallBack"
self.page_notify_url = "http://web.jiyuankeshang.com/api4/page_notify"
# self.notify_url = "http://172.16.6.15:3006/paymentCallBack"
def unified_order(self, order_no, total, description):
param = {
"mchnt_cd": self.mchnt_cd,
"sub_mchnt_cd": self.sub_mchnt_cd,
"order_date": datetime.now().strftime("%Y%m%d"),
"order_id": order_no,
"order_amt": total,
"page_notify_url": self.page_notify_url,
"back_notify_url": self.notify_url,
"ver": "4.0.0",
"goods_name": "云学堂年费",
"goods_detail": description,
"fee_type": "CNY",
}
pub_key_location = 'pub_key.pem'
# pub_key_location = 'E:\YinJian\银建支付对接维护说明\技培\jp-enterprise-wechat-payment-push\pub_key.pem'
print("======================发起支付====================",param)
# 加密
message = json.dumps(param)
encrypted_message = rsa_long_encrypt(pub_key_location,message,100)
return json.dumps({"message": encrypted_message})

0
README.md Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

42
config.py Normal file
View File

@ -0,0 +1,42 @@
'''
coding:utf-8
@Time:2023/3/28 5:02 PM
@Author:dyq
'''
# 调用域名
base_path = 'https://www.jiyuankeshang.com'
# 企微应用id 应用ID
corpid = 'wweb8b852846334c2f'
SECRET = 'MPa5NNk5SpE51CWrJEr6CkjWOzcpUxA_oIMC47bmj5c'
agentid = '1000005'
# 商户号
#mchid = '1640957093'
# APIv3密钥
v3_SECRET = '87568e2507acb94056e7310c9c2ab9d5'
# 服务器IP
ip = '101.43.208.145'
# 商户号证书序列号
#serial_no = '22E0F3EA849ABD1E687C82D43D26190C46DA5834'
# 未收付应用id
pay_app = '66e3dd31d396a07cd2c0974b'
# # 已收表单Id
received_id = '659af2d8771e971c583622ac'
# # 未收表单Id
uncollected_id = '66e412f9d396a07cd2c2662d'
# # 充值明细
pay_details_id = '66e412f9d396a07cd2c2662d'
# # 个人账户
accout_id = '6600d0ebcdefd20d64271f9c'
# 增减项app
hz_app = '66e3dd31d396a07cd2c0974b'
# 增减项表单
hz_id = '65a1b20255499f701ee7eee3'
# 合同信息表单
ht_id = '66e3e1f4d396a07cd2c0e663'
# apikey
apikey = '82bl1lhsgjzhd9ahBYvaMNVAncYYRkbE'
# 辅助表单(查询驾驶员身份证号)
fu_app = '628eeaace7f28c00089a60cc'
fu_id = '64685d55e6051a000edad530'
rule_sort = {"收预收承包金": 0, "承包金": 1, "调度费": 2, "保养费": 3, "费税收取-其他": 4}

143
jpapp.py Normal file
View File

@ -0,0 +1,143 @@
from flask import Flask, request, redirect, abort, session, jsonify, url_for
from utils import *
from FuiouPay import H5Main
# from WXPay import WXPay
import os, _thread, urllib
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
CORS(app, supports_credentials=True)
@app.route('/queryUser', methods=['GET'])
def queryUserApi():
# 获取支付明细
try:
id = request.args.get('user')
data = queryUser(id)
print("===================", data)
return data
except Exception as e:
return {}
@app.route('/page_notify', methods=['POST'])
@cross_origin()
def pageNotify():
"""处理 POST 请求并重定向为 GET 请求到 /redirect"""
try:
# 使用 303 See Other 状态码,将 POST 请求转换为 GET 请求的重定向
return redirect('/redirect', code=303)
except Exception as e:
print(f"Error occurred: {e}")
return jsonify({"error": "Internal Server Error"}), 500
@app.route('/redirect', methods=['GET'])
@cross_origin()
def redirectApi():
"""处理 GET 请求并重定向到外部 URL"""
try:
# 处理 GET 请求并重定向到外部 URL
return redirect('https://www.jiyuankeshang.com/f/66e412f9d396a07cd2c2662f', code=302)
except Exception as e:
print(f"Error occurred: {e}")
return jsonify({"error": "Internal Server Error"}), 500
@app.route('/getPaymentDetails', methods=['GET'])
def getPaymentDetails():
try:
id = request.args.get('user', '')
id = id.replace(" ", "")
if not id:
print("no id")
return {}
data = query_pay_details(id)
return data
except Exception as e:
print(e)
return {}
@app.route('/paymentCallBack', methods=['POST'])
def paymentCallBack():
# 充值成功后回调 {"pay_amount": 20000, "id": "18515367096"}
try:
print("====================================paymentCallBack=========================================")
msg = request.data.decode('UTF-8')
print("回调参数为====", msg)
msg = eval(msg)
print("eval参数为====", msg)
if msg['resp_desc'] == '成功':
print("=================================充值回调SUCCESS==========================================")
# rsa_key = RSA.importKey(open('priv_key.pem').read())
rsa_key = RSA.importKey(open('E:\YinJian\银建支付对接维护说明\DP\DP-enterprise-wechat-payment-push\priv_key.pem').read())
print("msg===",msg['message'])
print(rsa_key)
whp = rsa_long_decrypt(rsa_key, msg['message'])
print("报文已解密", whp)
whp_dict = json.loads(whp)
# 打印字典中的所有键
print("1111111",whp_dict.keys())
# 获取'order_id'键的值并取前18个字符
id = whp_dict['order_id'][:18]
# 查询机构、分司
res = filter_jdy_ht(id)
transaction_id = whp_dict['pay_ssn']
amount = float(whp_dict['order_amt'])
order_pay_type = whp_dict['order_pay_type']
# 判断支付类型
if order_pay_type[:2] == "We":
pay_type = "微信支付"
elif order_pay_type[:3] == "Ali":
pay_type = "支付宝支付"
elif order_pay_type == "0000000000":
pay_type = "云闪付支付"
else:
pay_type = "企微支付"
amount = amount / 100
payment_items = "承包金"
print("充值回调处理",{"pay_amount": amount, "id": id,
"sh": res[1], "base_company": res[0], "name": res[2], "transaction_id": transaction_id, "payment_items": payment_items, "pay_type": pay_type})
_thread.start_new_thread(add_payment, ({"pay_amount": amount, "id": id,
"sh": res[1], "base_company": res[0], "name": res[2], "transaction_id": transaction_id, "payment_items": payment_items, "pay_type": pay_type},))
return {"code": 200}
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/test', methods=['POST'])
def test():
# 新增未收付明细 {"pay_amount": 20000, "id": "18515367096"}
try:
data = request.data.decode("utf-8")
print(data)
return {}
except Exception as e:
print(e)
return {}
@app.route('/transactions', methods=['GET'])
def transactions():
# 调起h5支付
try:
print("开始支付")
id = request.args.get('user')
price = request.args.get('price')
print("金额", price)
price = float(price) * 100
fy = H5Main("0001000F8079871")
print("发起费用缴纳",f"{id}{int(time.time())}", int(price), "")
message = fy.unified_order(f"{id}{int(time.time())}", int(price), "订单支付")
return message
except Exception as e:
print("error", e)
return jsonify(error=str(e)), 500
if __name__ == '__main__':
app.run(host="0.0.0.0", port=3010, processes=True)

3
priv_key.pem Normal file
View File

@ -0,0 +1,3 @@
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC/32miL42GsFcVwII+YDxjbjAdASu6f0SyD6fz5jFl+QWYJ16Z8suIpFOpsrvlVE9t8PD1gX1tJmmJYCi1IjoUrVxdKc6nBZ8w68xhttIdnP341W2bBMjWK1Tr3IWC1BwUFYOaGT4c5RJf886BzmUQpQetxi88nXWJCVbAEedhi4OdCgULS7Z74leTDgIi3+xlU7qLICndcCC4zPQM3IsETt/WQBW0bed+sNYI7RxMaAKQ6PaGcbryjZshDtRby+s8UqgdHVnDXY4++DafJjg+FzflE7rM+TyDBY80gvZduMZXHlGytZm9FQNFZSbhvYW0mOOznuwpq7DDLOank6qzAgMBAAECggEBAIdP/WT9eCeGcMPMUY2/vJa6fH/X9Yi+fCm+1Mkyi5/IcGOPUC3thhBFIyNIAy6FuMZl5uice2HgdwkEoXCsRJ2UbNDezPgJBO0xPZ+jmKZ9srYrffKW+zPetzLm/9j10R9w1LB2INGr0ruMaxQsBCYq3DF21JVAzkToKx+lALJOwC+ZEdjwYBCEzSSAKI/VupEMucuRMlSRRIQQXlqDPO0s5ymSkhynslBstpeKsGhl38hLgRA6aQIuhuvtLO00OlOwLxAfWTxgT+2VKntvvBZ3waoUw7sKLlSpX99dfgfARdAj08+ZR4cD06QtLSgAoiYvCet+/1yX457/coH1UdECgYEA/HUAAsD0dM6LG99ki0879ep3+2nd3Msk+4/IPV6p7J3qKuXpG8yGIXGacXzo+gjTxbfkE0l/xD41TcOz8HV7ZRJHtOBGEy6ZZoyqzqTVFS71FjzUL2W1P7RQjDqOpCxZyuW3vsLFVdVrN3fVuMv0NBHDvnzB55HAAeJFrL6Hj70CgYEAwpDAegggdaOFWj9eo03+oiwqJsutK6O6Fa1OZAA+QPG4tXqgiRIAqQ87HEi+a7GPKbntYkJX0YYNhSDkIUqebT1Fb/7kDVfLuDhF2cRa6Qr4CNrIi+F9KguJo3grNzBk/SWNUyouJsSxnQ3XS9kGbIddIzTMOukrnNmNebvOUy8CgYEAij7HsrpXI1+3bZv3QxIwk4nCCjr+81mK9vbVgEXGZ3xSLwuXi1GEYewD1wG/0qviy/LXQniNLrmiFuOENbkfyUkpWzM1LGvoNO/y2RYKWX9NVtAYoZvglPH46dFnKx/eS+1foWanCUnFXKqSro+BOsI/nqBSzqxRqLZv0RjEw0ECgYBeKr7tkRdcuFrnVfpQ4YPXK7bu9e8HSwPaT/m7zp5SwmsacpJWJP9q03NReienadWXZWRuBRwJzW6nu0aOklXhGyGLVfs8NfzkWV/9SNqTJfrsFi+v+9+fRNxF4PhRirumBdHDqYuSueoY0EUecZh5WH6MdpZOAOJZ1LVzcKEogwKBgQDkA5O4Fcxgo8fZaCkeV7Tlg1C1RJBXDD+E29ToAJw2EOruPkWV+rkrZZSpz+4pwgKgcM9IIZJKo/fI7tKDIwj3D+JzFO+H0RNiyMvrCZe7fDnvaPcFGPwqKwyCpjkurKtUdXYbHz9wapFJzaLpYD9opPRBRwZK8TkmXSWNyJi0Kw==
-----END PRIVATE KEY-----

3
pub_key.pem Normal file
View File

@ -0,0 +1,3 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCg2Sk+UF++991s65lk5rIekfG82nvlzz5P8JKxm98ZA4e2UE4avHvGnFv16maFl6SzOTtKcVMnJzyxJsyTIUZvOeEuBXv2ChdVpqux19h1UJPrUoaSH1gi8sYYSkQkiX8i4JJy4yXEmShdajDEPU/ywZ2/0MqXahO1GlFwQid+wwIDAQAB
-----END PUBLIC KEY-----

16
test.py Normal file
View File

@ -0,0 +1,16 @@
from flask import Flask, request, redirect, abort, session
from FuiouPay import H5Main
from utils import *
from WXPay import WXPay
import os, _thread, urllib
id = "513030197011230614"
# 商户号
# price = float(1) * 100
# fy = H5Main('0001000F7152364')
# print("发起缴纳履约服务费", f"{id}{int(time.time())}", int(price), "")
# message = fy.unified_order(f"{id}{int(time.time())}", int(price), "订单支付")
# print("=============",message)
data = filter_jdy_ht(id)
print(data)

394
utils.py Normal file
View File

@ -0,0 +1,394 @@
from datetime import datetime
from Crypto.PublicKey import RSA
import base64
from Crypto.Cipher import PKCS1_v1_5
import requests, time, json, uuid, datetime
from flask import jsonify
from config import *
from dateutil.relativedelta import relativedelta
import threading
import urllib3
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
lock = threading.Lock()
def format_uct(origin_date_str):
origin_date_str = origin_date_str.split('.')[0]
utc_date = datetime.datetime.strptime(origin_date_str, "%Y-%m-%dT%H:%M:%S")
local_date = utc_date + datetime.timedelta(hours=8)
local_date_str = datetime.datetime.strftime(local_date, '%Y-%m-%d %H:%M:%S')
return local_date_str
def queryUser(id):
# 查询充值明细
# user = get_user_info(id)
url = f'{base_path}/api/v5/app/entry/data/list'
filter_data = {
"app_id": pay_app,
"entry_id": pay_details_id,
"limit": 100,
"filter": {
"rel": "and",
"cond": [
{
"field": "order_status",
"method": "eq",
"value": ["已完成"]
},
{
"field": "id_card",
"method": "eq",
"value": [id]
}
]
}
}
pay_detail = turn_page(url, filter_data)
for i in pay_detail:
i['pay_time'] = format_uct(i['pay_time'])
balance = 0
balance = float("%.2f" % balance)
return {"balance": balance, "pay_detail": pay_detail}
def filter_jdy_ht(id):
"""筛选简道云合同表单中驾驶员对应信息"""
url = f'{base_path}/api/v5/app/entry/data/list'
filter_data = {
"app_id": pay_app,
"entry_id": ht_id,
"limit": 100,
"filter": {
"rel": "and",
"cond": [
{
"field": "id_card",
"method": "eq",
"value": [id]
}
]
}
}
print("开始查询合同信息",filter_data)
ht_detail = turn_page(url, filter_data)
if not ht_detail:
return []
ht_detail = ht_detail[0]
# 机构
base_company = ht_detail['base_company']
# 商户号
sh = '0001000F7152040'
# 姓名
name = ht_detail['name']
# 车牌号
phone_num = ht_detail['phone_num']
return [base_company, sh, name, phone_num]
def querydpUser(id):
# 查询充值明细
# user = get_user_info(id)
url = f'{base_path}/api/v5/app/entry/data/list'
filter_data = {
"app_id": pay_app,
"entry_id": pay_details_id,
"limit": 100,
"filter": {
"rel": "and",
"cond": [
{
"field": "order_status",
"method": "eq",
"value": ["已完成"]
},
{
"field": "id_card",
"method": "eq",
"value": [id]
}
]
}
}
pay_detail = turn_page(url, filter_data)
for i in pay_detail:
i['time'] = format_uct(i['time'])
# # 查询个人余额
# info = {
# "app_id": pay_app,
# "entry_id": accout_id,
# "filter": {"rel": "and",
# "cond": [
# {
# "field": "id_card",
# "method": "eq",
# "value": [id]
# },
# {
# "field": "date",
# "method": "empty",
#
# }
# ]}
# }
# # 查询个人余额账户表
# res = req_tool_jdy(url, info)
# balance = 0
# if res['data']:
# balance = res['data'][0]['balance']
# balance = float("%.2f" % balance)
return {"balance": 0, "pay_detail": pay_detail}
def get_last_8_hour():
_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() - 8 * 60 * 60))
return _time
def turn_page(url, data):
"""翻页查询"""
info = []
while 1:
try:
res = req_tool_jdy(url, data)
info += res['data']
if len(res['data']) < 100:
return info
data["data_id"] = res["data"][-1]["_id"]
except Exception as e:
print("turn_page",e, res)
def get_user_info(id, type=None):
"""获取用户信息"""
url = f'{base_path}/api/v5/app/entry/data/list'
if type:
filter_data = {
"app_id": fu_app,
"entry_id": fu_id,
"filter": {
"rel": "and",
"cond": [
{
"field": "id_card",
"method": "eq",
"value": [id]
}
]
}
}
else:
filter_data = {
"app_id": fu_app,
"entry_id": fu_id,
"filter": {
"rel": "and",
"cond": [
{
"field": "user",
"method": "eq",
"value": [id]
}
]
}
}
res = req_tool_jdy(url, filter_data)
if res['data']:
return res['data'][0]
return ''
def query_pay_details(id):
# 查询某人未收付明细
url = f'{base_path}/api/v5/app/entry/data/list'
filter_data = {
"app_id": pay_app,
"entry_id": uncollected_id,
"limit": 100,
"filter": {
"rel": "and",
"cond": [
{
"field": "id_card",
"method": "eq",
"value": [id]
},
{
"field": "order_status",
"method": "eq",
"value": "已发起"
},
]
}
}
uncollected_data = turn_page(url, filter_data)
undata = {}
# 按月份归类 uncollected_data
for un in uncollected_data:
if un['month1'] in undata.keys():
undata[un['month1']]['data'].append(un)
else:
undata[un['month1']] = {"data": []}
undata[un['month1']]['data'] = [un]
# # 按月查询增减项 flowState结束
amount = 0
for un in undata:
_th_amount = 0
for index, j in enumerate(undata[un]['data']):
amount += j['pay_amount']
_th_amount += j['pay_amount']
undata[un]['_th_amount'] = _th_amount
undata['amount'] = float("%.2f" % amount)
for i in list(undata.keys()):
if i != 'amount' and not undata[i]['data']:
del undata[i]
return undata
def req_tool_jdy(url, data):
headers = {"Authorization": f"Bearer {apikey}"}
while 1:
try:
res = requests.post(url, headers=headers, json=data, timeout=10, verify=False).json()
if "code" in res.keys():
print("req_tool_jdy", res)
time.sleep(2)
continue
return res
except Exception as e:
print(e)
def req_tool_vx(url, data=None, flag=None):
while 1:
try:
if not flag:
res = requests.post(url, json=data, timeout=10, verify=False).json()
else:
res = requests.get(url, timeout=10, verify=False).json()
return res
except Exception as e:
print(e)
def add_payment(data, atype=None):
lock.acquire()
print("开始========", data, atype)
# user = get_user_info(data['id'])
# 充值成功后 回写充值明细
now_month = datetime.datetime.now().strftime("%Y-%m")
now_time = get_last_8_hour()
list_url = f'{base_path}/api/v5/app/entry/data/list'
filter_data = {
"app_id": pay_app,
"entry_id": uncollected_id,
"limit": 100,
"filter": {
"rel": "and",
"cond": [
{
"field": "id_card",
"method": "eq",
"value": data['id']
},
{
"field": "base_company",
"method": "eq",
"value": data['base_company']
},
{
"field": "order_status",
"method": "eq",
"value": "已发起"
},
]
}
}
res = req_tool_jdy(list_url, filter_data)
print("=========================res=========================",res)
print(type(res))
_id = res["data"][-1]["_id"]
url = f'{base_path}/api/v5/app/entry/data/update'
info = {
"app_id": pay_app,
"entry_id": pay_details_id,
"data_id": _id,
"is_start_workflow": True,
"is_start_trigger": True,
"data": {
"id_card": {"value": data['id']}, "name": {"value": data['name']},
"pay_type": {"value": data['pay_type']},
"pay_status": {"value": "已支付"}, "order_status": {"value": "已完成"},
"pay_time": {"value": now_time}, "transaction_id": {"value": data['transaction_id']}
}
}
req_tool_jdy(url, info)
lock.release()
print("结束========")
def rsa_long_decrypt(priv_key, msg, length=256):
"""
1024bit的证书用1282048bit证书用256位
"""
try:
privobj = PKCS1_v1_5.new(priv_key)
res = []
b64_msg = base64.b64decode(msg)
for i in range(0, len(b64_msg), length):
chunk = b64_msg[i:i + length]
decrypted_chunk = privobj.decrypt(chunk, 'xyz').decode('GBK')
res.append(decrypted_chunk)
print("解密回调完成:",res)
except Exception as e:
print(f"解密回调失败:{e}")
return jsonify(error=str(e)), 500
return "".join(res)
def decode_notify_data(res_json):
try:
ciphertext = res_json['resource']['ciphertext']
nonce = res_json['resource']['nonce']
associated_data = res_json['resource']['associated_data']
cipher = AES.new(v3_SECRET.encode(), AES.MODE_GCM, nonce=nonce.encode())
cipher.update(associated_data.encode())
en_data = b64decode(ciphertext.encode('utf-8'))
auth_tag = en_data[-16:]
_en_data = en_data[:-16]
plaintext = cipher.decrypt_and_verify(_en_data, auth_tag)
decodejson = json.loads(plaintext.decode())
except Exception as e:
print(f"解密回调失败:{e}")
return None
return decodejson
def get_wx_token():
url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={SECRET}'
res = req_tool_vx(url, flag=1)
return res['access_token']
def query_wx_fj_info(id):
"""查询企微中的附加信息"""
token = get_wx_token()
url = f'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={token}&userid={id}'
res = req_tool_vx(url, flag=1)
val = ""
print("query_wx_fj_info", res,id)
for i in res['extattr']['attrs']:
if i['name'] == '附加信息':
val = i['value']
return val
def query_wx_userid(code):
"""查询企微中的userid"""
token = get_wx_token()
url = f'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token={token}&code={code}'
res = req_tool_vx(url, flag=1)
return res['userid']