/plushcap/analysis/strapi/strapi-how-to-build-an-ecommerce-application-using-react-mongo-db-strapi-and-socket-io

How to build an E-commerce Store with Nuxt.js and Strapi

What's this blog post about?

In this tutorial, we will be building an E-Commerce store using Strapi as our backend framework. We will also use Nuxt.js for the frontend and Stripe for payment processing. Additionally, we will set up a simple email service to notify subscribers when they sign up. Firstly, you need to install Node.js and npm (Node Package Manager) on your computer if you haven't already done so. You can download them from the official website: https://nodejs.org/en/download/. Next, create a new project folder for our E-Commerce store and navigate into it using the terminal or command prompt. Then run the following commands to initialize a new Node.js project: ```bash npm init -y ``` This will generate a package.json file in your project directory. Now, let's install Strapi and other necessary dependencies by running the following command: ```bash npm install strapi @strapi/generator-admin@latest @strapi/generator-content-type@latest nodemon --save-dev ``` After installation is complete, create a new Strapi project within your current directory using the following command: ```bash npx create-strapi-app ./api --quickstart ``` This will prompt you to enter some details about your application. Fill in the required fields and wait for the installation process to finish. Once it's done, start your Strapi server by running: ```bash npm run develop ``` Now that our backend is set up, let's move on to installing Nuxt.js as our frontend framework. Run the following command in your terminal or command prompt: ```bash npx create-nuxt-app nuxt-strapi-ecommerce ``` Fill in the prompts with appropriate details and wait for the installation process to finish. Once it's done, navigate into your newly created Nuxt.js project folder using the terminal or command prompt: ```bash cd nuxt-strapi-ecommerce ``` Now let's install Stripe by running the following command: ```bash npm install stripe --save ``` To get started with Stripe, go to https://stripe.com/ and register to obtain your API keys before proceeding with this tutorial. Once you've done that, I'll assume you've gotten your API keys and you're ready to proceed. Installing Stripe Package Execute the following code to install Stripe: ```bash yarn add stripe # using yarn npm install stripe # using npm ``` Look for the .env.example file in the root folder of your Strapi application and rename it to .env. Then add the following line of text to it: ```bash STRIPE_KEY=<YOUR_STRIPE_KEY> ``` Replace <YOUR_STRIPE_KEY> with your Stripe credentials. Then proceed as follows to open up the order.js controller: ```bash cd src/api cd order cd controllers code order.js # open in your editor ``` Edit the contents of order.js to look like: ```javascript 'use strict'; const stripe = require('stripe')(process.env.STRIPE_KEY) const MY_DOMAIN = 'http://localhost:3000/cart'; const { createCoreController } = require('@strapi/strapi').factories; module.exports = createCoreController('api::order.order', ({ strapi }) => ({ async create(ctx) { const { cartDetail, cartTotal } = ctx.request.body // build line items array const line_items = cartDetail.map((cartItem) => { const item = {} item.price_data = { currency: 'usd', product_data: { name: cartItem.name, images: [`${cartItem.url}`] }, unit_amount: (cartItem.price * 100).toFixed(0), }, item.quantity = cartItem.quantity return item; }) // create order await strapi.service('api::order.order').create({ data: { item: line_items}}); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items, mode: 'payment', success_url: `${MY_DOMAIN}?success=true`, cancel_url: `${MY_DOMAIN}?canceled=true`, }) return { id: session.id} } })); ``` What we've done here is to redefine the create endpoint. Now when we hit the /order/create endpoint, we generate a line_items array which is stored in our database and also sent to Stripe as product details along with other essential details related to purchases. Finally, we return a JSON object containing an id with the Stripe session ID. That's all for Stripe on the backend. Next, open your Nuxt.js application to add Stripe support on the frontend. Installing @stripe/stripe-js To start using Stripe in our Nuxt.js application, we have to install a package to help us make the process easier. Execute the following code to install @stripe/stripe-js: ```bash yarn add @stripe/stripe-js # using yarn npm install @stripe/stripe-js # using npm ``` Open up your cart.vue file, then add the following lines of code to it: ```javascript export default { data() { return { dataItems: {}, session: {}, stripe: {}, stripePromise: {}, } }, computed: { ...mapGetters(['getCart', 'getCartTotal']), }, mounted() { this.displayMessage() }, methods: { async handleSubmit(e) { e.preventDefault() const response = await this.$http.$post( `http://localhost:1337/api/orders`, { cartDetail: this.getCart, cartTotal: this.getCartTotal.toFixed(2), } ) this.$swal({ title: 'Please wait', text: 'redirecting you to stripe, click ok', icon: 'success', button: 'Ok', }) // stripe logic const stripePromise = loadStripe(process.env.STRIPE_KEY) const session = response const stripe = await stripePromise const result = await stripe.redirectToCheckout({ sessionId: session.id, }) console.log(response) if (result.error) { this.$nuxt.context.error(result.error.message) } }, // using vue-swal to display messages displayMessage() { if (this.$route.query.success) { this.$swal({ title: 'Order placed!', text: 'Thanks for placing your orders', icon: 'success', button: 'Ok', }) } else if (this.$route.query.canceled) { this.$swal({ title: 'Order canceled!', text: "continue to shop around and checkout when you're ready.", icon: 'warning', button: 'Ok', }) } }, formatCartTotal(num) { if (num > 0) { return num.toFixed(2) } else { return num } }, ...mapActions(['deleteCartItem']), }, } ``` Replace <YOUR_STRIPE_KEY> with your Stripe credentials. Now, we should have Stripe working across the whole application. To install Nodemailer, run: ```bash yarn add nodemailer # using yarn npm install nodemailer # using npm ``` Open up your Strapi application and execute the following code to access the subscriber.js controller: ```bash cd src/api cd subscriber cd controllers code subscriber.js ``` Add the following lines of code to your subscriber.js file: ```javascript 'use strict'; const nodemailer = require('nodemailer') module.exports = { async create(ctx) { const { Email } = ctx.request.body const existingSub = await strapi.services.subscriber.find({ Email }) if (!existingSub) { await strapi.services.subscriber.create({ Email }) try { let transporter = nodemailer.createTransport({ service: "gmail", auth: { user: <your_email>, pass: <your_password>, } }) const mailOptions = { from: 'Unique essense stores', to: `${Email}`, subject: 'Welcome', text: `Hey @${Email}, Thanks for subscribing to our NewsLetter` }; await transporter.sendMail(mailOptions) } catch (error) { console.log(error) } } return Email } }; ``` In the code above, using Nodemailer, we've set up an email service that sends out notifications to subscribers. In order for Nodemailer to work with Gmail, you need to turn on less secure app access. You can do so here: https://www.google.com/settings/security/lesssecureapps Well devs, that's all for now. I hope this tutorial has given you an insight into how to build your own E-Commerce store with Strapi. You could even add more features to your store if you like.

Company
Strapi

Date published
Jan. 25, 2022

Author(s)
Alex Godwin

Word count
4807

Language
English

Hacker News points
None found.


By Matt Makai. 2021-2024.