Files
market_page/backend/shop/utils.py
jeremygan2021 db401a7103 小程序分销
2026-02-17 11:32:16 +08:00

49 lines
1.5 KiB
Python
Raw 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.
import requests
from django.core.cache import cache
from .models import WeChatPayConfig
import logging
logger = logging.getLogger(__name__)
def get_access_token(config=None):
"""
获取微信接口调用凭证 (client_credential)
"""
# 尝试从缓存获取
cache_key = 'wechat_access_token'
if config:
cache_key = f'wechat_access_token_{config.app_id}'
token = cache.get(cache_key)
if token:
return token
if not config:
# 优先查找指定 AppID
config = WeChatPayConfig.objects.filter(app_id='wxdf2ca73e6c0929f0').first()
if not config:
config = WeChatPayConfig.objects.filter(is_active=True).first()
if not config or not config.app_id or not config.app_secret:
logger.error("No active WeChatPayConfig found or missing app_id/app_secret")
return None
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={config.app_id}&secret={config.app_secret}"
try:
response = requests.get(url, timeout=10)
data = response.json()
if 'access_token' in data:
token = data['access_token']
expires_in = data.get('expires_in', 7200)
# 缓存 Token留出 200 秒缓冲时间
cache.set(cache_key, token, expires_in - 200)
return token
else:
logger.error(f"获取 AccessToken 失败: {data}")
except Exception as e:
logger.error(f"获取 AccessToken 异常: {str(e)}", exc_info=True)
return None