-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend-example.js
More file actions
268 lines (228 loc) · 8.63 KB
/
backend-example.js
File metadata and controls
268 lines (228 loc) · 8.63 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Backend API Example for Web Design Website
// This is a Node.js/Express example showing how to handle Stripe and Dynadot API integrations
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const cors = require('cors');
const axios = require('axios');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors({
origin: ['https://mattjhagen.github.io', 'https://packie-designs.onrender.com'],
credentials: true
}));
app.use(express.json());
// Environment variables (set these in your .env file)
const DYNADOT_API_KEY = process.env.DYNADOT_API_KEY;
const DYNADOT_API_URL = 'https://api.dynadot.com/api3.json';
const COMMISSION_RATE = 0.15; // 15% commission
// Stripe webhook endpoint (for handling successful payments)
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
} catch (err) {
console.log(`Webhook signature verification failed.`, err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log('Payment succeeded:', paymentIntent.id);
// Here you would typically:
// 1. Update your database
// 2. Send confirmation email
// 3. Start the web design project
break;
case 'invoice.payment_succeeded':
const invoice = event.data.object;
console.log('Subscription payment succeeded:', invoice.id);
// Handle successful subscription payment
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
res.json({received: true});
});
// Create payment intent for one-time website payments
app.post('/api/create-payment-intent', async (req, res) => {
try {
const { amount, currency = 'usd', plan } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: currency,
metadata: {
plan: plan,
type: 'website_design'
}
});
res.json({
clientSecret: paymentIntent.client_secret
});
} catch (error) {
console.error('Error creating payment intent:', error);
res.status(500).json({ error: 'Failed to create payment intent' });
}
});
// Create subscription for monthly maintenance
app.post('/api/create-subscription', async (req, res) => {
try {
const { price, currency = 'usd', plan } = req.body;
// First, create a Stripe price if it doesn't exist
const stripePrice = await stripe.prices.create({
unit_amount: price,
currency: currency,
recurring: { interval: 'month' },
product_data: {
name: plan,
description: `Monthly maintenance and hosting for ${plan}`
}
});
// Create a setup intent for the subscription
const setupIntent = await stripe.setupIntents.create({
payment_method_types: ['card'],
usage: 'off_session'
});
res.json({
clientSecret: setupIntent.client_secret,
priceId: stripePrice.id
});
} catch (error) {
console.error('Error creating subscription:', error);
res.status(500).json({ error: 'Failed to create subscription' });
}
});
// Check domain availability using Dynadot API
app.post('/api/check-domain', async (req, res) => {
try {
const { domain, apiKey } = req.body;
// Validate domain format
const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,}$/;
if (!domainRegex.test(domain)) {
return res.status(400).json({ error: 'Invalid domain format' });
}
// Call Dynadot API to check availability
const response = await axios.post(DYNADOT_API_URL, {
key: apiKey,
command: 'search',
domain0: domain
});
const data = response.data;
if (data.SearchResponse && data.SearchResponse.SearchResult) {
const result = data.SearchResponse.SearchResult;
const isAvailable = result.Available === 'yes';
res.json({
domain: domain,
available: isAvailable,
price: isAvailable ? parseFloat(result.Price) || 12.99 : null
});
} else {
throw new Error('Invalid response from Dynadot API');
}
} catch (error) {
console.error('Error checking domain:', error);
res.status(500).json({ error: 'Failed to check domain availability' });
}
});
// Create payment intent for domain purchase
app.post('/api/create-domain-payment', async (req, res) => {
try {
const { domain, price, commission } = req.body;
const totalAmount = (price + commission) * 100; // Convert to cents
const paymentIntent = await stripe.paymentIntents.create({
amount: totalAmount,
currency: 'usd',
metadata: {
domain: domain,
domainPrice: price,
commission: commission,
type: 'domain_purchase'
}
});
res.json({
clientSecret: paymentIntent.client_secret
});
} catch (error) {
console.error('Error creating domain payment intent:', error);
res.status(500).json({ error: 'Failed to create domain payment intent' });
}
});
// Purchase domain after successful payment
app.post('/api/purchase-domain', async (req, res) => {
try {
const { domain, paymentIntentId } = req.body;
// Verify the payment was successful
const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
if (paymentIntent.status !== 'succeeded') {
return res.status(400).json({ error: 'Payment not completed' });
}
// Call Dynadot API to purchase the domain
const response = await axios.post(DYNADOT_API_URL, {
key: DYNADOT_API_KEY,
command: 'register',
domain: domain,
years: 1
});
if (response.data.RegisterResponse && response.data.RegisterResponse.RegisterResult) {
const result = response.data.RegisterResponse.RegisterResult;
if (result.Success === 'yes') {
res.json({
success: true,
domain: domain,
orderId: result.OrderId
});
} else {
res.status(400).json({
error: 'Domain purchase failed',
message: result.Message || 'Unknown error'
});
}
} else {
throw new Error('Invalid response from Dynadot API');
}
} catch (error) {
console.error('Error purchasing domain:', error);
res.status(500).json({ error: 'Failed to purchase domain' });
}
});
// Get pricing information
app.get('/api/pricing', (req, res) => {
const pricing = {
website: {
basic: { name: 'Basic Website', price: 2500, type: 'one-time' },
professional: { name: 'Professional Website', price: 3500, type: 'one-time' },
premium: { name: 'Premium Website', price: 4500, type: 'one-time' }
},
maintenance: {
basic: { name: 'Basic Maintenance', price: 150, type: 'monthly' },
premium: { name: 'Premium Maintenance', price: 300, type: 'monthly' }
}
};
res.json(pricing);
});
// Health check endpoint
app.get('/api/health', (req, res) => {
res.json({ status: 'OK', timestamp: new Date().toISOString() });
});
// Test endpoint for frontend
app.get('/api/test', (req, res) => {
res.json({
message: 'Backend is working!',
timestamp: new Date().toISOString(),
frontend: 'https://mattjhagen.github.io/packie-designs/'
});
});
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Unhandled error:', error);
res.status(500).json({ error: 'Internal server error' });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Health check: http://localhost:${PORT}/api/health`);
});
module.exports = app;