wechat_mini_auth.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """微信小程序登录:code2session、手机号快速验证。"""
  2. from __future__ import annotations
  3. import logging
  4. import re
  5. from typing import Any, Dict, Optional
  6. import httpx
  7. from app.core.config import settings
  8. logger = logging.getLogger(__name__)
  9. _WX_CODE2SESSION = "https://api.weixin.qq.com/sns/jscode2session"
  10. _WX_TOKEN = "https://api.weixin.qq.com/cgi-bin/token"
  11. _WX_PHONE = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
  12. class WechatMiniAuthError(Exception):
  13. def __init__(self, message: str, *, wx_errcode: Optional[int] = None):
  14. super().__init__(message)
  15. self.wx_errcode = wx_errcode
  16. def normalize_cn_mobile(raw: Optional[str]) -> str:
  17. if raw is None:
  18. return ""
  19. s = re.sub(r"\s+", "", str(raw).strip())
  20. if s.startswith("+86"):
  21. s = s[3:]
  22. elif s.startswith("86") and len(s) == 13:
  23. s = s[2:]
  24. return s
  25. def _require_mini_credentials() -> tuple:
  26. appid = (settings.WXPAY_MINI_APPID or "").strip()
  27. secret = (settings.WXPAY_SECRET or "").strip()
  28. if not appid or not secret:
  29. raise WechatMiniAuthError("未配置小程序凭证(WXPAY_MINI_APPID / WXPAY_SECRET)")
  30. return appid, secret
  31. def code2session(login_code: str) -> Dict[str, Any]:
  32. code = (login_code or "").strip()
  33. if not code:
  34. raise WechatMiniAuthError("loginCode 不能为空")
  35. appid, secret = _require_mini_credentials()
  36. with httpx.Client(timeout=15.0) as client:
  37. r = client.get(
  38. _WX_CODE2SESSION,
  39. params={
  40. "appid": appid,
  41. "secret": secret,
  42. "js_code": code,
  43. "grant_type": "authorization_code",
  44. },
  45. )
  46. r.raise_for_status()
  47. data = r.json()
  48. if data.get("errcode"):
  49. logger.warning("code2session failed: %s", data)
  50. raise WechatMiniAuthError(
  51. "微信登录凭证无效或已过期", wx_errcode=data.get("errcode")
  52. )
  53. openid = data.get("openid")
  54. if not openid:
  55. raise WechatMiniAuthError("微信未返回 openid")
  56. return {
  57. "openid": openid,
  58. "session_key": data.get("session_key"),
  59. "unionid": data.get("unionid"),
  60. }
  61. def _get_access_token() -> str:
  62. appid, secret = _require_mini_credentials()
  63. with httpx.Client(timeout=15.0) as client:
  64. r = client.get(
  65. _WX_TOKEN,
  66. params={
  67. "grant_type": "client_credential",
  68. "appid": appid,
  69. "secret": secret,
  70. },
  71. )
  72. r.raise_for_status()
  73. data = r.json()
  74. token = data.get("access_token")
  75. if not token:
  76. logger.warning("get access_token failed: %s", data)
  77. raise WechatMiniAuthError(
  78. "获取微信 access_token 失败", wx_errcode=data.get("errcode")
  79. )
  80. return token
  81. def get_phone_number(phone_code: str) -> str:
  82. code = (phone_code or "").strip()
  83. if not code:
  84. raise WechatMiniAuthError("phoneCode 不能为空")
  85. token = _get_access_token()
  86. with httpx.Client(timeout=15.0) as client:
  87. r = client.post(
  88. f"{_WX_PHONE}?access_token={token}",
  89. json={"code": code},
  90. )
  91. r.raise_for_status()
  92. data = r.json()
  93. if data.get("errcode") not in (0, None):
  94. logger.warning("getuserphonenumber failed: %s", data)
  95. raise WechatMiniAuthError(
  96. "获取手机号失败,请改用账号密码登录",
  97. wx_errcode=data.get("errcode"),
  98. )
  99. info = data.get("phone_info") or {}
  100. phone = normalize_cn_mobile(
  101. info.get("purePhoneNumber") or info.get("phoneNumber")
  102. )
  103. if not phone:
  104. raise WechatMiniAuthError("微信未返回手机号")
  105. return phone