Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

E-commerce #34

Open
elicharlese opened this issue Feb 6, 2023 · 0 comments
Open

E-commerce #34

elicharlese opened this issue Feb 6, 2023 · 0 comments
Assignees
Labels
bug Something isn't working

Comments

@elicharlese
Copy link
Member

elicharlese commented Feb 6, 2023

Products Page

First, we'll create a new component called ProductsPage:

import React from 'react';
import { Container, Grid, Typography } from '@material-ui/core';

function ProductsPage() {
  return (
    <Container maxWidth="lg">
      <Typography variant="h4" gutterBottom>
        Products
      </Typography>
      <Grid container spacing={2}>
        {/* Product items go here */}
      </Grid>
    </Container>
  );
}

export default ProductsPage;

In this example, we're using the Container and Grid components from Material-UI to lay out our page. We've also added a Typography component to display the page title.

Next, we'll add some example product items to our ProductsPage:

import React from 'react';
import { Container, Grid, Typography, Card, CardMedia, CardContent, CardActions, Button } from '@material-ui/core';

const products = [
  {
    id: 1,
    name: 'Product 1',
    description: 'This is a description of product 1',
    price: 10.99,
    image: 'https://via.placeholder.com/300x200.png?text=Product+1',
  },
  {
    id: 2,
    name: 'Product 2',
    description: 'This is a description of product 2',
    price: 12.99,
    image: 'https://via.placeholder.com/300x200.png?text=Product+2',
  },
  {
    id: 3,
    name: 'Product 3',
    description: 'This is a description of product 3',
    price: 15.99,
    image: 'https://via.placeholder.com/300x200.png?text=Product+3',
  },
];

function ProductsPage() {
  return (
    <Container maxWidth="lg">
      <Typography variant="h4" gutterBottom>
        Products
      </Typography>
      <Grid container spacing={2}>
        {products.map((product) => (
          <Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
            <Card>
              <CardMedia
                image={product.image}
                title={product.name}
                style={{ height: 200 }}
              />
              <CardContent>
                <Typography gutterBottom variant="h5" component="h2">
                  {product.name}
                </Typography>
                <Typography variant="body2" color="textSecondary" component="p">
                  {product.description}
                </Typography>
              </CardContent>
              <CardActions>
                <Typography variant="h6" color="textPrimary" style={{ flexGrow: 1 }}>
                  ${product.price.toFixed(2)}
                </Typography>
                <Button size="small" color="primary">
                  Add to Cart
                </Button>
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>
    </Container>
  );
}

export default ProductsPage;

In this example, we're using the Card component from Material-UI to display each product item. We're also using the Grid component to lay out the product items in a responsive grid. The xs, sm, md, and lg props are used to specify the number of columns each item should span at different screen sizes.

Finally, we can import and render our ProductsPage component in our dashboard:

import React from 'react';
import ProductsPage from './ProductsPage';

function Dashboard() {
  return (
    <div>
      <h1>Welcome to the Dashboard</h1>
      <ProductsPage />
    </div>
  );
}

export default Dashboard;

Assuming that the ProductsPage component is exported from the ProductsPage.js file and that the Dashboard component is the main component for the dashboard, this code will render the ProductsPage component in the dashboard below the "Welcome to the Dashboard" header.

It displays a table with products information and a form to add new products.

import React, { useState } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TextField,
  Button,
  Typography,
  Grid
} from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    margin: theme.spacing(3)
  },
  table: {
    minWidth: 650,
  },
  form: {
    margin: theme.spacing(3)
  },
  textField: {
    marginRight: theme.spacing(2),
  },
  addButton: {
    marginTop: theme.spacing(2),
  },
}));

