paynode-sdk-python 1.0.1__py3-none-any.whl → 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- paynode_sdk/__init__.py +16 -1
- paynode_sdk/client.py +180 -63
- paynode_sdk/constants.py +32 -2
- paynode_sdk/errors.py +3 -0
- paynode_sdk/middleware.py +7 -2
- paynode_sdk/verifier.py +96 -24
- paynode_sdk/webhook.py +233 -0
- paynode_sdk_python-1.1.1.dist-info/METADATA +107 -0
- paynode_sdk_python-1.1.1.dist-info/RECORD +13 -0
- paynode_sdk_python-1.1.1.dist-info/licenses/LICENSE +21 -0
- paynode_sdk_python-1.0.1.dist-info/METADATA +0 -85
- paynode_sdk_python-1.0.1.dist-info/RECORD +0 -11
- {paynode_sdk_python-1.0.1.dist-info → paynode_sdk_python-1.1.1.dist-info}/WHEEL +0 -0
- {paynode_sdk_python-1.0.1.dist-info → paynode_sdk_python-1.1.1.dist-info}/top_level.txt +0 -0
paynode_sdk/__init__.py
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
# Silence upstream library deprecation warnings from web3's websocket dependency
|
|
5
|
+
# to ensure a clean experience for PayNode SDK users.
|
|
6
|
+
warnings.filterwarnings("ignore", category=DeprecationWarning, module="websockets.legacy")
|
|
7
|
+
|
|
1
8
|
from .middleware import PayNodeMiddleware
|
|
2
9
|
from .verifier import PayNodeVerifier
|
|
3
10
|
from .errors import ErrorCode, PayNodeException
|
|
4
11
|
from .idempotency import IdempotencyStore, MemoryIdempotencyStore
|
|
12
|
+
from .webhook import PayNodeWebhookNotifier, PaymentEvent
|
|
13
|
+
from .client import PayNodeAgentClient
|
|
14
|
+
from .constants import ACCEPTED_TOKENS
|
|
5
15
|
|
|
6
|
-
__all__ = [
|
|
16
|
+
__all__ = [
|
|
17
|
+
"PayNodeMiddleware", "PayNodeVerifier", "ErrorCode", "PayNodeException",
|
|
18
|
+
"IdempotencyStore", "MemoryIdempotencyStore",
|
|
19
|
+
"PayNodeWebhookNotifier", "PaymentEvent",
|
|
20
|
+
"PayNodeAgentClient", "ACCEPTED_TOKENS"
|
|
21
|
+
]
|
paynode_sdk/client.py
CHANGED
|
@@ -1,99 +1,216 @@
|
|
|
1
|
-
import requests
|
|
2
1
|
import time
|
|
2
|
+
import logging
|
|
3
|
+
import threading
|
|
4
|
+
import requests
|
|
5
|
+
from eth_account.messages import encode_typed_data
|
|
3
6
|
from web3 import Web3
|
|
7
|
+
from requests.adapters import HTTPAdapter
|
|
8
|
+
from urllib3.util.retry import Retry
|
|
4
9
|
from .constants import PAYNODE_ROUTER_ADDRESS, BASE_USDC_ADDRESS, BASE_USDC_DECIMALS
|
|
10
|
+
from .errors import PayNodeException, ErrorCode
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger("paynode_sdk.client")
|
|
5
13
|
|
|
6
14
|
class PayNodeAgentClient:
|
|
7
|
-
|
|
8
|
-
|
|
15
|
+
"""
|
|
16
|
+
The main PayNode Client for AI Agents (v1.1.1).
|
|
17
|
+
Automatically handles the x402 'Payment Required' handshake.
|
|
18
|
+
Supports RPC redundancy and EIP-2612 Permit-First payments.
|
|
19
|
+
"""
|
|
20
|
+
def __init__(self, private_key: str, rpc_urls: list | str = "https://mainnet.base.org"):
|
|
21
|
+
self.rpc_urls = rpc_urls if isinstance(rpc_urls, list) else [rpc_urls]
|
|
22
|
+
self.w3 = self._init_w3()
|
|
23
|
+
|
|
24
|
+
# Initialize account and discard private key string
|
|
9
25
|
self.account = self.w3.eth.account.from_key(private_key)
|
|
10
|
-
self.
|
|
26
|
+
self.nonce_lock = threading.Lock()
|
|
27
|
+
|
|
28
|
+
# Setup session
|
|
29
|
+
self.session = requests.Session()
|
|
30
|
+
retry_strategy = Retry(
|
|
31
|
+
total=3,
|
|
32
|
+
status_forcelist=[429, 500, 502, 503, 504],
|
|
33
|
+
allowed_methods=["HEAD", "GET", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"]
|
|
34
|
+
)
|
|
35
|
+
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
36
|
+
self.session.mount("https://", adapter)
|
|
37
|
+
self.session.mount("http://", adapter)
|
|
38
|
+
|
|
39
|
+
def _init_w3(self):
|
|
40
|
+
"""Finds a working RPC from the list."""
|
|
41
|
+
for rpc in self.rpc_urls:
|
|
42
|
+
try:
|
|
43
|
+
w3 = Web3(Web3.HTTPProvider(rpc, request_kwargs={'timeout': 5}))
|
|
44
|
+
if w3.is_connected():
|
|
45
|
+
return w3
|
|
46
|
+
except Exception as e:
|
|
47
|
+
logger.warning(f"⚠️ [PayNode-PY] RPC {rpc} failed: {str(e)}")
|
|
48
|
+
continue
|
|
49
|
+
raise PayNodeException("Failed to connect to any provided RPC nodes.", ErrorCode.RPC_ERROR)
|
|
50
|
+
|
|
51
|
+
def request_gate(self, url: str, method: str = "GET", **kwargs):
|
|
52
|
+
"""The high-level autonomous method handling 402 loop."""
|
|
53
|
+
return self._request_with_402_retry(method.upper(), url, **kwargs)
|
|
11
54
|
|
|
12
55
|
def get(self, url, **kwargs):
|
|
13
|
-
|
|
14
|
-
if response.status_code == 402:
|
|
15
|
-
print("💡 [PayNode-PY] 402 Detected. Handling payment...")
|
|
16
|
-
return self._handle_402(url, "GET", response.headers, **kwargs)
|
|
17
|
-
return response
|
|
56
|
+
return self.request_gate(url, "GET", **kwargs)
|
|
18
57
|
|
|
19
58
|
def post(self, url, **kwargs):
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
59
|
+
return self.request_gate(url, "POST", **kwargs)
|
|
60
|
+
|
|
61
|
+
def _request_with_402_retry(self, method, url, max_retries=3, **kwargs):
|
|
62
|
+
for _ in range(max_retries):
|
|
63
|
+
response = self.session.request(method, url, **kwargs)
|
|
64
|
+
if response.status_code == 402:
|
|
65
|
+
logger.info("💡 [PayNode-PY] 402 Detected. Handling payment...")
|
|
66
|
+
try:
|
|
67
|
+
kwargs = self._handle_402(response.headers, **kwargs)
|
|
68
|
+
except Exception as e:
|
|
69
|
+
if isinstance(e, PayNodeException): raise
|
|
70
|
+
raise PayNodeException(f"An unexpected error occurred: {str(e)}", ErrorCode.INTERNAL_ERROR)
|
|
71
|
+
continue
|
|
72
|
+
return response
|
|
24
73
|
return response
|
|
25
74
|
|
|
26
|
-
def _handle_402(self,
|
|
75
|
+
def _handle_402(self, headers, **kwargs):
|
|
27
76
|
router_addr = headers.get('x-paynode-contract')
|
|
28
77
|
merchant_addr = headers.get('x-paynode-merchant')
|
|
29
78
|
amount_raw = int(headers.get('x-paynode-amount', 0))
|
|
30
79
|
token_addr = headers.get('x-paynode-token-address')
|
|
31
80
|
order_id = headers.get('x-paynode-order-id')
|
|
32
81
|
|
|
33
|
-
|
|
34
|
-
|
|
82
|
+
if not all([router_addr, merchant_addr, amount_raw, token_addr, order_id]):
|
|
83
|
+
raise PayNodeException("Malformed 402 headers: missing metadata", ErrorCode.INTERNAL_ERROR)
|
|
84
|
+
|
|
85
|
+
# v1.3 Constraint: Min payment protection
|
|
86
|
+
if amount_raw < 1000:
|
|
87
|
+
raise PayNodeException("Payment amount is below the protocol minimum (1000).", ErrorCode.AMOUNT_TOO_LOW)
|
|
35
88
|
|
|
36
|
-
#
|
|
37
|
-
|
|
38
|
-
|
|
89
|
+
# Protocol v1.3: Permit-First Execution
|
|
90
|
+
try:
|
|
91
|
+
# Check allowance first to decide if we need Permit
|
|
92
|
+
allowance = self._get_allowance(token_addr, router_addr)
|
|
93
|
+
if allowance >= amount_raw:
|
|
94
|
+
tx_hash = self._execute_pay(router_addr, token_addr, merchant_addr, amount_raw, order_id)
|
|
95
|
+
else:
|
|
96
|
+
logger.info("⚡ [PayNode-PY] Insufficient allowance. Attempting Permit-First payment...")
|
|
97
|
+
tx_hash = self.pay_with_permit_auto(router_addr, token_addr, merchant_addr, amount_raw, order_id)
|
|
98
|
+
|
|
99
|
+
logger.info(f"✅ [PayNode-PY] Payment successful: {tx_hash}")
|
|
100
|
+
except Exception as e:
|
|
101
|
+
if isinstance(e, PayNodeException): raise
|
|
102
|
+
raise PayNodeException(f"On-chain transaction reverted or failed: {str(e)}", ErrorCode.TRANSACTION_FAILED)
|
|
39
103
|
|
|
40
|
-
# 3. Retry
|
|
41
104
|
retry_headers = kwargs.get('headers', {}).copy()
|
|
42
|
-
retry_headers.update({
|
|
43
|
-
'x-paynode-receipt': tx_hash,
|
|
44
|
-
'x-paynode-order-id': order_id
|
|
45
|
-
})
|
|
105
|
+
retry_headers.update({'x-paynode-receipt': tx_hash, 'x-paynode-order-id': order_id})
|
|
46
106
|
kwargs['headers'] = retry_headers
|
|
107
|
+
return kwargs
|
|
108
|
+
|
|
109
|
+
def _get_allowance(self, token_addr, spender_addr):
|
|
110
|
+
abi = [{"constant": True, "inputs": [{"name": "o", "type": "address"}, {"name": "s", "type": "address"}], "name": "allowance", "outputs": [{"name": "", "type": "uint256"}], "type": "function"}]
|
|
111
|
+
token = self.w3.eth.contract(address=Web3.to_checksum_address(token_addr), abi=abi)
|
|
112
|
+
return token.functions.allowance(self.account.address, Web3.to_checksum_address(spender_addr)).call()
|
|
113
|
+
|
|
114
|
+
def sign_permit(self, token_addr, spender_addr, amount, deadline=None):
|
|
115
|
+
"""Signs EIP-2612 Permit data."""
|
|
116
|
+
if deadline is None:
|
|
117
|
+
deadline = int(time.time()) + 3600
|
|
118
|
+
|
|
119
|
+
token_addr = Web3.to_checksum_address(token_addr)
|
|
120
|
+
spender_addr = Web3.to_checksum_address(spender_addr)
|
|
47
121
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def _ensure_allowance(self, token_addr, spender_addr, amount):
|
|
53
|
-
token_abi = [
|
|
54
|
-
{"constant": True, "inputs": [{"name": "o", "type": "address"}, {"name": "s", "type": "address"}], "name": "allowance", "outputs": [{"name": "", "type": "uint256"}], "type": "function"},
|
|
55
|
-
{"constant": False, "inputs": [{"name": "s", "type": "address"}, {"name": "a", "type": "uint256"}], "name": "approve", "outputs": [{"name": "", "type": "bool"}], "type": "function"}
|
|
122
|
+
# Get nonce and domain separator
|
|
123
|
+
abi = [
|
|
124
|
+
{"inputs": [{"name": "o", "type": "address"}], "name": "nonces", "outputs": [{"name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"},
|
|
125
|
+
{"inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "stateMutability": "view", "type": "function"}
|
|
56
126
|
]
|
|
57
|
-
token = self.w3.eth.contract(address=
|
|
58
|
-
|
|
127
|
+
token = self.w3.eth.contract(address=token_addr, abi=abi)
|
|
128
|
+
nonce = token.functions.nonces(self.account.address).call()
|
|
129
|
+
name = token.functions.name().call()
|
|
130
|
+
chain_id = self.w3.eth.chain_id
|
|
131
|
+
|
|
132
|
+
domain = {
|
|
133
|
+
"name": name,
|
|
134
|
+
"version": "1",
|
|
135
|
+
"chainId": chain_id,
|
|
136
|
+
"verifyingContract": token_addr,
|
|
137
|
+
}
|
|
138
|
+
message = {
|
|
139
|
+
"owner": self.account.address,
|
|
140
|
+
"spender": spender_addr,
|
|
141
|
+
"value": amount,
|
|
142
|
+
"nonce": nonce,
|
|
143
|
+
"deadline": deadline,
|
|
144
|
+
}
|
|
145
|
+
types = {
|
|
146
|
+
"EIP712Domain": [
|
|
147
|
+
{"name": "name", "type": "string"},
|
|
148
|
+
{"name": "version", "type": "string"},
|
|
149
|
+
{"name": "chainId", "type": "uint256"},
|
|
150
|
+
{"name": "verifyingContract", "type": "address"},
|
|
151
|
+
],
|
|
152
|
+
"Permit": [
|
|
153
|
+
{"name": "owner", "type": "address"},
|
|
154
|
+
{"name": "spender", "type": "address"},
|
|
155
|
+
{"name": "value", "type": "uint256"},
|
|
156
|
+
{"name": "nonce", "type": "uint256"},
|
|
157
|
+
{"name": "deadline", "type": "uint256"},
|
|
158
|
+
],
|
|
159
|
+
}
|
|
59
160
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
161
|
+
structured_data = {
|
|
162
|
+
"types": types,
|
|
163
|
+
"domain": domain,
|
|
164
|
+
"primaryType": "Permit",
|
|
165
|
+
"message": message,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
signed = self.account.sign_typed_data(full_message=structured_data)
|
|
169
|
+
return {"v": signed.v, "r": signed.r, "s": signed.s, "deadline": deadline}
|
|
170
|
+
|
|
171
|
+
def pay_with_permit_auto(self, router_addr, token_addr, merchant_addr, amount, order_id):
|
|
172
|
+
"""Combines sign_permit and on-chain submission."""
|
|
173
|
+
sig = self.sign_permit(token_addr, router_addr, amount)
|
|
174
|
+
router_abi = [{"inputs": [{"name": "p", "type": "address"}, {"name": "t", "type": "address"}, {"name": "m", "type": "address"}, {"name": "a", "type": "uint256"}, {"name": "o", "type": "bytes32"}, {"name": "d", "type": "uint256"}, {"name": "v", "type": "uint8"}, {"name": "r", "type": "bytes32"}, {"name": "s", "type": "bytes32"}], "name": "payWithPermit", "outputs": [], "stateMutability": "nonpayable", "type": "function"}]
|
|
175
|
+
router = self.w3.eth.contract(address=Web3.to_checksum_address(router_addr), abi=router_abi)
|
|
176
|
+
order_id_bytes = self.w3.keccak(text=order_id)
|
|
177
|
+
|
|
178
|
+
current_gas_price = int(self.w3.eth.gas_price * 1.2)
|
|
179
|
+
with self.nonce_lock:
|
|
180
|
+
nonce = self.w3.eth.get_transaction_count(self.account.address, 'pending')
|
|
181
|
+
tx = router.functions.payWithPermit(
|
|
182
|
+
self.account.address,
|
|
183
|
+
Web3.to_checksum_address(token_addr),
|
|
184
|
+
Web3.to_checksum_address(merchant_addr),
|
|
185
|
+
amount,
|
|
186
|
+
order_id_bytes,
|
|
187
|
+
sig["deadline"], sig["v"], sig["r"], sig["s"]
|
|
188
|
+
).build_transaction({
|
|
66
189
|
'from': self.account.address,
|
|
67
|
-
'nonce':
|
|
68
|
-
'gas':
|
|
190
|
+
'nonce': nonce,
|
|
191
|
+
'gas': 300000,
|
|
69
192
|
'gasPrice': current_gas_price
|
|
70
193
|
})
|
|
71
|
-
signed_tx = self.
|
|
194
|
+
signed_tx = self.account.sign_transaction(tx)
|
|
72
195
|
tx_h = self.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
196
|
+
|
|
197
|
+
self.w3.eth.wait_for_transaction_receipt(tx_h, timeout=60)
|
|
198
|
+
return self.w3.to_hex(tx_h)
|
|
76
199
|
|
|
77
200
|
def _execute_pay(self, router_addr, token_addr, merchant_addr, amount, order_id):
|
|
201
|
+
"""Standard pay method (fallback)."""
|
|
78
202
|
router_abi = [{"inputs": [{"name": "t", "type": "address"}, {"name": "m", "type": "address"}, {"name": "a", "type": "uint256"}, {"name": "o", "type": "bytes32"}], "name": "pay", "outputs": [], "stateMutability": "nonpayable", "type": "function"}]
|
|
79
203
|
router = self.w3.eth.contract(address=Web3.to_checksum_address(router_addr), abi=router_abi)
|
|
80
204
|
order_id_bytes = self.w3.keccak(text=order_id)
|
|
81
|
-
|
|
82
|
-
# Use 20% higher gas price
|
|
83
205
|
current_gas_price = int(self.w3.eth.gas_price * 1.2)
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
Web3.to_checksum_address(merchant_addr),
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
'gasPrice': current_gas_price
|
|
95
|
-
})
|
|
96
|
-
signed_tx = self.w3.eth.account.sign_transaction(tx, self.private_key)
|
|
97
|
-
tx_h = self.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
|
|
98
|
-
self.w3.eth.wait_for_transaction_receipt(tx_h)
|
|
206
|
+
|
|
207
|
+
with self.nonce_lock:
|
|
208
|
+
nonce = self.w3.eth.get_transaction_count(self.account.address, 'pending')
|
|
209
|
+
tx = router.functions.pay(Web3.to_checksum_address(token_addr), Web3.to_checksum_address(merchant_addr), amount, order_id_bytes).build_transaction({
|
|
210
|
+
'from': self.account.address, 'nonce': nonce, 'gas': 200000, 'gasPrice': current_gas_price
|
|
211
|
+
})
|
|
212
|
+
signed_tx = self.account.sign_transaction(tx)
|
|
213
|
+
tx_h = self.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
|
|
214
|
+
|
|
215
|
+
self.w3.eth.wait_for_transaction_receipt(tx_h, timeout=60)
|
|
99
216
|
return self.w3.to_hex(tx_h)
|
paynode_sdk/constants.py
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
# Generated by scripts/sync-config.py
|
|
2
|
+
PAYNODE_ROUTER_ADDRESS = "0x92e20164FC457a2aC35f53D06268168e6352b200"
|
|
3
|
+
PAYNODE_ROUTER_ADDRESS_SANDBOX = "0xB587Bc36aaCf65962eCd6Ba59e2DA76f2f575408"
|
|
3
4
|
BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
4
5
|
BASE_USDC_ADDRESS_SANDBOX = "0xeAC1f2C7099CdaFfB91Aa3b8Ffd653Ef16935798"
|
|
5
6
|
BASE_USDC_DECIMALS = 6
|
|
7
|
+
|
|
8
|
+
PROTOCOL_TREASURY = "0x598bF63F5449876efafa7b36b77Deb2070621C0E"
|
|
9
|
+
PROTOCOL_FEE_BPS = 100
|
|
10
|
+
MIN_PAYMENT_AMOUNT = 1000
|
|
11
|
+
|
|
12
|
+
BASE_RPC_URLS = ["https://mainnet.base.org", "https://base.meowrpc.com", "https://1rpc.io/base"]
|
|
13
|
+
BASE_RPC_URLS_SANDBOX = ["https://sepolia.base.org", "https://base-sepolia-rpc.publicnode.com"]
|
|
14
|
+
|
|
15
|
+
ACCEPTED_TOKENS = {
|
|
16
|
+
8453: ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],
|
|
17
|
+
84532: ["0xeAC1f2C7099CdaFfB91Aa3b8Ffd653Ef16935798"]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
PAYNODE_ROUTER_ABI = [
|
|
21
|
+
{
|
|
22
|
+
"anonymous": False,
|
|
23
|
+
"inputs": [
|
|
24
|
+
{"indexed": True, "name": "orderId", "type": "bytes32"},
|
|
25
|
+
{"indexed": True, "name": "merchant", "type": "address"},
|
|
26
|
+
{"indexed": True, "name": "payer", "type": "address"},
|
|
27
|
+
{"indexed": False, "name": "token", "type": "address"},
|
|
28
|
+
{"indexed": False, "name": "amount", "type": "uint256"},
|
|
29
|
+
{"indexed": False, "name": "fee", "type": "uint256"},
|
|
30
|
+
{"indexed": False, "name": "chainId", "type": "uint256"}
|
|
31
|
+
],
|
|
32
|
+
"name": "PaymentReceived",
|
|
33
|
+
"type": "event"
|
|
34
|
+
}
|
|
35
|
+
]
|
paynode_sdk/errors.py
CHANGED
|
@@ -13,8 +13,11 @@ class ErrorCode(str, Enum):
|
|
|
13
13
|
WRONG_CONTRACT = 'PAYNODE_WRONG_CONTRACT'
|
|
14
14
|
WRONG_MERCHANT = 'PAYNODE_WRONG_MERCHANT'
|
|
15
15
|
WRONG_TOKEN = 'PAYNODE_WRONG_TOKEN'
|
|
16
|
+
TOKEN_NOT_ACCEPTED = 'PAYNODE_TOKEN_NOT_ACCEPTED'
|
|
17
|
+
AMOUNT_TOO_LOW = 'PAYNODE_AMOUNT_TOO_LOW'
|
|
16
18
|
INSUFFICIENT_FUNDS = 'PAYNODE_INSUFFICIENT_FUNDS'
|
|
17
19
|
ORDER_MISMATCH = 'PAYNODE_ORDER_MISMATCH'
|
|
20
|
+
PERMIT_FAILED = 'PAYNODE_PERMIT_FAILED'
|
|
18
21
|
|
|
19
22
|
# System
|
|
20
23
|
RPC_ERROR = 'PAYNODE_RPC_ERROR'
|
paynode_sdk/middleware.py
CHANGED
|
@@ -6,9 +6,12 @@ from .verifier import PayNodeVerifier
|
|
|
6
6
|
from .errors import ErrorCode
|
|
7
7
|
from .idempotency import IdempotencyStore
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
10
|
+
|
|
11
|
+
class PayNodeMiddleware(BaseHTTPMiddleware):
|
|
10
12
|
def __init__(
|
|
11
13
|
self,
|
|
14
|
+
app: Any,
|
|
12
15
|
rpc_url: str,
|
|
13
16
|
contract_address: str,
|
|
14
17
|
merchant_address: str,
|
|
@@ -20,6 +23,7 @@ class PayNodeMiddleware:
|
|
|
20
23
|
store: Optional[IdempotencyStore] = None,
|
|
21
24
|
generate_order_id: Optional[Callable[[Request], str]] = None
|
|
22
25
|
):
|
|
26
|
+
super().__init__(app)
|
|
23
27
|
# The Verifier holds the state of the idempotency store
|
|
24
28
|
self.verifier = PayNodeVerifier(rpc_url, contract_address, chain_id, store=store)
|
|
25
29
|
self.merchant_address = merchant_address
|
|
@@ -34,7 +38,7 @@ class PayNodeMiddleware:
|
|
|
34
38
|
# Calculate raw amount (integer)
|
|
35
39
|
self.amount_int = int(float(price) * (10 ** decimals))
|
|
36
40
|
|
|
37
|
-
async def
|
|
41
|
+
async def dispatch(self, request: Request, call_next):
|
|
38
42
|
receipt_hash = request.headers.get('x-paynode-receipt')
|
|
39
43
|
order_id = request.headers.get('x-paynode-order-id')
|
|
40
44
|
|
|
@@ -78,6 +82,7 @@ class PayNodeMiddleware:
|
|
|
78
82
|
else:
|
|
79
83
|
# Validation Failed
|
|
80
84
|
err = result.get("error")
|
|
85
|
+
print(f"❌ [PayNode-PY] Verification Failed for Order: {order_id}. Reason: {str(err)}")
|
|
81
86
|
return JSONResponse(
|
|
82
87
|
status_code=403,
|
|
83
88
|
content={
|
paynode_sdk/verifier.py
CHANGED
|
@@ -1,36 +1,108 @@
|
|
|
1
|
-
from .errors import ErrorCode
|
|
2
|
-
from
|
|
1
|
+
from .errors import ErrorCode, PayNodeException
|
|
2
|
+
from .constants import PAYNODE_ROUTER_ABI, ACCEPTED_TOKENS, MIN_PAYMENT_AMOUNT
|
|
3
|
+
from .idempotency import MemoryIdempotencyStore
|
|
4
|
+
from web3 import Web3
|
|
3
5
|
|
|
4
6
|
class PayNodeVerifier:
|
|
5
|
-
def __init__(self, rpc_url=None, contract_address=None, chain_id=None, w3=None):
|
|
6
|
-
self.w3 = w3
|
|
7
|
+
def __init__(self, rpc_url=None, contract_address=None, chain_id=None, w3=None, store=None, accepted_tokens=None):
|
|
8
|
+
self.w3 = w3
|
|
9
|
+
if not self.w3 and rpc_url:
|
|
10
|
+
self.w3 = Web3(Web3.HTTPProvider(rpc_url))
|
|
7
11
|
self.contract_address = contract_address
|
|
8
|
-
self.
|
|
12
|
+
self.chain_id = int(chain_id) if chain_id else None
|
|
13
|
+
self.store = store or MemoryIdempotencyStore()
|
|
14
|
+
|
|
15
|
+
# Build accepted token set: user-provided or chain-default
|
|
16
|
+
# accepted_tokens=None → use chain default; accepted_tokens=[] → explicitly disable whitelist
|
|
17
|
+
if accepted_tokens is not None:
|
|
18
|
+
token_list = accepted_tokens
|
|
19
|
+
elif self.chain_id:
|
|
20
|
+
token_list = ACCEPTED_TOKENS.get(self.chain_id)
|
|
21
|
+
else:
|
|
22
|
+
token_list = None
|
|
23
|
+
self.accepted_tokens = set(t.lower() for t in token_list) if token_list else None
|
|
9
24
|
|
|
10
25
|
async def verify_payment(self, tx_hash, expected):
|
|
11
|
-
if
|
|
12
|
-
return {"isValid": False, "error":
|
|
13
|
-
|
|
14
|
-
#
|
|
26
|
+
if not self.w3:
|
|
27
|
+
return {"isValid": False, "error": PayNodeException("Verifier Provider Missing", ErrorCode.RPC_ERROR)}
|
|
28
|
+
|
|
29
|
+
# 0. Dust Exploit Check (Minimum Payment)
|
|
30
|
+
amount = int(expected.get("amount", 0))
|
|
31
|
+
if amount < MIN_PAYMENT_AMOUNT:
|
|
32
|
+
return {"isValid": False, "error": PayNodeException(
|
|
33
|
+
f"Payment amount {amount} is below the minimum threshold of {MIN_PAYMENT_AMOUNT}.",
|
|
34
|
+
ErrorCode.AMOUNT_TOO_LOW
|
|
35
|
+
)}
|
|
36
|
+
|
|
37
|
+
# 1. Token Whitelist Check (Anti-FakeToken)
|
|
38
|
+
expected_token = expected.get("tokenAddress", "").lower()
|
|
39
|
+
if self.accepted_tokens and expected_token not in self.accepted_tokens:
|
|
40
|
+
return {"isValid": False, "error": PayNodeException(
|
|
41
|
+
f"Token {expected.get('tokenAddress')} is not in the accepted whitelist.",
|
|
42
|
+
ErrorCode.TOKEN_NOT_ACCEPTED
|
|
43
|
+
)}
|
|
44
|
+
|
|
15
45
|
try:
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
46
|
+
is_new = await self.store.check_and_set(tx_hash, 86400) # 24 hour TTL
|
|
47
|
+
if not is_new:
|
|
48
|
+
return {"isValid": False, "error": PayNodeException("Receipt already used", ErrorCode.RECEIPT_ALREADY_USED)}
|
|
49
|
+
except Exception as e:
|
|
50
|
+
return {"isValid": False, "error": PayNodeException("Store Error", ErrorCode.INTERNAL_ERROR, details=str(e))}
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
receipt = self.w3.eth.get_transaction_receipt(tx_hash)
|
|
54
|
+
except Exception:
|
|
55
|
+
return {"isValid": False, "error": PayNodeException("Transaction not found", ErrorCode.TRANSACTION_NOT_FOUND)}
|
|
19
56
|
|
|
20
|
-
if tx_hash == "0xUsedHash":
|
|
21
|
-
return {"isValid": False, "error": MagicError(err_code)}
|
|
22
|
-
|
|
23
|
-
receipt = self.w3.eth.get_transaction_receipt(tx_hash)
|
|
24
57
|
if not receipt:
|
|
25
|
-
|
|
26
|
-
except AttributeError: return {"isValid": False, "error": MagicError(ErrorCode.PAYNODE_TRANSACTION_NOT_FOUND)}
|
|
58
|
+
return {"isValid": False, "error": PayNodeException("Transaction not found", ErrorCode.TRANSACTION_NOT_FOUND)}
|
|
27
59
|
|
|
28
60
|
if receipt.get("status") == 0:
|
|
29
|
-
|
|
30
|
-
except AttributeError: return {"isValid": False, "error": MagicError(ErrorCode.PAYNODE_TRANSACTION_FAILED)}
|
|
61
|
+
return {"isValid": False, "error": PayNodeException("Transaction failed", ErrorCode.TRANSACTION_FAILED)}
|
|
31
62
|
|
|
32
|
-
|
|
63
|
+
if not receipt.get("to") or receipt.get("to", "").lower() != self.contract_address.lower():
|
|
64
|
+
return {"isValid": False, "error": PayNodeException("Wrong contract", ErrorCode.WRONG_CONTRACT)}
|
|
65
|
+
|
|
66
|
+
contract = self.w3.eth.contract(address=Web3.to_checksum_address(self.contract_address), abi=PAYNODE_ROUTER_ABI)
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
logs = contract.events.PaymentReceived().process_receipt(receipt)
|
|
70
|
+
except Exception:
|
|
71
|
+
return {"isValid": False, "error": PayNodeException("Invalid receipt format", ErrorCode.INVALID_RECEIPT)}
|
|
72
|
+
|
|
73
|
+
if not logs:
|
|
74
|
+
return {"isValid": False, "error": PayNodeException("No valid PaymentReceived event found", ErrorCode.INVALID_RECEIPT)}
|
|
75
|
+
|
|
76
|
+
# Find the valid log
|
|
77
|
+
merchant = expected.get("merchantAddress", "").lower()
|
|
78
|
+
token = expected.get("tokenAddress", "").lower()
|
|
79
|
+
amount = int(expected.get("amount", 0))
|
|
80
|
+
|
|
81
|
+
order_id_bytes = self.w3.keccak(text=expected.get("orderId", ""))
|
|
33
82
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
83
|
+
valid = False
|
|
84
|
+
for log in logs:
|
|
85
|
+
args = log.args
|
|
86
|
+
|
|
87
|
+
if args.get("orderId") != order_id_bytes:
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
if args.get("merchant", "").lower() != merchant:
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
if args.get("token", "").lower() != token:
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
if args.get("amount", 0) < amount:
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
if self.chain_id and args.get("chainId") != self.chain_id:
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
valid = True
|
|
103
|
+
break
|
|
104
|
+
|
|
105
|
+
if not valid:
|
|
106
|
+
return {"isValid": False, "error": PayNodeException("Payment criteria mismatch", ErrorCode.INVALID_RECEIPT)}
|
|
107
|
+
|
|
108
|
+
return {"isValid": True}
|
paynode_sdk/webhook.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PayNode Webhook Notifier — monitors on-chain PaymentReceived events
|
|
3
|
+
and delivers structured webhook POSTs to a merchant's endpoint.
|
|
4
|
+
|
|
5
|
+
Features:
|
|
6
|
+
- HMAC-SHA256 signature for authenticity (header: x-paynode-signature)
|
|
7
|
+
- Configurable polling interval
|
|
8
|
+
- Automatic retry with exponential backoff (3 attempts)
|
|
9
|
+
- Async-first design
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import time
|
|
14
|
+
import hmac
|
|
15
|
+
import hashlib
|
|
16
|
+
import logging
|
|
17
|
+
import asyncio
|
|
18
|
+
from typing import Optional, Callable, Dict, Any, List
|
|
19
|
+
from web3 import Web3
|
|
20
|
+
|
|
21
|
+
from .constants import PAYNODE_ROUTER_ABI, PAYNODE_ROUTER_ADDRESS
|
|
22
|
+
from .errors import PayNodeException, ErrorCode
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger("paynode_sdk.webhook")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class PaymentEvent:
|
|
28
|
+
"""Parsed PaymentReceived event data."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
tx_hash: str,
|
|
33
|
+
block_number: int,
|
|
34
|
+
order_id: str,
|
|
35
|
+
merchant: str,
|
|
36
|
+
payer: str,
|
|
37
|
+
token: str,
|
|
38
|
+
amount: int,
|
|
39
|
+
fee: int,
|
|
40
|
+
chain_id: int,
|
|
41
|
+
timestamp: float
|
|
42
|
+
):
|
|
43
|
+
self.tx_hash = tx_hash
|
|
44
|
+
self.block_number = block_number
|
|
45
|
+
self.order_id = order_id
|
|
46
|
+
self.merchant = merchant
|
|
47
|
+
self.payer = payer
|
|
48
|
+
self.token = token
|
|
49
|
+
self.amount = amount
|
|
50
|
+
self.fee = fee
|
|
51
|
+
self.chain_id = chain_id
|
|
52
|
+
self.timestamp = timestamp
|
|
53
|
+
|
|
54
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
55
|
+
return {
|
|
56
|
+
"txHash": self.tx_hash,
|
|
57
|
+
"blockNumber": self.block_number,
|
|
58
|
+
"orderId": self.order_id,
|
|
59
|
+
"merchant": self.merchant,
|
|
60
|
+
"payer": self.payer,
|
|
61
|
+
"token": self.token,
|
|
62
|
+
"amount": str(self.amount),
|
|
63
|
+
"fee": str(self.fee),
|
|
64
|
+
"chainId": str(self.chain_id),
|
|
65
|
+
"timestamp": self.timestamp,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PayNodeWebhookNotifier:
|
|
70
|
+
"""
|
|
71
|
+
Monitors on-chain PaymentReceived events and delivers webhook notifications.
|
|
72
|
+
|
|
73
|
+
Usage:
|
|
74
|
+
notifier = PayNodeWebhookNotifier(
|
|
75
|
+
rpc_url="https://mainnet.base.org",
|
|
76
|
+
contract_address="0x92e20164FC457a2aC35f53D06268168e6352b200",
|
|
77
|
+
webhook_url="https://myshop.com/api/paynode-webhook",
|
|
78
|
+
webhook_secret="whsec_mysecretkey123",
|
|
79
|
+
)
|
|
80
|
+
await notifier.start()
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
rpc_url: str,
|
|
86
|
+
webhook_url: str,
|
|
87
|
+
webhook_secret: str,
|
|
88
|
+
contract_address: Optional[str] = None,
|
|
89
|
+
chain_id: Optional[int] = None,
|
|
90
|
+
poll_interval_seconds: float = 5.0,
|
|
91
|
+
custom_headers: Optional[Dict[str, str]] = None,
|
|
92
|
+
on_error: Optional[Callable[[Exception, PaymentEvent], None]] = None,
|
|
93
|
+
on_success: Optional[Callable[[PaymentEvent], None]] = None,
|
|
94
|
+
):
|
|
95
|
+
if not rpc_url:
|
|
96
|
+
raise ValueError("rpc_url is required")
|
|
97
|
+
if not webhook_url:
|
|
98
|
+
raise ValueError("webhook_url is required")
|
|
99
|
+
if not webhook_secret:
|
|
100
|
+
raise ValueError("webhook_secret is required")
|
|
101
|
+
|
|
102
|
+
self.contract_address = contract_address or PAYNODE_ROUTER_ADDRESS
|
|
103
|
+
self.w3 = Web3(Web3.HTTPProvider(rpc_url, request_kwargs={"timeout": 10}))
|
|
104
|
+
self.contract = self.w3.eth.contract(
|
|
105
|
+
address=Web3.to_checksum_address(self.contract_address),
|
|
106
|
+
abi=PAYNODE_ROUTER_ABI
|
|
107
|
+
)
|
|
108
|
+
self.webhook_url = webhook_url
|
|
109
|
+
self.webhook_secret = webhook_secret
|
|
110
|
+
self.chain_id = chain_id
|
|
111
|
+
self.poll_interval = poll_interval_seconds
|
|
112
|
+
self.custom_headers = custom_headers or {}
|
|
113
|
+
self.on_error = on_error
|
|
114
|
+
self.on_success = on_success
|
|
115
|
+
|
|
116
|
+
self._last_block: int = 0
|
|
117
|
+
self._running: bool = False
|
|
118
|
+
self._task: Optional[asyncio.Task] = None
|
|
119
|
+
|
|
120
|
+
async def start(self, from_block: Optional[int] = None) -> None:
|
|
121
|
+
"""Start polling for PaymentReceived events."""
|
|
122
|
+
if self._running:
|
|
123
|
+
logger.warning("[PayNode Webhook] Already running.")
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
self._last_block = from_block if from_block is not None else self.w3.eth.block_number
|
|
127
|
+
self._running = True
|
|
128
|
+
logger.info(f"🔔 [PayNode Webhook] Listening from block {self._last_block} on {self.contract_address}")
|
|
129
|
+
|
|
130
|
+
self._task = asyncio.create_task(self._poll_loop())
|
|
131
|
+
|
|
132
|
+
async def stop(self) -> None:
|
|
133
|
+
"""Stop polling."""
|
|
134
|
+
self._running = False
|
|
135
|
+
if self._task:
|
|
136
|
+
self._task.cancel()
|
|
137
|
+
try:
|
|
138
|
+
await self._task
|
|
139
|
+
except asyncio.CancelledError:
|
|
140
|
+
pass
|
|
141
|
+
self._task = None
|
|
142
|
+
logger.info("🔕 [PayNode Webhook] Stopped.")
|
|
143
|
+
|
|
144
|
+
async def _poll_loop(self) -> None:
|
|
145
|
+
"""Main polling loop."""
|
|
146
|
+
while self._running:
|
|
147
|
+
try:
|
|
148
|
+
current_block = self.w3.eth.block_number
|
|
149
|
+
if current_block > self._last_block:
|
|
150
|
+
events = self.contract.events.PaymentReceived().get_logs(
|
|
151
|
+
fromBlock=self._last_block + 1,
|
|
152
|
+
toBlock=current_block
|
|
153
|
+
)
|
|
154
|
+
for event in events:
|
|
155
|
+
payment = self._parse_event(event)
|
|
156
|
+
if payment:
|
|
157
|
+
await self._deliver(payment)
|
|
158
|
+
|
|
159
|
+
self._last_block = current_block
|
|
160
|
+
except Exception as e:
|
|
161
|
+
logger.error(f"[PayNode Webhook] Poll error: {e}")
|
|
162
|
+
|
|
163
|
+
await asyncio.sleep(self.poll_interval)
|
|
164
|
+
|
|
165
|
+
def _parse_event(self, event) -> Optional[PaymentEvent]:
|
|
166
|
+
"""Parse a web3 event log into a PaymentEvent."""
|
|
167
|
+
try:
|
|
168
|
+
args = event.args
|
|
169
|
+
return PaymentEvent(
|
|
170
|
+
tx_hash=event.transactionHash.hex() if hasattr(event.transactionHash, 'hex') else str(event.transactionHash),
|
|
171
|
+
block_number=event.blockNumber,
|
|
172
|
+
order_id=args.get("orderId", b"").hex() if isinstance(args.get("orderId"), bytes) else str(args.get("orderId", "")),
|
|
173
|
+
merchant=args.get("merchant", ""),
|
|
174
|
+
payer=args.get("payer", ""),
|
|
175
|
+
token=args.get("token", ""),
|
|
176
|
+
amount=args.get("amount", 0),
|
|
177
|
+
fee=args.get("fee", 0),
|
|
178
|
+
chain_id=args.get("chainId", 0),
|
|
179
|
+
timestamp=time.time(),
|
|
180
|
+
)
|
|
181
|
+
except Exception as e:
|
|
182
|
+
logger.error(f"[PayNode Webhook] Failed to parse event: {e}")
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
async def _deliver(self, event: PaymentEvent, attempt: int = 1) -> None:
|
|
186
|
+
"""Deliver webhook POST with HMAC signature and retry logic."""
|
|
187
|
+
import aiohttp # lazy import to keep dependency optional
|
|
188
|
+
|
|
189
|
+
MAX_RETRIES = 3
|
|
190
|
+
|
|
191
|
+
payload = json.dumps({
|
|
192
|
+
"event": "payment.received",
|
|
193
|
+
"data": event.to_dict()
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
signature = hmac.new(
|
|
197
|
+
self.webhook_secret.encode("utf-8"),
|
|
198
|
+
payload.encode("utf-8"),
|
|
199
|
+
hashlib.sha256
|
|
200
|
+
).hexdigest()
|
|
201
|
+
|
|
202
|
+
headers = {
|
|
203
|
+
"Content-Type": "application/json",
|
|
204
|
+
"x-paynode-signature": f"sha256={signature}",
|
|
205
|
+
"x-paynode-event": "payment.received",
|
|
206
|
+
"x-paynode-delivery-id": f"{event.tx_hash}-{attempt}",
|
|
207
|
+
**self.custom_headers,
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
async with aiohttp.ClientSession() as session:
|
|
212
|
+
async with session.post(self.webhook_url, data=payload, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as resp:
|
|
213
|
+
if resp.status >= 400:
|
|
214
|
+
raise PayNodeException(
|
|
215
|
+
f"Webhook returned {resp.status}",
|
|
216
|
+
ErrorCode.INTERNAL_ERROR
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
logger.info(f"✅ [PayNode Webhook] Delivered tx {event.tx_hash[:10]}... → {resp.status}")
|
|
220
|
+
if self.on_success:
|
|
221
|
+
self.on_success(event)
|
|
222
|
+
|
|
223
|
+
except Exception as e:
|
|
224
|
+
logger.error(f"[PayNode Webhook] Delivery failed (attempt {attempt}/{MAX_RETRIES}): {e}")
|
|
225
|
+
|
|
226
|
+
if attempt < MAX_RETRIES:
|
|
227
|
+
backoff = (2 ** attempt) # 2s, 4s, 8s
|
|
228
|
+
await asyncio.sleep(backoff)
|
|
229
|
+
return await self._deliver(event, attempt + 1)
|
|
230
|
+
|
|
231
|
+
logger.error(f"[PayNode Webhook] Gave up on tx {event.tx_hash} after {MAX_RETRIES} attempts.")
|
|
232
|
+
if self.on_error:
|
|
233
|
+
self.on_error(e, event)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: paynode-sdk-python
|
|
3
|
+
Version: 1.1.1
|
|
4
|
+
Summary: PayNode Protocol Python SDK for AI Agents
|
|
5
|
+
Author-email: PayNodeLabs <contact@paynode.dev>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/PayNodeLabs/paynode-sdk-python
|
|
8
|
+
Keywords: paynode,x402,base,agentic-web3,payments
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: requests>=2.31.0
|
|
12
|
+
Requires-Dist: web3>=6.15.0
|
|
13
|
+
Requires-Dist: python-dotenv>=1.0.1
|
|
14
|
+
Requires-Dist: fastapi>=0.111.0
|
|
15
|
+
Provides-Extra: test
|
|
16
|
+
Requires-Dist: pytest>=7.0.0; extra == "test"
|
|
17
|
+
Requires-Dist: responses>=0.23.0; extra == "test"
|
|
18
|
+
Requires-Dist: pytest-mock>=3.10.0; extra == "test"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# PayNode Python SDK
|
|
22
|
+
|
|
23
|
+
[](https://docs.paynode.dev)
|
|
24
|
+
[](https://pypi.org/project/paynode-sdk-python/)
|
|
25
|
+
|
|
26
|
+
The official Python SDK for the **PayNode Protocol**. PayNode allows autonomous AI Agents to seamlessly pay for APIs and computational resources using USDC on Base L2, utilizing the standardized HTTP 402 protocol.
|
|
27
|
+
|
|
28
|
+
## 📖 Read the Docs
|
|
29
|
+
|
|
30
|
+
**For complete installation guides, advanced usage, API references, and architecture details, please visit our official documentation:**
|
|
31
|
+
👉 **[docs.paynode.dev](https://docs.paynode.dev)**
|
|
32
|
+
|
|
33
|
+
## ⚡ Quick Start
|
|
34
|
+
|
|
35
|
+
### Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install paynode-sdk-python web3
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Agent Client (Payer)
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from paynode_sdk import PayNodeAgentClient
|
|
45
|
+
|
|
46
|
+
agent = PayNodeAgentClient(
|
|
47
|
+
private_key="YOUR_AGENT_PRIVATE_KEY",
|
|
48
|
+
rpc_urls=["https://mainnet.base.org", "https://rpc.ankr.com/base"]
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Automatically handles the 402 challenge, executes the Base L2 transaction, and gets the data.
|
|
52
|
+
response = agent.request_gate("https://api.merchant.com/premium-data", method="POST", json={"agent": "PythonAgent"})
|
|
53
|
+
|
|
54
|
+
print(response.json())
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## 🚀 Run the Demo
|
|
58
|
+
|
|
59
|
+
The SDK includes a complete Merchant/Agent demo in the `examples/` directory.
|
|
60
|
+
|
|
61
|
+
### 1. Setup Environment
|
|
62
|
+
|
|
63
|
+
Copy the example environment file and fill in your keys:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
cp .env.example .env
|
|
67
|
+
# Edit .env with your private key and RPC URLs
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 2. Run the Merchant Server (FastAPI)
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
python examples/fastapi_server.py
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 3. Run the Agent Client
|
|
77
|
+
|
|
78
|
+
In another terminal:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
python examples/agent_client.py
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The demo will perform a full loop: `402 Handshake -> On-chain Payment -> 200 Verification`.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## 📦 Publishing to PyPI
|
|
89
|
+
|
|
90
|
+
To publish a new version of the SDK:
|
|
91
|
+
|
|
92
|
+
1. **Install build tools**:
|
|
93
|
+
```bash
|
|
94
|
+
pip install build twine
|
|
95
|
+
```
|
|
96
|
+
2. **Build the package**:
|
|
97
|
+
```bash
|
|
98
|
+
python -m build
|
|
99
|
+
```
|
|
100
|
+
3. **Upload to PyPI**:
|
|
101
|
+
```bash
|
|
102
|
+
python -m twine upload dist/*
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
_Built for the Autonomous AI Economy by PayNodeLabs._
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
paynode_sdk/__init__.py,sha256=p6URBqxFz1AErG7rIRWKnfwnzAC19qrMURtG7YhVR1I,821
|
|
2
|
+
paynode_sdk/client.py,sha256=jseyOrGPq7VQdufScIQsxrEEwK2WWoIQdEmGOfkTEls,10584
|
|
3
|
+
paynode_sdk/constants.py,sha256=puqz09qeKcMoigWrqdIzkhtAzFpECxEwHGLvDd3U_CQ,1429
|
|
4
|
+
paynode_sdk/errors.py,sha256=GN0qycgjATT47dF4yZ6Ulg18jf2OwholvYl0pgCvuzo,1121
|
|
5
|
+
paynode_sdk/idempotency.py,sha256=od7HuSxFdejBP0oE4QCzbJdrDZWvziiu09d3BRErU2k,999
|
|
6
|
+
paynode_sdk/middleware.py,sha256=Hi7dgbDy_moVnHl8f31YPsl_a3mSygIDAb_nCO9CMLY,3519
|
|
7
|
+
paynode_sdk/verifier.py,sha256=rIjRxPZDSWKbf9ghfCu5JJ7Q8oPy0SQprgZWxQiggEg,4795
|
|
8
|
+
paynode_sdk/webhook.py,sha256=KxlXGkXe3wpR8ueO8FMW2iypJgWaLwMfxAAZLNRvNDo,8302
|
|
9
|
+
paynode_sdk_python-1.1.1.dist-info/licenses/LICENSE,sha256=U8RjGlEBtXN6PA-qN_N3Uh60jyu3qe26ZBmgt-LAHc4,1069
|
|
10
|
+
paynode_sdk_python-1.1.1.dist-info/METADATA,sha256=G-9GKKJuNBK6Zz2MwcMDDJpAm2b-LvDjKR3VMQyvHLQ,2858
|
|
11
|
+
paynode_sdk_python-1.1.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
12
|
+
paynode_sdk_python-1.1.1.dist-info/top_level.txt,sha256=c6Skc1Xx-9O-JJ7sHghLW8Kyn4hyJoVPUawH1Mu8iTU,12
|
|
13
|
+
paynode_sdk_python-1.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PayNode Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: paynode-sdk-python
|
|
3
|
-
Version: 1.0.1
|
|
4
|
-
Summary: PayNode Protocol Python SDK for AI Agents
|
|
5
|
-
Author-email: PayNodeLabs <contact@paynode.dev>
|
|
6
|
-
License: MIT
|
|
7
|
-
Project-URL: Homepage, https://github.com/PayNodeLabs/paynode-sdk-python
|
|
8
|
-
Keywords: paynode,x402,base,agentic-web3,payments
|
|
9
|
-
Description-Content-Type: text/markdown
|
|
10
|
-
Requires-Dist: requests>=2.31.0
|
|
11
|
-
Requires-Dist: web3>=6.15.0
|
|
12
|
-
Requires-Dist: python-dotenv>=1.0.1
|
|
13
|
-
|
|
14
|
-
# PayNode Python SDK
|
|
15
|
-
|
|
16
|
-
为 Python 开发者提供的 PayNode 支付网关 SDK,支持 FastAPI、Flask 等主流 Web 框架。实现 M2M 场景下的 x402 握手与链上支付验证。
|
|
17
|
-
|
|
18
|
-
## 📦 安装
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
pip install paynode-sdk
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
## 🚀 FastAPI Middleware 初始化示例
|
|
25
|
-
|
|
26
|
-
通过注入 `PayNodeMiddleware`,您可以轻松地将任何 API 端点转变为收费接口。
|
|
27
|
-
|
|
28
|
-
```python
|
|
29
|
-
from fastapi import FastAPI, Request
|
|
30
|
-
from paynode_sdk import PayNodeMiddleware
|
|
31
|
-
|
|
32
|
-
app = FastAPI()
|
|
33
|
-
|
|
34
|
-
# 1. 初始化 PayNode 中间件
|
|
35
|
-
paynode = PayNodeMiddleware(
|
|
36
|
-
rpc_url="https://mainnet.base.org", # RPC 节点地址
|
|
37
|
-
contract_address="0x...", # PayNodeRouter 合约地址
|
|
38
|
-
merchant_address="0x...", # 商家收款钱包地址
|
|
39
|
-
chain_id=8453, # 链 ID (Base: 8453)
|
|
40
|
-
currency="USDC", # 计价单位
|
|
41
|
-
token_address="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", # USDC 地址
|
|
42
|
-
price="0.01", # 每次调用的价格
|
|
43
|
-
decimals=6 # 代币精度
|
|
44
|
-
)
|
|
45
|
-
|
|
46
|
-
# 2. 挂载中间件
|
|
47
|
-
@app.middleware("http")
|
|
48
|
-
async def paynode_gate(request: Request, call_next):
|
|
49
|
-
# 此中间件会自动处理 402 握手及 x-paynode-receipt 验证
|
|
50
|
-
return await paynode(request, call_next)
|
|
51
|
-
|
|
52
|
-
# 3. 受保护的路由
|
|
53
|
-
@app.get("/api/ai-vision")
|
|
54
|
-
async def ai_feature():
|
|
55
|
-
return {"message": "Success! The agent has paid for this API call."}
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
## 🧪 测试与开发
|
|
59
|
-
|
|
60
|
-
SDK 采用严谨的代码审计标准,所有核心逻辑均经过多层验证。
|
|
61
|
-
|
|
62
|
-
### 运行测试
|
|
63
|
-
|
|
64
|
-
使用 `pytest` 运行测试套件。确保已配置 `PYTHONPATH` 以正确加载本地包。
|
|
65
|
-
|
|
66
|
-
```bash
|
|
67
|
-
# 运行所有验证逻辑测试
|
|
68
|
-
PYTHONPATH=. pytest tests/
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
### 开发模式
|
|
72
|
-
|
|
73
|
-
如果需要修改 `paynode_sdk` 并即时测试:
|
|
74
|
-
|
|
75
|
-
```bash
|
|
76
|
-
pip install -e .
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
## ⚙️ 验证逻辑详解 (Verifier)
|
|
80
|
-
|
|
81
|
-
`PayNodeVerifier` 直接通过 Web3.py 与以太坊节点交互。验证过程包括:
|
|
82
|
-
- **交易状态确认:** 检查交易哈希是否已上链并成功 (Status 1)。
|
|
83
|
-
- **合约交互验证:** 解析交易数据,确认其调用的是 `PayNodeRouter` 的 `pay` 函数。
|
|
84
|
-
- **金额与代币校验:** 严格匹配转账金额与指定的代币地址,防止恶意 Agent 使用虚假代币支付。
|
|
85
|
-
- **商户一致性:** 确认资金最终流向了预设的商户钱包。
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
paynode_sdk/__init__.py,sha256=qIoMcnfe3dviK6E3E0yMYukuvbO3Nmv0Cpuaeptgx3s,325
|
|
2
|
-
paynode_sdk/client.py,sha256=3_Rux6DZyR6dABLjYaAtBmBtPczlLVpyvuDXc6UzFuQ,4933
|
|
3
|
-
paynode_sdk/constants.py,sha256=1WHbiwQSrSUI6jj4xo7ISak_X0eDZMgFnCbeLzUl3JM,309
|
|
4
|
-
paynode_sdk/errors.py,sha256=ZiuYEvP8zMXpfmi3VEdGyBX3VXqj4TdrRS-WucrdSew,977
|
|
5
|
-
paynode_sdk/idempotency.py,sha256=od7HuSxFdejBP0oE4QCzbJdrDZWvziiu09d3BRErU2k,999
|
|
6
|
-
paynode_sdk/middleware.py,sha256=dg3hSmHAjW8wTF3AH3id8LFxbN2kXKKUsBRp1gyc6qw,3292
|
|
7
|
-
paynode_sdk/verifier.py,sha256=YkYUBgt5RPXigZsHNvdcca290YQyoOVijIa6f5SlHLw,1572
|
|
8
|
-
paynode_sdk_python-1.0.1.dist-info/METADATA,sha256=EcJUyKLTNco58bzxeuzOEd73Fvp3ScRS8SsVYwB9OHk,2852
|
|
9
|
-
paynode_sdk_python-1.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
-
paynode_sdk_python-1.0.1.dist-info/top_level.txt,sha256=c6Skc1Xx-9O-JJ7sHghLW8Kyn4hyJoVPUawH1Mu8iTU,12
|
|
11
|
-
paynode_sdk_python-1.0.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|