rbi-learning / Today-I-Learned

1 stars 0 forks source link

08/17 Day 16 Lecture Notes #149

Open Limlight86 opened 4 years ago

Limlight86 commented 4 years ago

08/17 Day 16 Lecture Notes

4242 4242 4242 4242, any date and cvc and name for testing purposes on stripe test.

Publishable key goes on the front end and secret key goes on the backend

Boiler plate express set up

const express = require("express")

const app = express()

app.use(express.json())

const PORT = process.env.PORT || 3000

app.listen(PORT, () =>
  console.log(`Server is up and running at port ${PORT} 🚀`)
);

Stripe products and prices come in separately, they most be queried individually and combined in your server before sending it to the front end.

https://stripe.com/docs/api

yarn add stripe

Processing the different datapoint from our stripe api to put together a more comprehensive response to our front end, so the data is easier to work with.

app.get('/products', async (_request, response) => {
  const products = await stripe.products.list({limit: 100});
  const prices = await stripe.prices.list({limit: 100});
  prices.data.forEach(price => {
    const theAssociatedProduct = products.data.find(product => product.id === price.product);
    theAssociatedProduct.price = price;
  });
  const cleanedUpProducts = products.data.map(product => ({
    name: product.name,
    description: product.description,
    image: product.images[0],
    category: product.metadata.category,
    currency: product.price.currency,
    price_cents: product.price.unit_amount,
  }));
  response.json(cleanedUpProducts);
});

https://www.npmjs.com/package/dotenv

yarn add dotenv

Add your secret keys in the .env file so you can call on them in other files

STRIPE_SECRET_KEY=<your secret key>

Call in your .env file by requiring dotenv

require('dotenv').config()
const stripe = require('stripe'(process.env.STRIPE_SECRET_KEY);