# HOW TO INTEGRATE STRAPI WITH BIGCOMMERCE TO BUILD AN E-COMMERCE STORE ![How To Integrate (1)](https://hackmd.io/_uploads/BJLso-wC1x.jpg) Developing an e-commerce website requires a scalable architecture that manages product information and transactions seamlessly, businesses need an e-commerce website that can adapt to its changing needs and that of the customers. BigCommerce is software that provides comprehensive e-commerce solutions to businesses, handling tasks like setting up online stores, managing inventory and processing payment options. However, for content management and customization, integrating Strapi as a headless content management system(CMS) can improve the development process. This guide explores the technical aspects of integrating Strapi with BigCommerce to build a powerful e-commerce store. ## Prerequisites Before you start, make sure you have installed the first two: * Node.js (v18 or v20) * Node.js package manager such as yarn or npm(v6 and above) * Basic knowledge of web development and APIs ## Steps For Integrating Strapi with BigCommerce ### Set up [Strapi](https://docs.strap.io/dev-docs/quick-start) You need to set up Strapi as the backend for your application. Start by installing Strapi via npm (Node Package Manager) in your terminal , then use the command-line tool to create a fresh Strapi project. Simply run the following command: ``` npx create-strapi-app@latest my-project ``` After the project is created, you will be asked to select QuickStart or Custom (Manuals) as the installation. Quickstart uses SQLite, which is the default database, while Custom (manual settings) allows you to select a database of your choice, such as MariaDB, PostgreSQL or MySQL. After installation, configure basic settings such as authentication and permissions. ![image](https://hackmd.io/_uploads/HJS5cZeWC.png) Once the installation is complete, your browser will automatically open a new tab. Fill the form to create your account and you will become the first admin user of this Strapi application. If the server is not running in your terminal, simply navigate to the project folder in your terminal and run the following command: `npm run develop` or `yarn develop` to launch it. ![image](https://hackmd.io/_uploads/rJA0I3DbR.png) ### Set up [BigCommerce ](https://BigCommerce.com) You can set up a BigCommerce store by signing up on their website, filling in your email, password, and store details, the following their setup process to add products, design your storefront, and configure payments. ![big commerce home page](https://hackmd.io/_uploads/S1TWQmzg0.png) ![IMG-20240417-WA0000](https://hackmd.io/_uploads/HkVZG0hlR.jpg) ### Fetch Data from BigCommerce Navigate to your Strapi project's API directory and create a new JavaScript file (e.g.,fetch_bigcommerce_products.js). Write code to make an HTTP request to the BigCommerce API in the JavaScript file. You can use an HTTP client library such as `axios` or for Python projects, consider using libraries like `requests`. To authenticate your request, you'll need your BigCommerce API credentials: Client ID and Access Token. You can get these credentials by creating an API account within your BigCommerce account settings (under Advanced Settings > API Accounts). Grant the API account read-only permissions for products. ![create api account, big commerece](https://hackmd.io/_uploads/Skq6xQfeA.png) BigCommerce's API uses endpoints to access specific resources, an endpoint is a URL that represents a resource or collection of resources in the server. Example: to fetch ‘product’ data, you will use the `/catalog/product` endpoint. You can find [endpoints](https://developer.bigcommerce.com/docs/api) for your specific use case on BigCommerce document API. ``` const axios = require('axios'); // Define BigCommerce API endpoint const endpoint = 'https://api.bigcommerce.com/stores/{store_id}/v3/catalog/products'; // Define your BigCommerce API credentials const apiKey = 'YOUR_API_KEY'; const apiToken = 'YOUR_API_TOKEN'; // Define request headers with authentication credentials const headers = { 'X-Auth-Token': apiKey, 'Accept': 'application/json' }; // Define a function to fetch product data from BigCommerce async function fetchProductData() { try { // Make an HTTP GET request to the BigCommerce API const response = await axios.get(endpoint, { headers }); // Extract product data from the response const products = response.data; // Process the product data as needed console.log('Product data:', products); } catch (error) { // Handle any errors that occur during the request console.error('Error fetching product data:', error.message); } } // Call the fetchProductData function to initiate the request fetchProductData(); ``` > **Replace:** > * The ‘store id’ with your BigCommerce store id > * ‘YOUR API KEY’ and ‘YOUR API TOKEN’ with your BigCommerce api credentials ### Map Data to Strapi Models Data mapping ensures a seamless flow of data between the two platforms. This involves creating content models in Strapi that corresponds with BigCommerce's product data structure such as name, description, price while also ensuring the data types align such as text and number formats. For example, if BigCommerce provides a product price, Strapi should also have a field for product price to ensure a clear transfer of data between the two platforms. To achieve this,you need to write a custom script in the JavaScript file that iterates through BigCommerce product data and creates corresponding Strapi product entries. ```// Define a function to map Strapi product data to BigCommerce product data function mapToStrapiProduct(strapiProduct) { return { name: strapiProduct.name, description: strapiProduct.description, price: parseFloat(strapiProduct.price), // Convert price to float sku: strapiProduct.sku, // Assuming SKU field is the same category: strapiProduct.category, // Assuming category field is the same // Add more mappings as needed }; } ``` ### Handle Webhooks Webhook handlers are customised functions that listen for and respond to incoming HTTP requests(webhooks) from external systems or services. You need to set up webhook handlers for events like new orders, product price changes, cancelled orders and more. To get started: * Navigate to the settings section of your admin panel in your strapi web application, you will see the ‘webhook’ option, click on it to access webhook settings and create a new webhook endpoint. ![strapi webhooks](https://hackmd.io/_uploads/rJfNPIVeR.png) * Next, write custom webhook handler functions that will be responsible for handling incoming webhook payloads and executing appropriate actions based on the event type. Depending on the event type, you may need to update database records, trigger email notifications, or perform other actions. An example is sending a notification mail when a product is ordered. Here's an example of a function that processes a new order event and sends a notification email: ``` async function handleOrderCreated(eventData) { // Extract order details from event data (replace with your actual field names) const orderId = eventData.data.id; const customerEmail = eventData.data.customer_email; const orderItems = eventData.data.items; // Assuming an "items" array exists // 1. Update data in Strapi (create an order entry) const newOrder = await strapi.services.order.create({ data: { orderId, customerEmail, // Add other relevant order details here (e.g., total amount) }, }); // 2. Trigger actions - Send email notification const emailContent = buildOrderConfirmationEmail(customerEmail, orderId, orderItems); await sendEmail(customerEmail, "Your Order Confirmation", emailContent); console.log("Order created successfully and confirmation email sent:", orderId); } // Helper functions for building email content and sending emails (implementation not shown) function buildOrderConfirmationEmail(customerEmail, orderId, orderItems) { // ... Logic to build email content with order details } async function sendEmail(recipientEmail, subject, content) { // ... Logic to send email using an email service provider } ``` * Navigate to your BigCommerce admin panel and configure it to send notifications of relevant events to the webhook endpoints you’ve created in Strapi, see how [here](https://developer.bigcommerce.com/docs/integrations/webhooks/overview) * Finally, test the webhook handlers to ensure they’re working correctly , you can do this by sending a test webhook payload from BigCommerce to Strapi to ensure Strapi receives them and processes them as expected. Also, you can write a custom script to periodically sync data with BigCommerce. ### Managing content with Strapi You can use Strapi to manage non-product content such as blog posts, testimonial, landing pages, and product descriptions. Use the content-type builder to create content models for the content you want. Define the specific fields and data points you need to capture for each content type. ![image](https://hackmd.io/_uploads/rkRDwhD-C.png) This can include text fields, images for a testimonial. This content can be accessed via Strapi's API. ### Customise Frontend Choose between frameworks like React, Vue.js, Angular or Next.js to customise the frontend. Your choice of framework depends on your project requirements and desired functionalities. Use BigCommerce API to fetch product data and other relevant information to fill the frontend. Also,use Strapi APIs like REST API and GraphQL API to fetch contents like blog posts, landing pages and testimonials from your database and display them on your website. BigCommerce has a library called [Stencil](https://developer.bigcommerce.com/stencil-docs) for theme development, you can use Stencil's components and functionalities as the foundation for your custom frontend application. ![big commerce frontend](https://hackmd.io/_uploads/SkfZlmMlA.png) ### Test and Deploy Test the integration process to ensure it is working accurately, start with implementing unit test to ensure all components are working and then evaluate the integration process. After that, you can deploy your e-commerce store, monitor and also maintain the e-commerce store. ## CONCLUSION Integrating Strapi's content management and BigCommerce's product management features allows you to create a powerful e-commerce store with a flexible architecture. You can create a seamless shopping experience for your customers using these steps and choosing the approach that best suits your skills and project.