-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebhook-server.ts
More file actions
164 lines (137 loc) · 4.05 KB
/
webhook-server.ts
File metadata and controls
164 lines (137 loc) · 4.05 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
/**
* AgentGatePay SDK - Webhook Server Example
*
* Express.js server that handles AgentPay webhooks
*
* Requires: npm install express body-parser
*/
import express from 'express';
import bodyParser from 'body-parser';
import { AgentGatePay } from '../src';
const app = express();
const PORT = 3000;
// IMPORTANT: Use raw body parser for webhook signature verification
app.use(bodyParser.json({
verify: (req: any, res, buf) => {
req.rawBody = buf.toString('utf8');
}
}));
// Initialize AgentPay client
const client = new AgentGatePay({
apiKey: process.env.AGENTPAY_API_KEY!
});
// Webhook secret (get this from webhook configuration)
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'my-webhook-secret-123';
/**
* Webhook endpoint
* Receives payment notifications from AgentPay
*/
app.post('/agentpay-webhook', async (req, res) => {
try {
// Get signature from header
const signature = req.headers['x-agentpay-signature'] as string;
if (!signature) {
console.error('Missing signature header');
return res.status(400).json({ error: 'Missing signature' });
}
// Verify and parse webhook payload
const payload = client.webhooks.verifyAndParse(
(req as any).rawBody,
signature,
WEBHOOK_SECRET
);
console.log(`\n=== Webhook Received: ${payload.type} ===`);
console.log(`TX Hash: ${payload.data.txHash}`);
console.log(`Amount: $${payload.data.amountUsd}`);
console.log(`From: ${payload.data.sender}`);
console.log(`To: ${payload.data.recipient}`);
console.log(`Token: ${payload.data.token} on ${payload.data.chain}`);
console.log(`Timestamp: ${payload.data.timestamp}\n`);
// Handle different event types
switch (payload.type) {
case 'payment.completed':
await handlePaymentCompleted(payload.data);
break;
case 'payment.failed':
await handlePaymentFailed(payload.data);
break;
case 'payment.pending':
await handlePaymentPending(payload.data);
break;
default:
console.log(`Unknown event type: ${payload.type}`);
}
// Respond with success
res.json({ received: true });
} catch (error: any) {
console.error('Webhook error:', error.message);
res.status(400).json({ error: error.message });
}
});
/**
* Handle completed payment
*/
async function handlePaymentCompleted(data: any) {
console.log('✓ Payment completed - granting access to service');
// TODO: Your business logic here
// - Grant access to resource
// - Update database
// - Send confirmation email
// - etc.
}
/**
* Handle failed payment
*/
async function handlePaymentFailed(data: any) {
console.log('✗ Payment failed - notifying user');
// TODO: Your business logic here
// - Notify user
// - Log failure
// - etc.
}
/**
* Handle pending payment
*/
async function handlePaymentPending(data: any) {
console.log('⏳ Payment pending - waiting for confirmation');
// TODO: Your business logic here
// - Show pending status
// - Wait for completion
// - etc.
}
/**
* Health check endpoint
*/
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
/**
* Test webhook configuration
*/
app.post('/test-webhook', async (req, res) => {
try {
// Configure webhook
const webhook = await client.webhooks.create(
`http://localhost:${PORT}/agentpay-webhook`,
['payment.completed', 'payment.failed'],
WEBHOOK_SECRET
);
console.log('Webhook configured:', webhook.webhookId);
// Test webhook delivery
await client.webhooks.test(webhook.webhookId);
res.json({
success: true,
webhookId: webhook.webhookId,
message: 'Webhook configured and tested'
});
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Start server
app.listen(PORT, () => {
console.log(`\n=== AgentPay Webhook Server ===`);
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: http://localhost:${PORT}/agentpay-webhook`);
console.log(`\nReady to receive payment notifications!\n`);
});