-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskillpay_integration.py
More file actions
192 lines (169 loc) · 6.4 KB
/
skillpay_integration.py
File metadata and controls
192 lines (169 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
"""
SkillPay 支付集成模块
支持 Base 链 USDC 支付验证
"""
import os
import json
import requests
from typing import Optional, Dict, Any
from datetime import datetime, timedelta
# Base 链 USDC 合约地址
USDC_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
BASE_RPC = "https://mainnet.base.org"
class SkillPayVerifier:
"""验证用户 USDC 支付状态"""
def __init__(self, merchant_address: str):
"""
初始化
:param merchant_address: 你的 BNB/Base 收款地址 0x...
"""
self.merchant_address = merchant_address.lower()
self.cache_file = ".payment_cache.json"
self.cache = self._load_cache()
def _load_cache(self) -> Dict:
"""加载支付缓存"""
if os.path.exists(self.cache_file):
try:
with open(self.cache_file, 'r') as f:
return json.load(f)
except:
pass
return {}
def _save_cache(self):
"""保存支付缓存"""
with open(self.cache_file, 'w') as f:
json.dump(self.cache, f, indent=2)
def _get_usdc_balance(self, address: str) -> float:
"""
查询地址 USDC 余额 (Base 链)
注意:这是简化版,实际应该调用 Base 链 RPC
"""
# 这里应该调用 Base 链 RPC 查询 USDC 余额
# 简化演示,返回 0
return 0.0
def _check_recent_payments(self, user_address: str, amount: float = 0.01) -> bool:
"""
检查最近支付(简化版)
实际应该:
1. 调用 BaseScan API 查询转账记录
2. 验证付款金额和时间
3. 确认收款地址匹配
"""
# 演示:假设已支付
# 实际实现需要调用区块链 API
return False
def verify_payment(self, user_id: str, user_address: Optional[str] = None) -> Dict[str, Any]:
"""
验证用户支付状态
:param user_id: 用户唯一标识
:param user_address: 用户钱包地址(可选)
:return: {
"paid": bool,
"expiry": str, # ISO 格式过期时间
"plan": str, # "free" | "premium"
"message": str
}
"""
# 检查缓存
if user_id in self.cache:
cached = self.cache[user_id]
expiry = datetime.fromisoformat(cached["expiry"])
if expiry > datetime.now():
return {
"paid": True,
"expiry": cached["expiry"],
"plan": cached.get("plan", "premium"),
"message": f"✅ 付费版已激活,有效期至 {cached['expiry'][:10]}"
}
# 免费版限制
free_limits = {
"max_wallets": 3,
"features": ["basic_monitoring"],
"delay_seconds": 300 # 5分钟延迟
}
# 如果提供了用户地址,检查链上支付
if user_address:
if self._check_recent_payments(user_address):
# 支付确认,更新缓存
expiry = datetime.now() + timedelta(days=30)
self.cache[user_id] = {
"address": user_address,
"expiry": expiry.isoformat(),
"plan": "premium",
"verified_at": datetime.now().isoformat()
}
self._save_cache()
return {
"paid": True,
"expiry": expiry.isoformat(),
"plan": "premium",
"message": f"✅ 支付验证成功!已解锁付费版(30天)"
}
# 未支付,返回免费版
return {
"paid": False,
"expiry": None,
"plan": "free",
"message": f"ℹ️ 免费版:最多3个地址,5分钟延迟\n💎 付费版:0.01 BNB/USDC/月,无限地址实时推送\n\n付款地址:{self.merchant_address}",
"limits": free_limits
}
def record_payment(self, user_id: str, tx_hash: str, amount: float, user_address: str) -> bool:
"""
手动记录支付(用户发送交易哈希后验证)
:param user_id: 用户ID
:param tx_hash: 交易哈希
:param amount: 支付金额
:param user_address: 用户付款地址
:return: 是否验证成功
"""
# 这里应该:
# 1. 调用 BaseScan/BscScan API 查询交易
# 2. 验证收款地址是 merchant_address
# 3. 验证金额 >= 0.01 USDC/BNB
# 4. 确认交易成功
# 简化演示:假设验证成功
expiry = datetime.now() + timedelta(days=30)
self.cache[user_id] = {
"tx_hash": tx_hash,
"amount": amount,
"address": user_address,
"expiry": expiry.isoformat(),
"plan": "premium",
"verified_at": datetime.now().isoformat()
}
self._save_cache()
return True
# 便捷函数
def check_payment_status(user_id: str, user_address: Optional[str] = None) -> Dict[str, Any]:
"""
检查用户支付状态(全局函数)
用法:
from skillpay_integration import check_payment_status
status = check_payment_status("user_123", "0x...")
if status["paid"]:
print("付费用户")
else:
print(f"免费用户,限制:{status['message']}")
"""
# 使用环境变量或配置文件中的收款地址
merchant = os.getenv("MERCHANT_ADDRESS", "0xd49536C908fa29c103501ed17b568628b16C8cE2")
verifier = SkillPayVerifier(merchant)
return verifier.verify_payment(user_id, user_address)
# 测试
if __name__ == "__main__":
# 测试免费版
print("=== 测试免费版 ===")
status = check_payment_status("test_user_1")
print(json.dumps(status, indent=2, ensure_ascii=False))
print("\n=== 测试付费版(模拟)===")
# 模拟已支付用户
verifier = SkillPayVerifier("0xd49536C908fa29c103501ed17b568628b16C8cE2")
verifier.record_payment(
"test_user_2",
"0x1234567890abcdef",
0.01,
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
)
status = verifier.verify_payment("test_user_2")
print(json.dumps(status, indent=2, ensure_ascii=False))