const Products = () => {
  const classes = useStyles();
  const [products, setProducts] = useState([
    { id: 1, name: 'Product 1', price: 10.00 },
    { id: 2, name: 'Product 2', price: 20.00 },
    { id: 3, name: 'Product 3', price: 30.00 }
  ]);
  const [newProduct, setNewProduct] = useState({ name: '', price: 0 });

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setNewProduct({ ...newProduct, [name]: value });
  };

  const handleAddProduct = () => {
    const newId = products.length + 1;
    const newProductWithId = { id: newId, ...newProduct };
    setProducts([...products, newProductWithId]);
    setNewProduct({ name: '', price: 0 });
  };

  return (
    <div className={classes.root}>
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Typography variant="h5" component="h2">Products</Typography>
        </Grid>
        <Grid item xs={12}>
          <TableContainer component={Paper}>
            <Table className={classes.table} aria-label="Products table">
              <TableHead>
                <TableRow>
                  <TableCell>ID</TableCell>
                  <TableCell>Name</TableCell>
                  <TableCell>Price</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {products.map((product) => (
                  <TableRow key={product.id}>
                    <TableCell>{product.id}</TableCell>
                    <TableCell>{product.name}</TableCell>
                    <TableCell>{product.price}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Grid>
        <Grid item xs={12}>
          <form className={classes.form} noValidate autoComplete="off">
            <TextField className={classes.textField} label="Name" name="name" value={newProduct.name} onChange={handleInputChange} />
            <TextField className={classes.textField} label="Price" name="price" value={newProduct.price} onChange={handleInputChange} />
            <Button className={classes.addButton} variant="contained" color="primary" onClick={handleAddProduct}>Add Product</Button>
          </form>
        </Grid>
      </Grid>
    </div>
  );
};

export default Products;

Cart Page

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@material-ui/core';

const useStyles = makeStyles({
  table: {
    minWidth: 650,
  },
});

function CartPage() {
  const classes = useStyles();

  const cartItems = [
    { id: 1, name: 'Product 1', price: 10.00, quantity: 2 },
    { id: 2, name: 'Product 2', price: 5.00, quantity: 3 },
    { id: 3, name: 'Product 3', price: 15.00, quantity: 1 },
  ];

  const subtotal = cartItems.reduce((acc, item) => acc + (item.price * item.quantity), 0);

  return (
    <div>
      <Typography variant="h5">Shopping Cart</Typography>
      <TableContainer component={Paper}>
        <Table className={classes.table} aria-label="shopping cart table">
          <TableHead>
            <TableRow>
              <TableCell>Product</TableCell>
              <TableCell align="right">Price</TableCell>
              <TableCell align="right">Quantity</TableCell>
              <TableCell align="right">Total</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {cartItems.map((item) => (
              <TableRow key={item.id}>
                <TableCell component="th" scope="row">
                  {item.name}
                </TableCell>
                <TableCell align="right">${item.price.toFixed(2)}</TableCell>
                <TableCell align="right">{item.quantity}</TableCell>
                <TableCell align="right">${(item.price * item.quantity).toFixed(2)}</TableCell>
              </TableRow>
            ))}
            <TableRow>
              <TableCell rowSpan={3} />
              <TableCell colSpan={2}>Subtotal</TableCell>
              <TableCell align="right">${subtotal.toFixed(2)}</TableCell>
            </TableRow>
            <TableRow>
              <TableCell colSpan={2}>Tax</TableCell>
              <TableCell align="right">${(subtotal * 0.1).toFixed(2)}</TableCell>
            </TableRow>
            <TableRow>
              <TableCell colSpan={2}>Total</TableCell>
              <TableCell align="right">${(subtotal * 1.1).toFixed(2)}</TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

export default CartPage;

This code defines a CartPage component that displays a shopping cart with a list of items and a subtotal, tax, and total calculated based on the prices and quantities of the items. The Table component from Material-UI is used to display the cart items in a table, and the TableContainer, TableHead, TableBody, TableRow, and TableCell components are used to structure the table.

To use this component in the dashboard, you can import and render it just like you would any other component:

import React from 'react';
import CartPage from './CartPage';

function Dashboard() {
  return (
    <div>
      <h1>Welcome to the Dashboard</h1>
      <CartPage />
    </div>
  );
}

export default Dashboard;

This will render the CartPage component in the dashboard.

Thank You Page

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    marginTop: theme.spacing(8),
    marginBottom: theme.spacing(8),
  },
  icon: {
    fontSize: '80px',
    marginBottom: theme.spacing(3),
    color: theme.palette.success.main,
  },
  title: {
    marginBottom: theme.spacing(2),
  },
  message: {
    textAlign: 'center',
    marginBottom: theme.spacing(4),
  },
  button: {
    marginBottom: theme.spacing(4),
  },
}));

