Skip to content

Commit

Permalink
- feat: add base stripe methods
Browse files Browse the repository at this point in the history
  • Loading branch information
VasylHryha committed Dec 17, 2024
1 parent ad290c0 commit ae59990
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 0 deletions.
34 changes: 34 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
"dependencies": {
"@supabase/supabase-js": "^2.45.4",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"stripe": "^17.3.1",
"uuid": "^10.0.0"
},
"engines": {
Expand Down
44 changes: 44 additions & 0 deletions routes/checkout-sesssion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const express = require('express');
const Stripe = require('stripe');
const router = express.Router();

const stripe = new Stripe('process.env.STRIPE_SECRET_KEY', {
apiVersion: '2020-08-27',
});

router.post('/create-session', async (req, res) => {
const { amount = 500, product = 'test', quantity = 1 } = req.body;

// Validate that amount, product, and quantity are provided in the request
if (!amount || !product || !quantity) {
return res.status(400).json({ error: 'Amount, product, and quantity are required.' });
}

try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: product,
},
unit_amount: amount, // Amount should be in cents, e.g., $50 = 5000
},
quantity: quantity,
},
],
mode: 'payment',
success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/cancel`,
});

res.json({ id: session.id });
} catch (error) {
console.error('Error creating checkout session:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

module.exports = router;
5 changes: 5 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ const express = require('express');
const router = express.Router();
const userRoutes = require('./users');
const rootRoutes = require('./root');
const checkoutSession = require('./checkout-sesssion')
const stripeApi = require('./stripe');

router.use('/users', userRoutes);
router.use('/', rootRoutes);
router.use('/api/checkout', checkoutSession);
router.use('/api', stripeApi);


module.exports = router;
93 changes: 93 additions & 0 deletions routes/stripe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
const express = require('express');
const Stripe = require('stripe');
const cors = require('cors'); // Import the CORS middleware

const router = express.Router();

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
});

const HARD_CODED_CUSTOMER_ID = 'cus_RPmbpSyKY0cF1N'; // Hard-coded customer ID for testing purposes

// Enable CORS for all routes in this router
router.use(cors()); // Allow cross-origin requests for all routes in this router

// Route to retrieve all saved payment methods for a customer
router.get('/payment-method', async (req, res) => {
try {
const paymentMethods = await stripe.paymentMethods.list({
customer: HARD_CODED_CUSTOMER_ID,
type: 'card',
});

res.status(200).json({
status: 'success',
message: 'Payment methods retrieved successfully.',
data: paymentMethods.data,
});
} catch (error) {
console.error('Error fetching payment methods:', error.message);
res.status(500).json({
status: 'error',
message: 'Failed to fetch payment methods.',
data: null,
});
}
});

// Route to remove a payment method
router.delete('/payment-method/:id', async (req, res) => {
const { id } = req.params;

try {
await stripe.paymentMethods.detach(id);

res.status(200).json({
status: 'success',
message: 'Payment method removed successfully.',
data: { id },
});
} catch (error) {
console.error('Error removing payment method:', error.message);
res.status(500).json({
status: 'error',
message: 'Failed to remove payment method.',
data: null,
});
}
});

// Route to attach a payment method to a customer
router.put('/payment-method', async (req, res) => {
const { paymentMethodId } = req.body;

if (!paymentMethodId) {
return res.status(400).json({
status: 'error',
message: 'Payment Method ID is required.',
data: null,
});
}

try {
const paymentMethod = await stripe.paymentMethods.attach(paymentMethodId, {
customer: HARD_CODED_CUSTOMER_ID,
});

res.status(200).json({
status: 'success',
message: 'Payment method added successfully.',
data: paymentMethod,
});
} catch (error) {
console.error('Error adding payment method:', error.message);
res.status(500).json({
status: 'error',
message: 'Failed to add payment method.',
data: null,
});
}
});

module.exports = router;

0 comments on commit ae59990

Please sign in to comment.