update pay ui

This commit is contained in:
2025-12-12 14:16:50 +08:00
parent 39c6eacb58
commit 28de373b85
2 changed files with 54 additions and 45 deletions

View File

@@ -43,14 +43,15 @@ ALIPAY_CONFIG = {
def load_key_from_file(file_path): def load_key_from_file(file_path):
"""从文件读取密钥内容""" """从文件读取密钥内容"""
import sys
try: try:
with open(file_path, 'r', encoding='utf-8') as f: with open(file_path, 'r', encoding='utf-8') as f:
return f.read().strip() return f.read().strip()
except FileNotFoundError: except FileNotFoundError:
print(f"❌ 密钥文件不存在: {file_path}") print(f"[AlipayConfig] Key file not found: {file_path}", file=sys.stderr)
return None return None
except Exception as e: except Exception as e:
print(f"❌ 读取密钥文件失败: {e}") print(f"[AlipayConfig] Read key file failed: {e}", file=sys.stderr)
return None return None
@@ -70,48 +71,48 @@ def validate_config():
# 检查 app_id # 检查 app_id
if not ALIPAY_CONFIG.get('app_id') or ALIPAY_CONFIG['app_id'].startswith('your_'): if not ALIPAY_CONFIG.get('app_id') or ALIPAY_CONFIG['app_id'].startswith('your_'):
issues.append("app_id 未配置请替换为真实的支付宝应用ID") issues.append("app_id not configured")
# 检查密钥文件 # 检查密钥文件
if not os.path.exists(ALIPAY_CONFIG['app_private_key_path']): if not os.path.exists(ALIPAY_CONFIG['app_private_key_path']):
issues.append(f"❌ 应用私钥文件不存在: {ALIPAY_CONFIG['app_private_key_path']}") issues.append(f"Private key file not found: {ALIPAY_CONFIG['app_private_key_path']}")
else: else:
key = get_app_private_key() key = get_app_private_key()
if not key or len(key) < 100: if not key or len(key) < 100:
issues.append("❌ 应用私钥内容异常,请检查文件格式") issues.append("Private key content invalid")
if not os.path.exists(ALIPAY_CONFIG['alipay_public_key_path']): if not os.path.exists(ALIPAY_CONFIG['alipay_public_key_path']):
issues.append(f"❌ 支付宝公钥文件不存在: {ALIPAY_CONFIG['alipay_public_key_path']}") issues.append(f"Alipay public key file not found: {ALIPAY_CONFIG['alipay_public_key_path']}")
else: else:
key = get_alipay_public_key() key = get_alipay_public_key()
if not key or len(key) < 100: if not key or len(key) < 100:
issues.append("❌ 支付宝公钥内容异常,请检查文件格式") issues.append("Alipay public key content invalid")
return len(issues) == 0, issues return len(issues) == 0, issues
if __name__ == "__main__": if __name__ == "__main__":
print("支付宝支付配置验证") print("Alipay Payment Config Validation")
print("=" * 50) print("=" * 50)
is_valid, issues = validate_config() is_valid, issues = validate_config()
if is_valid: if is_valid:
print("✅ 配置验证通过!") print("[OK] Config validation passed!")
print(f" App ID: {ALIPAY_CONFIG['app_id']}") print(f" App ID: {ALIPAY_CONFIG['app_id']}")
print(f" 网关: {ALIPAY_CONFIG['gateway_url']}") print(f" Gateway: {ALIPAY_CONFIG['gateway_url']}")
print(f" 回调地址: {ALIPAY_CONFIG['notify_url']}") print(f" Notify URL: {ALIPAY_CONFIG['notify_url']}")
print(f" 同步跳转: {ALIPAY_CONFIG['return_url']}") print(f" Return URL: {ALIPAY_CONFIG['return_url']}")
else: else:
print("⚠️ 配置存在问题:") print("[ERROR] Config has issues:")
for issue in issues: for issue in issues:
print(f" {issue}") print(f" - {issue}")
print("\n📋 配置步骤:") print("\nSetup steps:")
print("1. 登录支付宝开放平台 (open.alipay.com)") print("1. Login to Alipay Open Platform (open.alipay.com)")
print("2. 创建应用并获取 App ID") print("2. Create app and get App ID")
print("3. 在开发设置中配置RSA2密钥") print("3. Configure RSA2 keys in development settings")
print("4. 将应用私钥、支付宝公钥放到 ./alipay/ 文件夹") print("4. Put private key and Alipay public key in ./alipay/ folder")
print("5. 更新本文件中的配置信息") print("5. Update config in this file")
print("=" * 50) print("=" * 50)

View File

@@ -46,9 +46,7 @@ class AlipayPay:
self.app_private_key = self._load_private_key(app_private_key) self.app_private_key = self._load_private_key(app_private_key)
self.alipay_public_key = self._load_public_key(alipay_public_key) self.alipay_public_key = self._load_public_key(alipay_public_key)
print(f"✅ 支付宝支付初始化成功") # 注意:不要在这里使用 print会影响 subprocess 的 JSON 输出
print(f" App ID: {app_id}")
print(f" 网关: {gateway_url}")
def _load_private_key(self, key_str): def _load_private_key(self, key_str):
"""加载RSA私钥支持 PKCS#1 和 PKCS#8 格式)""" """加载RSA私钥支持 PKCS#1 和 PKCS#8 格式)"""
@@ -76,11 +74,13 @@ class AlipayPay:
) )
return private_key return private_key
except Exception as e: except Exception as e:
print(f"[AlipayPay] Load private key failed: {e}") import sys
print(f"[AlipayPay] Load private key failed: {e}", file=sys.stderr)
raise raise
def _load_public_key(self, key_str): def _load_public_key(self, key_str):
"""加载RSA公钥""" """加载RSA公钥"""
import sys
try: try:
# 如果密钥不包含头尾添加PEM格式头尾 # 如果密钥不包含头尾添加PEM格式头尾
if '-----BEGIN' not in key_str: if '-----BEGIN' not in key_str:
@@ -92,7 +92,7 @@ class AlipayPay:
) )
return public_key return public_key
except Exception as e: except Exception as e:
print(f"❌ 加载公钥失败: {e}") print(f"[AlipayPay] Load public key failed: {e}", file=sys.stderr)
raise raise
def _sign(self, unsigned_string): def _sign(self, unsigned_string):
@@ -105,6 +105,7 @@ class AlipayPay:
Returns: Returns:
Base64编码的签名 Base64编码的签名
""" """
import sys
try: try:
signature = self.app_private_key.sign( signature = self.app_private_key.sign(
unsigned_string.encode('utf-8'), unsigned_string.encode('utf-8'),
@@ -113,7 +114,7 @@ class AlipayPay:
) )
return base64.b64encode(signature).decode('utf-8') return base64.b64encode(signature).decode('utf-8')
except Exception as e: except Exception as e:
print(f"❌ 签名失败: {e}") print(f"[AlipayPay] Sign failed: {e}", file=sys.stderr)
raise raise
def _verify(self, message, signature): def _verify(self, message, signature):
@@ -127,6 +128,7 @@ class AlipayPay:
Returns: Returns:
bool: 验证是否通过 bool: 验证是否通过
""" """
import sys
try: try:
self.alipay_public_key.verify( self.alipay_public_key.verify(
base64.b64decode(signature), base64.b64decode(signature),
@@ -136,7 +138,7 @@ class AlipayPay:
) )
return True return True
except Exception as e: except Exception as e:
print(f"❌ 签名验证失败: {e}") print(f"[AlipayPay] Verify signature failed: {e}", file=sys.stderr)
return False return False
def _get_sign_content(self, params): def _get_sign_content(self, params):
@@ -205,9 +207,9 @@ class AlipayPay:
# 构建完整的支付URL # 构建完整的支付URL
pay_url = f"{self.gateway_url}?{urlencode(params)}" pay_url = f"{self.gateway_url}?{urlencode(params)}"
print(f"✅ 支付宝订单创建成功: {out_trade_no}") # 日志输出到 stderr避免影响 subprocess JSON 输出
print(f" 金额: {total_amount}") import sys
print(f" 标题: {subject}") print(f"[AlipayPay] Order created: {out_trade_no}, amount: {total_amount}", file=sys.stderr)
return { return {
'success': True, 'success': True,
@@ -216,7 +218,8 @@ class AlipayPay:
} }
except Exception as e: except Exception as e:
print(f"❌ 创建支付宝订单失败: {e}") import sys
print(f"[AlipayPay] Create order failed: {e}", file=sys.stderr)
return { return {
'success': False, 'success': False,
'error': str(e) 'error': str(e)
@@ -266,7 +269,9 @@ class AlipayPay:
response = requests.get(self.gateway_url, params=params, timeout=30) response = requests.get(self.gateway_url, params=params, timeout=30)
result = response.json() result = response.json()
print(f"📡 支付宝查询响应: {result}") # 日志输出到 stderr
import sys
print(f"[AlipayPay] Query response: {result}", file=sys.stderr)
# 解析响应 # 解析响应
query_response = result.get('alipay_trade_query_response', {}) query_response = result.get('alipay_trade_query_response', {})
@@ -295,10 +300,12 @@ class AlipayPay:
} }
except requests.RequestException as e: except requests.RequestException as e:
print(f"❌ 支付宝API请求失败: {e}") import sys
print(f"[AlipayPay] API request failed: {e}", file=sys.stderr)
return {'success': False, 'error': f'网络请求失败: {e}'} return {'success': False, 'error': f'网络请求失败: {e}'}
except Exception as e: except Exception as e:
print(f"❌ 查询订单异常: {e}") import sys
print(f"[AlipayPay] Query order error: {e}", file=sys.stderr)
return {'success': False, 'error': str(e)} return {'success': False, 'error': str(e)}
def verify_callback(self, params): def verify_callback(self, params):
@@ -323,21 +330,22 @@ class AlipayPay:
sign_content = self._get_sign_content(params) sign_content = self._get_sign_content(params)
# 验证签名 # 验证签名
import sys
if self._verify(sign_content, sign): if self._verify(sign_content, sign):
print(f"✅ 支付宝回调签名验证通过") print(f"[AlipayPay] Callback signature verified", file=sys.stderr)
return { return {
'success': True, 'success': True,
'data': params 'data': params
} }
else: else:
print(f"❌ 支付宝回调签名验证失败") print(f"[AlipayPay] Callback signature verification failed", file=sys.stderr)
return { return {
'success': False, 'success': False,
'error': '签名验证失败' 'error': '签名验证失败'
} }
except Exception as e: except Exception as e:
print(f"❌ 验证回调异常: {e}") print(f"[AlipayPay] Verify callback error: {e}", file=sys.stderr)
return {'success': False, 'error': str(e)} return {'success': False, 'error': str(e)}
def verify_return(self, params): def verify_return(self, params):
@@ -403,14 +411,14 @@ if __name__ == '__main__':
import sys import sys
print("=" * 60) print("=" * 60)
print("支付宝支付测试") print("Alipay Payment Test")
print("=" * 60) print("=" * 60)
try: try:
# 检查配置 # 检查配置
is_ready, message = check_alipay_ready() is_ready, message = check_alipay_ready()
print(f"\n配置状态: {'✅ 就绪' if is_ready else '❌ 未就绪'}") print(f"\nConfig status: {'READY' if is_ready else 'NOT READY'}")
print(f"详情: {message}") print(f"Details: {message}")
if is_ready: if is_ready:
# 创建实例 # 创建实例
@@ -421,19 +429,19 @@ if __name__ == '__main__':
result = alipay.create_page_pay_url( result = alipay.create_page_pay_url(
out_trade_no=test_order_no, out_trade_no=test_order_no,
total_amount='0.01', total_amount='0.01',
subject='测试商品', subject='Test Product',
body='这是一个测试订单' body='This is a test order'
) )
print(f"\n创建订单结果:") print(f"\nCreate order result:")
print(json.dumps(result, indent=2, ensure_ascii=False)) print(json.dumps(result, indent=2, ensure_ascii=False))
if result['success']: if result['success']:
print(f"\n🔗 支付链接(复制到浏览器打开):") print(f"\nPayment URL (open in browser):")
print(result['pay_url'][:200] + '...') print(result['pay_url'][:200] + '...')
except Exception as e: except Exception as e:
print(f"\n❌ 测试失败: {e}") print(f"\nTest failed: {e}")
import traceback import traceback
traceback.print_exc() traceback.print_exc()