function ThankYouPage() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Typography className={classes.icon}>
        <i className="fas fa-check-circle"></i>
      </Typography>
      <Typography variant="h5" className={classes.title}>
        Thank You!
      </Typography>
      <Typography variant="body1" className={classes.message}>
        Your order has been received and is being processed. You will receive a confirmation email shortly.
      </Typography>
      <Button
        component={Link}
        to="/dashboard"
        variant="contained"
        color="primary"
        className={classes.button}
      >
        Back to Dashboard
      </Button>
    </div>
  );
}

export default ThankYouPage;

This component displays a checkmark icon and a message to confirm that the order has been received and is being processed. It also includes a button that takes the user back to the dashboard. You can customize the styles and messaging as needed.

Python API for Orders and Billing

import stripe

# Set your Stripe API key
stripe.api_key = "sk_test_your_secret_key"

# Create a new customer
customer = stripe.Customer.create(
    name="John Doe",
    email="johndoe@example.com",
    phone="+14155552671",
    address={
        "line1": "123 Main Street",
        "line2": "Apt. 4",
        "city": "San Francisco",
        "state": "CA",
        "postal_code": "94111",
        "country": "US"
    }
)

# Create a new product
product = stripe.Product.create(
    name="Example Product",
    description="This is an example product."
)

# Create a new price for the product
price = stripe.Price.create(
    unit_amount=1999,
    currency="usd",
    product=product["id"]
)

# Create a new order for the customer
order = stripe.Order.create(
    customer=customer["id"],
    currency="usd",
    items=[{
        "type": "sku",
        "parent": price["id"]
    }]
)

# Pay for the order
charge = stripe.Charge.create(
    amount=order["amount"],
    currency=order["currency"],
    customer=order["customer"],
    description="Example Payment"
)

# Get the customer's billing history
invoices = stripe.Invoice.list(customer=customer["id"])

# Print the invoices
for invoice in invoices:
    print(invoice["amount_paid"], invoice["date"])

This script creates a new customer, product, price, and order using the Stripe API, pays for the order with a charge, and then retrieves the customer's billing history. You can modify the script to suit your needs and integrate it into your own application as needed.

Checkout Page (Stripe)

import stripe

stripe.api_key = "YOUR_STRIPE_SECRET_KEY"

def create_checkout_session(price_id, success_url, cancel_url):
    try:
        checkout_session = stripe.checkout.Session.create(
            mode="payment",
            payment_method_types=["card"],
            line_items=[
                {
                    "price": price_id,
                    "quantity": 1,
                }
            ],
            success_url=success_url,
            cancel_url=cancel_url
        )
        return checkout_session
    except stripe.error.StripeError as e:
        print("Error:", e)
        return None

In this script, we import the Stripe API library and set our Stripe secret key. Then, we define a function create_checkout_session that takes in the price_id of the product being purchased, success_url and cancel_url that the customer will be redirected to upon successful or cancelled checkout.

Inside the function, we call stripe.checkout.Session.create to create a new checkout session. We set the mode to "payment" and payment_method_types to "card" to specify that we're accepting card payments. We then specify the line_items of the purchase, which includes the price_id and a quantity of 1.

Finally, we set the success_url and cancel_url parameters to the URLs the customer will be redirected to based on the outcome of their checkout.

This is a basic example of how you can use the Stripe API to create a custom checkout page with Python. Of course, the implementation will depend on your specific use case and requirements.

@elicharlese elicharlese added the bug Something isn't working label Feb 6, 2023
@elicharlese elicharlese self-assigned this Feb 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant