Files

526 lines
20 KiB
Python
Raw Permalink 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.
# -*- coding: utf-8 -*-
"""xq0076 交行接口通道(纯接口,借用页面国密库加密/签名)。
协议(2026-11 实测,密文与抓包逐字节一致):
请求 body = plainText=<hex( SM4-ECB( PKCS5(明文JSON), key ) )>
&verify=<hex( SM2.sign( UTF8(plainText的hex), privKey ) )>
响应 body = {"plainText": "<base64 密文>"} → base64→hex→SM4 解密→去 PKCS5→明文 JSON
鉴权 = Authorization: Bearer <JWT>(登录后由页面请求产生,hook 捕获)
加密/签名全部交给页面自带的 KeyouCryptography(window 上可见),不在 Python 侧重写国密,
平台升级加密实现时可自动跟随;只有换 key/私钥/签名规则才需要跟版。
"""
import json
import re
import time
from .. import config
# ==================== 会话密钥捕获(关键) ====================
# SM4 key 与 SM2 私钥都是「会话级」的:每次登录由服务端协商,与上一次不同。
# 之前把某一次的 key 硬编码进来,只在那个会话有效 —— 这是响应解不开的根因。
# 做法:页面加载前注入 hook,拦截页面自己的加解密调用,把当前会话的 key 抓下来。
JS_CAPTURE = r"""
(function () {
window.__sess = window.__sess || { sm4: '', sm2: '' };
function hook() {
try {
var K = window.KeyouCryptography;
if (!K || !K.algorithm || !K.algorithm.SM4) return false;
var SM4 = K.algorithm.SM4, SM2 = K.algorithm.SM2;
var U = K.util.UTF8, H = K.util.Hex;
if (!SM4.__hc) {
SM4.__hc = true;
var oe = SM4.encryptWithECB;
SM4.encryptWithECB = function (p, k) {
try { if (!window.__sess.sm4) window.__sess.sm4 = U.stringify(k); } catch (e) {}
return oe.apply(this, arguments);
};
var od = SM4.decryptWithECB;
SM4.decryptWithECB = function (d, k) {
try { if (!window.__sess.sm4) window.__sess.sm4 = U.stringify(k); } catch (e) {}
return od.apply(this, arguments);
};
}
if (SM2 && !SM2.__hc) {
SM2.__hc = true;
var os = SM2.sign;
SM2.sign = function (m, p) {
try { if (!window.__sess.sm2) window.__sess.sm2 = H.stringify(p); } catch (e) {}
return os.apply(this, arguments);
};
}
return true;
} catch (e) { return false; }
}
if (!hook()) {
var t = setInterval(function () { if (hook()) clearInterval(t); }, 200);
setTimeout(function () { clearInterval(t); }, 30000);
}
})();
"""
_captured = {'sm4': '', 'sm2': ''}
def install_capture(page):
"""注册初始化脚本:每次页面加载都会注入「会话密钥捕获 + 鉴权捕获」hook。"""
ok = False
try:
page.add_init_js(JS_CAPTURE)
ok = True
except Exception as e:
config.log(f'注册会话密钥捕获脚本失败:{e}', 'WARN')
try:
page.add_init_js(JS_HOOK_AUTH)
except Exception:
pass
return ok
def wait_session_keys(page, timeout=40, trigger=True):
"""捕获当前会话的 SM4/SM2 密钥。
两步保证:
① 现在页面里直接注入 hook(页面已加载时 add_init_js 不生效);
② 主动点一次页面「查询」,让页面自己走一遍「加密请求 → 解密响应」,hook 即拿到 key。
"""
try:
page.run_js(JS_CAPTURE)
except Exception as e:
config.debug(f'注入密钥 hook 失败:{e}')
if trigger:
try:
for el in page.eles('tag:button'):
try:
if el.states.is_displayed and ''.join((el.text or '').split()) == '查询':
el.click()
config.debug('已点页面「查询」触发密钥捕获')
break
except Exception:
continue
except Exception:
pass
deadline = time.time() + timeout
while time.time() < deadline:
try:
raw = page.run_js('return JSON.stringify(window.__sess || {})')
d = json.loads(raw) if raw else {}
except Exception:
d = {}
if d.get('sm4'):
_captured['sm4'] = d.get('sm4') or ''
_captured['sm2'] = d.get('sm2') or ''
config.log(f'已捕获会话密钥(SM4 {len(_captured["sm4"])} 字符'
f",SM2 {len(_captured['sm2'])} 字符)")
return dict(_captured)
time.sleep(2)
config.log('未捕获到会话密钥(回落到默认值,可能当前会话不匹配)', 'WARN')
return {}
# ==================== 页面注入:加密 + 签名 + 请求 + 解密 ====================
JS_TOOLKIT = r"""
if (!window.__bk) {
window.__bk = {
init: function () {
var K = window.KeyouCryptography;
if (!K) throw new Error('KeyouCryptography 未加载');
this.SM4 = K.algorithm.SM4;
this.SM2 = K.algorithm.SM2;
this.PAD = K.util.DataPadding;
this.H = K.util.Hex;
this.U = K.util.UTF8;
this.HP = K.util.Helper;
this.KEY = this.U.parse(arguments[0]);
this.PRIV = this.H.parse(arguments[1]);
return true;
},
_dec: function (bytes, mode) {
try {
var out;
if (mode === 'ECB') {
out = this.SM4.decryptWithECB(bytes, this.KEY);
} else if (mode === 'CBC_IV16') {
out = this.SM4.decryptWithCBC(bytes.slice(16), this.KEY, bytes.slice(0, 16));
} else {
var z = [];
for (var i = 0; i < 16; i++) z.push(0);
out = this.SM4.decryptWithCBC(bytes, this.KEY, z);
}
var s = this.U.stringify(this.PAD.decodeWithPKCS5(out, 16));
// 去掉首尾 BOM / 空白 / 控制字符(PKCS5 补位有时去不干净,尾部残留 \u0002)
var t = String(s)
.replace(/^[\s\u0000-\u001f\uFEFF]+/, '')
.replace(/[\s\u0000-\u001f\uFEFF]+$/, '');
if (t.charAt(0) === '{' || t.charAt(0) === '[') return t; // 必须是 JSON 才算成功
} catch (e) {}
return null;
},
_decodeResp: function (pt) {
// 密文格式可能是 base64 也可能是 hex;模式可能是 ECB 也可能 CBC,逐一尝试
var cands = [];
try {
var h1 = this.HP.b64tohex(pt);
if (h1) cands.push(h1);
} catch (e) {}
if (/^[0-9A-Fa-f]+$/.test(pt) && pt.length % 2 === 0) cands.push(pt);
var modes = ['ECB', 'CBC_IV16', 'CBC_ZERO'];
for (var i = 0; i < cands.length; i++) {
var bytes;
try { bytes = this.H.parse(cands[i]); } catch (e) { continue; }
for (var m = 0; m < modes.length; m++) {
var r = this._dec(bytes, modes[m]);
if (r !== null) {
window.__decMode = modes[m] + '/' + (i === 0 ? 'b64' : 'hex');
return r;
}
}
}
return null;
},
call: function (path, obj) {
var plain = JSON.stringify(obj);
var ct = this.SM4.encryptWithECB(this.PAD.encodeWithPKCS5(this.U.parse(plain), 16), this.KEY);
var ctHex = this.H.stringify(ct);
var sig = this.SM2.sign(this.U.parse(ctHex), this.PRIV);
var body = 'plainText=' + ctHex + '&verify=' + this.H.stringify(sig);
var xhr = new XMLHttpRequest();
xhr.open('POST', path, false);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Authorization', window.__auth || '');
xhr.setRequestHeader('SecurityType', 'S');
xhr.setRequestHeader('source', 'pc');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(body);
var raw = xhr.responseText || '';
var o = null;
try { o = JSON.parse(raw); } catch (e) { o = null; }
if (o && typeof o === 'object' && o.plainText) {
var dec = this._decodeResp(String(o.plainText));
if (dec !== null) return dec;
return 'ERR:decrypt-fail len=' + String(o.plainText).length +
' ct=' + (xhr.getResponseHeader('Content-Type') || '') +
' full=' + String(o.plainText).slice(0, 200);
}
if (o && typeof o === 'object') return raw; // 明文 JSON(如错误码)
return 'ERR:non-json status=' + xhr.status +
' ct=' + (xhr.getResponseHeader('Content-Type') || '') +
' len=' + raw.length + ' head=' + raw.slice(0, 80);
}
};
}
return window.__bk.init(arguments[0], arguments[1]);
"""
# 拦截页面所有请求的 Authorization(登录后页面自己发请求时会带上正式 JWT)
JS_HOOK_AUTH = r"""
if (!window.__authHook) {
window.__authHook = true;
window.__authList = window.__authList || [];
var sh = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function (k, v) {
try {
if (String(k).toLowerCase() === 'authorization' && v) {
window.__authList.push(String(v));
window.__auth = String(v);
}
} catch (e) {}
return sh.apply(this, arguments);
};
}
return true;
"""
JS_CALL = 'return window.__bk.call(arguments[0], arguments[1]);'
# ==================== 解密诊断(DEBUG 模式):hook 页面自身的解密调用 ====================
# 用途:我们手动加密的请求服务端能受理,但响应解不开;让页面自己发一次请求,
# 观察它到底调哪个 decrypt、用什么 key,从而确定正确的响应解密方式。
JS_DIAG_HOOK = r"""
window.__diag = [];
function __hookDec(obj, path) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) return;
var names = [];
try {
var cur = obj, d = 0;
while (cur && d < 3) {
Object.getOwnPropertyNames(cur).forEach(function (n) { if (names.indexOf(n) < 0) names.push(n); });
cur = Object.getPrototypeOf(cur); d++;
}
} catch (e) {}
names.forEach(function (n) {
if (!/decrypt|Decrypt|unseal|plainText|decodeResp/i.test(n)) return;
var f;
try { f = obj[n]; } catch (e) { return; }
if (typeof f !== 'function') return;
try {
obj[n] = function () {
var r = f.apply(this, arguments);
try {
var args = [];
for (var i = 0; i < arguments.length; i++) {
var a = arguments[i];
args.push((a && typeof a === 'object') ? JSON.stringify(a).slice(0, 160) : String(a).slice(0, 160));
}
window.__diag.push({ t: path + '.' + n, a: args, r: String(r).slice(0, 180) });
} catch (e) {}
return r;
};
} catch (e) {}
});
}
try {
Object.keys(window).forEach(function (k) {
try {
var v = window[k];
if (v && typeof v.getSessionData === 'function') __hookDec(v, 'win/' + k);
} catch (e) {}
});
} catch (e) {}
try { __hookDec(window.KeyouCryptography, 'Keyou'); } catch (e) {}
try { __hookDec(window.KeyouCryptography && window.KeyouCryptography.algorithm, 'Keyou.alg'); } catch (e) {}
try { __hookDec(window.CryptoJS, 'CryptoJS'); } catch (e) {}
return 'ok';
"""
def diagnose_init(page):
"""DEBUG 用:注入解密 hook(需在页面加载完成后调用)。"""
try:
page.run_js(JS_DIAG_HOOK)
return True
except Exception as e:
config.log(f'注入解密诊断 hook 失败:{e}', 'WARN')
return False
def diagnose_report(page, limit=3):
"""DEBUG 用:取回命中的解密调用。"""
try:
raw = page.run_js('return JSON.stringify((window.__diag || []).slice(0, 20))')
return json.loads(raw) if raw else []
except Exception:
return []
_last_call_ts = [0.0]
def _throttle():
gap = config.API_INTERVAL - (time.time() - _last_call_ts[0])
if gap > 0:
time.sleep(gap)
# ==================== 通道初始化 / 鉴权 ====================
def init(page, sm4_key=None, priv=None):
"""注入加密通道(需页面已加载出 KeyouCryptography)。
密钥优先用本次会话捕获到的值;捕获失败才回落到配置里的默认值。
"""
sm4 = sm4_key or _captured.get('sm4') or config.SM4_KEY
priv = priv or _captured.get('sm2') or config.SM2_PRIV
if not _captured.get('sm4'):
config.log('警告:使用默认密钥(可能与本会话不匹配,解密会失败)', 'WARN')
deadline = time.time() + 30
while time.time() < deadline:
try:
ok = page.run_js(JS_TOOLKIT, sm4, priv)
if ok:
config.log('国密通道已就绪')
return True
except Exception as e:
config.debug(f'注入通道失败:{e}')
time.sleep(1)
raise RuntimeError('页面国密库未加载(KeyouCryptography 不存在),无法初始化接口通道')
def install_auth_hook(page):
page.run_js(JS_HOOK_AUTH)
def _nudge(page):
"""轻推一下页面(切菜单触发一次带鉴权的请求),用于页面空闲没有请求时补抓 token。"""
try:
for el in page.eles('tag:li'):
try:
if '交易汇总' in (el.text or '') and el.states.is_displayed:
el.click()
config.debug('已切到「交易汇总」触发鉴权请求')
return True
except Exception:
continue
except Exception:
pass
return False
def wait_token(page, timeout=60):
"""等页面发出带正式 JWT 的请求(跳过 temporary 临时票据)。"""
start = time.time()
nudged = False
while time.time() - start < timeout:
# ① 优先用「最近一次页面请求实际带的」票据(hook 每次请求都会刷新)
try:
cur = page.run_js('return window.__auth || ""') or ''
except Exception:
cur = ''
if cur and 'temporary=' not in cur:
config.log(f'已捕获登录票据({len(cur)} 字符,取最近请求)')
return cur
# ② 历史列表兜底
try:
lst = page.run_js('return JSON.stringify(window.__authList || [])')
items = json.loads(lst) if lst else []
except Exception:
items = []
for item in reversed(items):
if item and 'temporary=' not in item:
config.log(f'已捕获登录票据({len(item)} 字符)')
# 必须写回 window.__auth:__bk.call 读的是它,登录过程中可能被临时票据覆盖
try:
page.run_js('window.__auth = arguments[0]; return true;', item)
except Exception as e:
config.debug(f'写回票据失败:{e}')
return item
# 15 秒还没抓到,主动切一次菜单触发请求
if not nudged and time.time() - start > 15:
nudged = True
_nudge(page)
time.sleep(2)
# 兜底:当前 __auth
cur = page.run_js('return window.__auth || ""') or ''
if cur and 'temporary=' not in cur:
return cur
raise RuntimeError('未捕获到登录票据(Authorization),可能登录未完成')
# ==================== 通用调用(限流 + 重试) ====================
def call(page, path, payload, retry=None):
"""调用一个业务接口,返回解密后的 dict。全局限流 + 重试。"""
retry = retry or config.RETRY_MAX
last_err = ''
for attempt in range(1, retry + 1):
_throttle()
try:
raw = page.run_js(JS_CALL, path, payload)
except Exception as e:
last_err = f'执行异常:{e}'
time.sleep(config.API_INTERVAL)
continue
_last_call_ts[0] = time.time()
if not raw:
last_err = '空响应'
continue
try:
data = json.loads(raw)
except Exception:
last_err = f'响应异常:{str(raw)[:220]}'
config.log(last_err, 'WARN')
time.sleep(config.API_INTERVAL)
continue
code = str(data.get('RespCode') or '')
msg = str(data.get('RespMsg') or '')
# 银行侧限流:退避后重试(不要立刻重发,否则一直被拒)
if code == 'AM00049' or '频繁' in msg:
last_err = f'RespCode={code} {msg}(退避 {config.RATE_LIMIT_WAIT}s)'
config.log(last_err, 'WARN')
time.sleep(config.RATE_LIMIT_WAIT)
continue
if code == '000000':
try:
mode = page.run_js('return window.__decMode || ""')
if mode:
config.debug(f'响应解密方式:{mode}')
except Exception:
pass
return data
last_err = f"RespCode={code} {data.get('RespMsg') or ''}"
# 业务错误(非系统异常)不重试
if code and code not in ('999999', 'AM00040'):
break
time.sleep(config.API_INTERVAL)
raise RuntimeError(f'接口 {path} 调用失败({attempt}/{retry}):{last_err}')
# ==================== 业务接口 ====================
def _fmt_start(d):
return d.strftime('%Y%m%d') + '000000'
def _fmt_end(d):
return d.strftime('%Y%m%d') + '235959'
def _base_payload(mcht_id, mcht_acc):
return {
'mchtId': mcht_id,
'shopId': '',
'mchtOrderNo': '',
'bussType': config.BUSS_TYPE_COUPON,
'tradeState': config.TRADE_STATE_ALL,
'tradeType': '',
'payType': '',
'authNo': '',
'tradeNo': '',
'paycardNo': '',
'mchtAcc': mcht_acc,
}
def query_trades(page, mcht_id, mcht_acc, date_from, date_to, page_index=1, page_size=None):
"""交易流水明细查询(商户验券)。"""
p = _base_payload(mcht_id, mcht_acc)
p.update({
'txnStartDate': _fmt_start(date_from),
'txnEndDate': _fmt_end(date_to),
'pageIndex': str(page_index),
'pageSize': str(page_size or config.PAGE_SIZE_QUERY),
})
return call(page, config.API_QUERY, p)
def submit_export(page, mcht_id, mcht_acc, date_from, date_to):
"""提交导出,返回 {taskID, filename}。"""
p = _base_payload(mcht_id, mcht_acc)
p.update({
'txnStartDate': _fmt_start(date_from),
'txnEndDate': _fmt_end(date_to),
'pageType': config.PAGE_TYPE,
})
data = call(page, config.API_EXPORT_SUBMIT, p)
rd = data.get('responseData') or {}
return {'task_id': rd.get('taskID') or '', 'filename': rd.get('filename') or ''}
def check_export(page, mcht_id, task_ids):
"""查导出任务状态,返回原始 responseData 列表。"""
data = call(page, config.API_EXPORT_STATUS, {
'mrchId': mcht_id,
'pageType': config.PAGE_TYPE,
'taskIdList': list(task_ids),
})
return data.get('responseData') or []
def get_download_url(page, mcht_id):
data = call(page, config.API_DOWNLOAD, {'mrchId': mcht_id, 'pageType': config.PAGE_TYPE})
return data.get('downLoadUrl') or ''
# ==================== 商户识别 ====================
def detect_merchant(page):
"""从页面文本解析 mchtId(15 位)与 mchtAcc(MER 账号)。"""
try:
txt = page.run_js('return document.body ? document.body.innerText : ""') or ''
except Exception:
txt = ''
mcht_id = ''
m = re.search(r'\b(\d{15})-[^\n]{2,40}', txt)
if m:
mcht_id = m.group(1)
accs = re.findall(r'\b(MER\d{6,})\b', txt)
mcht_acc = accs[0] if accs else ''
return mcht_id, mcht_acc