from __future__ import annotations import hashlib import hmac import json from typing import Any import httpx from app.config import settings def calc_pay_sig(uri: str, post_body: str, appkey: str) -> str: """uri 不带问号参数。C 端固定 requestVirtualPayment;B 端为 /xpay/* 路径。""" msg = f"{uri}&{post_body}" return hmac.new(appkey.encode("utf-8"), msg.encode("utf-8"), hashlib.sha256).hexdigest() def calc_signature(post_body: str, session_key: str) -> str: return hmac.new(session_key.encode("utf-8"), post_body.encode("utf-8"), hashlib.sha256).hexdigest() def build_sign_data( *, offer_id: str, product_id: str, goods_price: int, out_trade_no: str, attach: str, buy_quantity: int = 1, env: int | None = None, ) -> str: # 键顺序保持稳定,且与实际发送字符串完全一致(不美化、不改序) payload = { "offerId": offer_id, "buyQuantity": buy_quantity, "env": settings.wx_pay_env if env is None else env, "currencyType": "CNY", "productId": product_id, "goodsPrice": goods_price, "outTradeNo": out_trade_no, "attach": attach, } return json.dumps(payload, ensure_ascii=False, separators=(",", ":")) async def code2session(code: str) -> dict[str, Any]: code = (code or "").strip() mock_codes = {"dev", "the code is a mock one"} if code in mock_codes or code.startswith("mock"): if settings.debug or settings.wx_allow_devtools_login: digest = hashlib.sha256(code.encode("utf-8")).hexdigest()[:16] return { "openid": f"devtools_{digest}", "session_key": f"devtools_session_{digest}", "unionid": None, } url = "https://api.weixin.qq.com/sns/jscode2session" params = { "appid": settings.wx_appid, "secret": settings.wx_secret, "js_code": code, "grant_type": "authorization_code", } async with httpx.AsyncClient(timeout=15) as client: r = await client.get(url, params=params) data = r.json() err = data.get("errcode") if err: # 开发者工具无效 code / 已使用 code:降级为可阅读联调账号 if settings.wx_allow_devtools_login and int(err) in {40029, 40163, 40252}: digest = hashlib.sha256(code.encode("utf-8")).hexdigest()[:16] return { "openid": f"devtools_{digest}", "session_key": f"devtools_session_{digest}", "unionid": None, } raise RuntimeError(f"code2session failed: {data}") if not data.get("openid"): raise RuntimeError(f"code2session missing openid: {data}") return data _access_token_cache: dict[str, Any] = {"token": "", "expire_at": 0} async def get_access_token() -> str: import time now = time.time() if _access_token_cache["token"] and _access_token_cache["expire_at"] > now + 60: return _access_token_cache["token"] url = "https://api.weixin.qq.com/cgi-bin/token" params = { "grant_type": "client_credential", "appid": settings.wx_appid, "secret": settings.wx_secret, } async with httpx.AsyncClient(timeout=15) as client: r = await client.get(url, params=params) data = r.json() if "access_token" not in data: raise RuntimeError(f"get access_token failed: {data}") _access_token_cache["token"] = data["access_token"] _access_token_cache["expire_at"] = now + int(data.get("expires_in", 7200)) return data["access_token"] async def query_order(openid: str, out_trade_no: str) -> dict[str, Any]: """POST /xpay/query_order,带 pay_sig。""" body_obj = {"openid": openid, "env": settings.wx_pay_env, "order_id": out_trade_no} post_body = json.dumps(body_obj, ensure_ascii=False, separators=(",", ":")) pay_sig = calc_pay_sig("/xpay/query_order", post_body, settings.wx_app_key) token = await get_access_token() url = f"https://api.weixin.qq.com/xpay/query_order?access_token={token}&pay_sig={pay_sig}" async with httpx.AsyncClient(timeout=20) as client: r = await client.post(url, content=post_body, headers={"Content-Type": "application/json"}) return r.json()