-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPayment.js
More file actions
82 lines (69 loc) · 2.77 KB
/
Copy pathPayment.js
File metadata and controls
82 lines (69 loc) · 2.77 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
import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { loadStripe } from '@stripe/stripe-js';
import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import axios from 'axios';
// 🔥 YOUR STRIPE KEY IS NOW ADDED BELOW 🔥
const stripePromise = loadStripe('pk_test_51SflxBQq5TlEKg0sD7xDEGgmC4LGsYlVXNVbtYAZEjxmEtuIgzTlUQM20rmAtbZ1qEIV0xZ15LPOp5UU9gXJzVsI00AX1ZnS0S');
const CheckoutForm = ({ courseId }) => {
const stripe = useStripe();
const elements = useElements();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const handleSubmit = async (event) => {
event.preventDefault();
setLoading(true);
if (!stripe || !elements) return;
// 1. Create Payment Method (The "Token")
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement),
});
if (!error) {
try {
const { id } = paymentMethod;
const user = JSON.parse(localStorage.getItem('userInfo'));
// 2. Charge the Card
await axios.post('https://studysync-backend-gnzb.onrender.com/api/payment', {
amount: 1000,
id,
});
// 3. 🔥 ENROLL THE USER IN DATABASE 🔥
const config = { headers: { Authorization: `Bearer ${user.token}` } };
await axios.post('https://studysync-backend-gnzb.onrender.com/api/users/enroll', { courseId }, config);
alert('Payment Successful! You are now enrolled.');
navigate('/dashboard');
} catch (error) {
console.error(error);
alert('Payment or Enrollment Failed. Please try again.');
}
} else {
console.log(error.message);
alert(error.message);
}
setLoading(false);
};
return (
<form onSubmit={handleSubmit} style={{ maxWidth: '400px', margin: '0 auto', padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}>
<h3>Enter Card Details</h3>
<div style={{ border: '1px solid #ccc', padding: '10px', borderRadius: '4px', marginBottom: '20px' }}>
<CardElement />
</div>
<button type="submit" disabled={!stripe || loading} style={{ width: '100%', padding: '10px', backgroundColor: '#4CAF50', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>
{loading ? 'Processing...' : 'Pay Now'}
</button>
</form>
);
};
const Payment = () => {
const { id } = useParams();
return (
<Elements stripe={stripePromise}>
<div style={{ padding: '50px', textAlign: 'center' }}>
<h1>Complete Your Purchase</h1>
<CheckoutForm courseId={id} />
</div>
</Elements>
);
};
export default Payment;