Files
xbcr/test_order_status.py

271 lines
9.0 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试:读取当前账号的还车状态和骑行开始时间
========================================
使用 app.py 中硬编码的凭据 (token_id=1499773, wx_signature=db057ef3...)
1. 查 /user/info → 获取 nonDealOrder
2. 调 /record/refresh → 获取已用时间/费用
3. 调 /record/detail → 获取订单详情(含开始时间)
"""
import json
import time
import hashlib
import sys
from pathlib import Path
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
try:
import requests
except ImportError:
print("[!] 需要安装 requests 库: pip install requests")
sys.exit(1)
if sys.platform == "win32":
sys.stdout.reconfigure(encoding="utf-8") # type: ignore
# ============================================================
# 配置
# ============================================================
WECHAT_BASE = "https://bike.sdlongren.com"
TOKEN_ID = "1499773"
WECHAT_HEADERS = {
"Host": "bike.sdlongren.com",
"hsf-x-timestamp": "",
"hsf-x-tokenid": TOKEN_ID,
"xweb_xhr": "1",
"platform": "xiaobai",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 "
"MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI "
"MiniProgramEnv/Windows WindowsWechat/WMPF "
"WindowsWechat(0x63090c38)XWEB/8518",
"content-type": "application/json",
"accept": "*/*",
"accept-language": "*",
"sec-fetch-site": "cross-site",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
"referer": "https://servicewechat.com/wx10426ca961518f43/98/page-frame.html",
}
def compute_signature(token_id: str, timestamp: str, method: str, path: str,
data: dict = None, params: dict = None) -> str:
"""模拟 app.py 的签名算法"""
if method.upper() == "GET":
params_str = ""
if params:
sorted_params = sorted(params.items())
params_str = "&".join(f"{k}={v}" for k, v in sorted_params)
raw = f"{token_id}{method}{path}{timestamp}{params_str}"
else:
body_str = json.dumps(data, separators=(",", ":")) if data else ""
raw = f"{token_id}POST{path}{timestamp}{body_str}"
return hashlib.sha256(raw.encode()).hexdigest()[:40]
def wechat_get(path: str, params: dict = None) -> dict:
ts = str(int(time.time()))
sig = compute_signature(TOKEN_ID, ts, "GET", path, params=params)
headers = WECHAT_HEADERS.copy()
headers["hsf-x-timestamp"] = ts
headers["hsf-x-signature"] = sig
url = f"{WECHAT_BASE}{path}"
try:
resp = requests.get(url, params=params, headers=headers,
timeout=10, verify=False)
return resp.json()
except Exception as e:
return {"rtn_code": -1, "error": str(e)}
def wechat_post(path: str, data: dict = None) -> dict:
ts = str(int(time.time()))
sig = compute_signature(TOKEN_ID, ts, "POST", path, data=data)
headers = WECHAT_HEADERS.copy()
headers["hsf-x-timestamp"] = ts
headers["hsf-x-signature"] = sig
url = f"{WECHAT_BASE}{path}"
try:
resp = requests.post(url, json=data, headers=headers,
timeout=10, verify=False)
return resp.json()
except Exception as e:
return {"rtn_code": -1, "error": str(e)}
def print_title(title: str):
print()
print("=" * 65)
print(f" {title}")
print("=" * 65)
# ============================================================
# 1. 查 /user/info → 获取 nonDealOrder
# ============================================================
def step1_user_info():
print_title("第1步:查 /user/info 获取当前账号信息")
result = wechat_get("/user/info")
if result.get("rtn_code") != 0:
print(f" [错误] rtn_code={result.get('rtn_code')}, message={result.get('message')}")
return None
data = result.get("data", {})
print(f" 用户信息获取成功")
# 打印基础信息
print(f" - schoolId: {data.get('schoolId')}")
print(f" - is_order: {data.get('is_order')}") # 1=有订单
print(f" - bikeNum: {data.get('bikeNum')}")
print(f" - user_status: {data.get('auth', {}).get('status')}")
# 重点:nonDealOrder
non_deal = data.get("nonDealOrder")
if not non_deal or not non_deal.get("order_id"):
print(f" - nonDealOrder: 无活跃订单")
return None
print(f"\n ✅ 有活跃订单:")
print(f" order_id: {non_deal.get('order_id')}")
print(f" code (车牌号): {non_deal.get('code')}")
print(f" status: {non_deal.get('status')} (1=未支付, 2=进行中)")
print(f" type: {non_deal.get('type')} (3=电动车)")
print(f" lock_protocol_id: {non_deal.get('lock_protocol_id')}")
print(f" projectId: {non_deal.get('projectId')}")
return non_deal
# ============================================================
# 2. 调 /record/refresh → 获取已用时间/费用
# ============================================================
def step2_refresh_order(order_id):
print_title("第2步:调 /record/refresh 获取订单实时状态")
result = wechat_get("/record/refresh", params={"order_id": order_id})
if result.get("rtn_code") != 0:
print(f" [错误] rtn_code={result.get('rtn_code')}, message={result.get('message')}")
return None
data = result.get("data", {})
print(f" /record/refresh 返回:")
for k, v in data.items():
print(f" {k}: {v}")
print()
if data.get("time") is not None:
print(f" ⏱️ 已用时间: {data['time']} (单位未知,可能是分钟或秒)")
print(f" 如果 time 是分钟,已骑行 {data['time']} 分钟")
print(f" 如果 time 是秒,已骑行 {int(data['time'])/60:.1f} 分钟")
if data.get("money") is not None:
print(f" 💰 当前费用: {data['money']} 元")
if data.get("state") is not None:
state_map = {"0": "未知", "1": "进行中", "2": "已结束", "9": "故障"}
print(f" 📌 订单状态码: {data['state']} ({state_map.get(str(data['state']), '未知')})")
return data
# ============================================================
# 3. 调 /record/detail → 获取订单详细信息
# ============================================================
def step3_order_detail(order_id):
print_title("第3步:调 /record/detail 获取订单详情")
result = wechat_get("/record/detail", params={"order_id": order_id})
if result.get("rtn_code") != 0:
print(f" [错误] rtn_code={result.get('rtn_code')}, message={result.get('message')}")
return None
data = result.get("data", {})
print(f" /record/detail 返回:")
for k, v in data.items():
print(f" {k}: {v}")
# 尝试找时间相关字段
time_keys = [k for k in data.keys() if "time" in k.lower()
or "date" in k.lower() or "start" in k.lower()
or "create" in k.lower() or "begin" in k.lower()]
if time_keys:
print(f"\n ⏱️ 时间相关字段:")
for k in time_keys:
print(f" {k}: {data[k]}")
return data
# ============================================================
# 4. 计算倒计时(假设19分钟限制)
# ============================================================
def step4_calc_countdown(refresh_data):
print_title("第4步:计算19分钟倒计时")
if not refresh_data or refresh_data.get("time") is None:
print(" 缺少 time 数据,无法计算倒计时")
return
time_val = int(refresh_data["time"])
# 试两种情况:time 是分钟 或 time 是秒
for unit, divisor in [("秒", 1), ("分钟", 60)]:
elapsed_min = time_val / divisor
remaining = 19 - elapsed_min
if remaining > 0:
print(f" 假设 time 是{unit}: 已用 {elapsed_min:.1f} 分钟, 剩余 {remaining:.1f} 分钟")
print(f" 建议倒计时 = {remaining:.1f} 分钟 = {int(remaining * 60)} 秒")
else:
print(f" 假设 time 是{unit}: 已用 {elapsed_min:.1f} 分钟 (已超19分钟)")
# ============================================================
# 主流程
# ============================================================
def main():
print("=" * 65)
print(" 查询当前账号的还车状态和骑行开始时间")
print("=" * 65)
print(f" API: {WECHAT_BASE}")
print(f" 凭据: token_id={TOKEN_ID}")
print()
# 第1步:获取 nonDealOrder
non_deal = step1_user_info()
if not non_deal:
print("\n [!] 无活跃订单,无需继续")
return
order_id = non_deal.get("order_id")
# 第2步:刷新订单
refresh_data = step2_refresh_order(order_id)
# 第3步:订单详情
detail_data = step3_order_detail(order_id)
# 第4步:计算倒计时
step4_calc_countdown(refresh_data)
print()
print("=" * 65)
print(" 测试完成")
print("=" * 65)
if __name__ == "__main__":
main()