· 5 years ago · Oct 28, 2020, 01:32 AM
1const stripe = require('stripe')('sk_test_51Hemg7ETi3TpMq6bUmiw1HoxERPmReLOT3YLthf11MEVh4xCmnsmxtFHZRlWpimoSnwHjmUOKNkOFsbr9lEEIybe00SQF71RtF');
2//This is a test secret key for a dummy stripe account, don't worry I'm not sharing anything sensitive
3const express = require('express');
4const app = express();
5app.use(express.static('.'));
6const YOUR_DOMAIN = 'http://localhost:4242';
7
8app.post('/create-session', async(req, res) => {
9 //Body of the POST request
10 const cartContents = [{
11 product_id: 'prod_IHb8dX3ESy2kwk',
12 quantity: '2',
13 price_id: 'price_1Hh1wcETi3TpMq6bSjVCf3EI'
14 }, {
15 product_id: 'prod_IFIIyTO0fHCfGx',
16 quantity: '2',
17 price_id: 'price_1HeniJETi3TpMq6bPDWb3lrp'
18 }
19 ];
20
21 //Array to push parsed data onto for line_items object in stripe session
22 const lineItems = [];
23 try {
24 for (let item of cartContents) {
25 //Retrieve price object from stripe API:
26 const price = await stripe.prices.retrieve(item.price_id);
27 console.log(price.unit_amount);
28 //log the unit_amount value from price object
29 //retrieve product object from stripe API
30 const product = await stripe.products.retrieve(item.product_id);
31 console.log(product.name);
32 // retrieve "name" and "images" from returned product object and assign to variable
33 const productName = product.name;
34 const productImage = product.images;
35 //retrieve "unit_amount" from returned price object and assign to variable
36 const productPrice = price.unit_amount;
37 //retrieve item quantity from cartContents object and assign to variable
38 const productQuantity = item.quantity;
39 //Add variables to item and push to lineItems array
40 lineItems.push({
41 price_data: {
42 currency: 'usd',
43 product_data: {
44 name: productName,
45 images: [productImage],
46 },
47 unit_amount: productPrice,
48 },
49 quantity: productQuantity,
50 });
51 }
52 const session = await stripe.checkout.sessions.create({
53 payment_method_types: ['card'],
54 line_items: lineItems,
55 mode: 'payment',
56 success_url: `http://localhost:5001/success.html`,
57 cancel_url: `http://localhost:5001/cancel.html`,
58 });
59 res.json({id: session.id});
60 } catch(e) {
61 // handle error here
62 }
63});