Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API. Co-authored-by: Cursor <cursoragent@cursor.com>
137 lines
4.0 KiB
Python
137 lines
4.0 KiB
Python
"""WeChat miniprogram virtual payment helpers (personal-subject xpay)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import time
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
WX_APPID = os.getenv("WX_APPID", "wxa55815dd741a540d")
|
|
WX_APPSECRET = os.getenv("WX_APPSECRET", "bf71025c209e7567d49268bc427ba22b")
|
|
WX_OFFER_ID = os.getenv("WX_OFFER_ID", "1450642200")
|
|
WX_PAY_ENV = int(os.getenv("WX_PAY_ENV", "1")) # 0=prod 1=sandbox
|
|
WX_APP_KEY = (
|
|
os.getenv("WX_LIVE_APPKEY")
|
|
if WX_PAY_ENV == 0
|
|
else os.getenv("WX_SANDBOX_APPKEY")
|
|
) or os.getenv(
|
|
"WX_APP_KEY",
|
|
"CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg"
|
|
if WX_PAY_ENV == 0
|
|
else "0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn",
|
|
)
|
|
|
|
|
|
def calc_pay_sig(uri: str, post_body: str, appkey: str) -> str:
|
|
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(
|
|
*,
|
|
product_id: str,
|
|
goods_price: int,
|
|
out_trade_no: str,
|
|
attach: str = "",
|
|
buy_quantity: int = 1,
|
|
) -> str:
|
|
payload = {
|
|
"offerId": WX_OFFER_ID,
|
|
"buyQuantity": buy_quantity,
|
|
"env": WX_PAY_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()
|
|
if not code:
|
|
raise ValueError("empty code")
|
|
if code.startswith("mock") or code in {"dev", "the code is a mock one"}:
|
|
digest = hashlib.sha256(code.encode()).hexdigest()[:16]
|
|
return {
|
|
"openid": f"devtools_{digest}",
|
|
"session_key": f"devtools_session_{digest}",
|
|
}
|
|
if not WX_APPSECRET:
|
|
raise RuntimeError("WX_APPSECRET not configured")
|
|
url = "https://api.weixin.qq.com/sns/jscode2session"
|
|
params = {
|
|
"appid": WX_APPID,
|
|
"secret": WX_APPSECRET,
|
|
"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()
|
|
if data.get("errcode"):
|
|
# DevTools invalid/used code → soft mock for local
|
|
if int(data.get("errcode") or 0) in {40029, 40163, 40252}:
|
|
digest = hashlib.sha256(code.encode()).hexdigest()[:16]
|
|
return {
|
|
"openid": f"devtools_{digest}",
|
|
"session_key": f"devtools_session_{digest}",
|
|
}
|
|
raise RuntimeError(f"code2session failed: {data}")
|
|
if not data.get("openid"):
|
|
raise RuntimeError(f"code2session missing openid: {data}")
|
|
return data
|
|
|
|
|
|
# in-memory session store (replace with Redis/PB in prod)
|
|
_SESSIONS: dict[str, dict[str, Any]] = {}
|
|
|
|
|
|
def store_session(openid: str, session_key: str) -> str:
|
|
token = hashlib.sha256(f"{openid}.{time.time()}".encode()).hexdigest()
|
|
_SESSIONS[token] = {
|
|
"openid": openid,
|
|
"session_key": session_key,
|
|
"ts": time.time(),
|
|
}
|
|
return token
|
|
|
|
|
|
def get_session(token: str) -> dict[str, Any] | None:
|
|
return _SESSIONS.get(token)
|
|
|
|
|
|
def make_pay_payload(
|
|
*,
|
|
session_key: str,
|
|
product_id: str,
|
|
goods_price: int,
|
|
out_trade_no: str,
|
|
) -> dict[str, str]:
|
|
if not WX_APP_KEY:
|
|
raise RuntimeError("WX_SANDBOX_APPKEY / WX_LIVE_APPKEY not configured")
|
|
sign_data = build_sign_data(
|
|
product_id=product_id,
|
|
goods_price=goods_price,
|
|
out_trade_no=out_trade_no,
|
|
)
|
|
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, WX_APP_KEY)
|
|
signature = calc_signature(sign_data, session_key)
|
|
return {
|
|
"signData": sign_data,
|
|
"mode": "short_series_goods",
|
|
"paySig": pay_sig,
|
|
"signature": signature,
|
|
"outTradeNo": out_trade_no,
|
|
}
|