Skip to content

Instantly share code, notes, and snippets.

@NerdFaisal404
Last active October 22, 2024 17:53
Show Gist options
  • Select an option

  • Save NerdFaisal404/b583f68e0c9b75a93295157bcf517169 to your computer and use it in GitHub Desktop.

Select an option

Save NerdFaisal404/b583f68e0c9b75a93295157bcf517169 to your computer and use it in GitHub Desktop.

To build the same functionality using Laravel (a PHP framework) for the backend and React for the frontend, the steps and structure change slightly. Below is the breakdown of how to create a Laravel application that syncs data from Printify, displays it, and exports that data to an Etsy store.

Prerequisites

  • Knowledge Required: PHP, Laravel, JavaScript, React, REST APIs, and basic database management.
  • Tools Required: Composer (for Laravel), Node.js, Laravel, React, Axios (for API calls), MySQL or other relational databases, Printify API keys, Etsy API keys.

Project Structure

my-laravel-app/
│
├── app/                   # Laravel application logic
│   ├── Http/
│   │   ├── Controllers/   # Controllers for business logic
│   │   ├── Models/        # Eloquent models for database tables
│
├── routes/
│   ├── api.php            # API routes for Printify and Etsy integration
│
├── database/              # Migrations and seeders for the database
│
├── resources/             # Frontend resources
│   ├── js/                # React app can live here
│
├── .env                   # Environment variables (API keys, secrets)
├── composer.json          # PHP dependencies
├── package.json           # JS dependencies
└── README.md              # Project documentation

Step 1: Set Up Laravel

  1. Install Laravel:

    composer create-project --prefer-dist laravel/laravel my-laravel-app
    cd my-laravel-app
  2. Set Up Environment Variables: Edit the .env file with your database configuration:

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=my_database
    DB_USERNAME=root
    DB_PASSWORD=your_password
    
    PRINTIFY_API_KEY=your_printify_api_key
    ETSY_API_KEY=your_etsy_api_key

Step 2: Create Models and Migrations

  1. Create the Product Model:

    php artisan make:model Product -m

    This will create a Product model and a migration file.

  2. Define the Product Migration: Edit the migration file in database/migrations:

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->string('printify_id');
            $table->decimal('price', 8, 2);
            $table->string('image_url');
            $table->timestamps();
        });
    }
  3. Run the Migration:

    php artisan migrate

Step 3: Create Controllers for Printify and Etsy

  1. Create the Printify Controller:

    php artisan make:controller PrintifyController
  2. Create the Etsy Controller:

    php artisan make:controller EtsyController

Step 4: Define Routes

  1. Add Routes in routes/api.php:
    use App\Http\Controllers\PrintifyController;
    use App\Http\Controllers\EtsyController;
    
    Route::get('/printify/sync', [PrintifyController::class, 'sync']);
    Route::post('/etsy/export', [EtsyController::class, 'export']);

Step 5: Implement Printify Sync in PrintifyController

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\Support\Facades\Http;

class PrintifyController extends Controller
{
    public function sync(Request $request)
    {
        $printifyApiKey = env('PRINTIFY_API_KEY');
        $response = Http::withHeaders([
            'Authorization' => "Bearer {$printifyApiKey}"
        ])->get('https://api.printify.com/v1/shops/your-shop-id/products.json');

        if ($response->successful()) {
            $products = $response->json()['data'];

            foreach ($products as $productData) {
                Product::updateOrCreate(
                    ['printify_id' => $productData['id']],
                    [
                        'title' => $productData['title'],
                        'description' => $productData['description'],
                        'price' => $productData['variants'][0]['price'],
                        'image_url' => $productData['images'][0]['src']
                    ]
                );
            }

            return response()->json(['message' => 'Data synced successfully']);
        }

        return response()->json(['message' => 'Failed to sync data'], 500);
    }
}

Step 6: Implement Etsy Export in EtsyController

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\Support\Facades\Http;

class EtsyController extends Controller
{
    public function export(Request $request)
    {
        $etsyApiKey = env('ETSY_API_KEY');
        $products = Product::all();

        $exportedProducts = [];

        foreach ($products as $product) {
            $response = Http::withHeaders([
                'Authorization' => "Bearer {$etsyApiKey}"
            ])->post('https://openapi.etsy.com/v3/application/listings', [
                'title' => $product->title,
                'description' => $product->description,
                'price' => $product->price,
                'images' => [$product->image_url],
            ]);

            if ($response->successful()) {
                $exportedProducts[] = $response->json();
            }
        }

        return response()->json(['message' => 'Products exported to Etsy', 'exportedProducts' => $exportedProducts]);
    }
}

Step 7: Set Up React for the Frontend

  1. Install React in Laravel:

    npm install && npm install react react-dom
  2. Configure React in Laravel: Create a new App.js file in resources/js and set up the component:

    import React, { useState } from 'react';
    import axios from 'axios';
    
    function App() {
        const [products, setProducts] = useState([]);
    
        const syncPrintify = async () => {
            try {
                const response = await axios.get('/api/printify/sync');
                alert(response.data.message);
            } catch (error) {
                console.error('Error syncing data:', error);
            }
        };
    
        const exportToEtsy = async () => {
            try {
                const response = await axios.post('/api/etsy/export');
                alert(response.data.message);
            } catch (error) {
                console.error('Error exporting data:', error);
            }
        };
    
        return (
            <div>
                <h1>Printify to Etsy Sync</h1>
                <button onClick={syncPrintify}>Sync Printify Data</button>
                <button onClick={exportToEtsy}>Export to Etsy</button>
            </div>
        );
    }
    
    export default App;
  3. Compile Frontend:

    npm run dev

Step 8: Serve the Application

Start the Laravel server:

php artisan serve

Visit the application in the browser at http://localhost:8000, where you can use the sync and export features.

Notes:

  1. Replace "your-shop-id" in the Printify API endpoint with your actual shop ID.
  2. Set up environment variables in .env for API keys.
  3. Implement validation and error handling for production.
  4. Customize the frontend as needed for better user experience.

This setup will provide a Laravel-based backend for handling Printify and Etsy integrations, with a React-based frontend for user interactions.

Web Application with Node.js and React for Printify and Etsy Sync

Overview

This application allows users to sync data from Printify, display the data in their store, and export that data to an Etsy store. The application uses Node.js for the backend and React for the frontend.

Prerequisites

  • Basic understanding of JavaScript, React, Node.js, REST APIs, and authentication.
  • Tools required:
    • Node.js
    • Express
    • React
    • Axios (for API calls)
    • MongoDB (as the database)
    • Printify API keys
    • Etsy API keys

Project Structure

my-app/
│
├── backend/               # Backend code (Node.js)
│   ├── app.js             # Main entry point
│   ├── routes/            # API routes
│   │   ├── printify.js    # Printify related routes
│   │   └── etsy.js        # Etsy related routes
│   ├── controllers/       # Controllers for logic
│   ├── services/          # Services for API calls
│   └── models/            # Database models
│
├── frontend/              # Frontend code (React)
│   ├── public/
│   └── src/
│       ├── components/    # React components
│       ├── pages/         # Pages of the application
│       ├── App.js         # Main component
│       └── index.js       # Entry point
│
├── .env                   # Environment variables (API keys, secrets)
├── package.json           # Project dependencies
└── README.md              # Project documentation

Backend: Node.js with Express

1. Setting up the Backend

Create a simple Express server:

// backend/app.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const printifyRoutes = require('./routes/printify');
const etsyRoutes = require('./routes/etsy');

const app = express();
app.use(cors());
app.use(express.json());

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('MongoDB connection error:', err));

app.use('/api/printify', printifyRoutes);
app.use('/api/etsy', etsyRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

2. Define Models

Create a model for storing user data and product data:

// backend/models/Product.js
const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    title: String,
    description: String,
    printifyId: String,
    price: Number,
    imageUrl: String,
    userId: mongoose.Schema.Types.ObjectId,
});

module.exports = mongoose.model('Product', productSchema);

3. Printify Integration

Add a route to sync data from Printify:

// backend/routes/printify.js
const express = require('express');
const axios = require('axios');
const Product = require('../models/Product');
const router = express.Router();

// Sync data from Printify
router.get('/sync', async (req, res) => {
    const { userId, printifyApiKey } = req.query;

    try {
        const response = await axios.get('https://api.printify.com/v1/shops/your-shop-id/products.json', {
            headers: {
                'Authorization': `Bearer ${printifyApiKey}`,
            },
        });

        const products = response.data.data;

        // Save products to the database
        const savedProducts = await Promise.all(products.map(product => {
            return Product.create({
                title: product.title,
                description: product.description,
                printifyId: product.id,
                price: product.variants[0].price,
                imageUrl: product.images[0].src,
                userId,
            });
        }));

        res.json({ message: 'Data synced successfully', products: savedProducts });
    } catch (error) {
        console.error('Error syncing data from Printify:', error);
        res.status(500).json({ message: 'Failed to sync data' });
    }
});

module.exports = router;

4. Etsy Integration

Add a route to export products to Etsy:

// backend/routes/etsy.js
const express = require('express');
const axios = require('axios');
const Product = require('../models/Product');
const router = express.Router();

// Export products to Etsy
router.post('/export', async (req, res) => {
    const { userId, etsyApiKey } = req.body;

    try {
        const products = await Product.find({ userId });

        const exportedProducts = await Promise.all(products.map(async (product) => {
            const response = await axios.post('https://openapi.etsy.com/v3/application/listings', {
                title: product.title,
                description: product.description,
                price: product.price,
                images: [product.imageUrl],
            }, {
                headers: {
                    'Authorization': `Bearer ${etsyApiKey}`,
                },
            });
            return response.data;
        }));

        res.json({ message: 'Products exported to Etsy', exportedProducts });
    } catch (error) {
        console.error('Error exporting data to Etsy:', error);
        res.status(500).json({ message: 'Failed to export data' });
    }
});

module.exports = router;

Frontend: React

1. Setting up React

Create a new React app using:

npx create-react-app frontend

2. Main Component (App.js)

Setup the main component to handle API calls:

// frontend/src/App.js
import React, { useState } from 'react';
import axios from 'axios';

function App() {
    const [products, setProducts] = useState([]);
    const [printifyApiKey, setPrintifyApiKey] = useState('');
    const [etsyApiKey, setEtsyApiKey] = useState('');

    const syncPrintify = async () => {
        try {
            const response = await axios.get('/api/printify/sync', {
                params: { printifyApiKey },
            });
            setProducts(response.data.products);
        } catch (error) {
            console.error('Error syncing with Printify:', error);
        }
    };

    const exportToEtsy = async () => {
        try {
            await axios.post('/api/etsy/export', {
                etsyApiKey,
            });
            alert('Products exported to Etsy successfully!');
        } catch (error) {
            console.error('Error exporting to Etsy:', error);
        }
    };

    return (
        <div className="App">
            <h1>Printify to Etsy Sync</h1>
            <input
                type="text"
                placeholder="Printify API Key"
                value={printifyApiKey}
                onChange={(e) => setPrintifyApiKey(e.target.value)}
            />
            <button onClick={syncPrintify}>Sync Printify Data</button>
            <input
                type="text"
                placeholder="Etsy API Key"
                value={etsyApiKey}
                onChange={(e) => setEtsyApiKey(e.target.value)}
            />
            <button onClick={exportToEtsy}>Export to Etsy</button>

            <h2>Products</h2>
            <ul>
                {products.map((product) => (
                    <li key={product.id}>
                        <h3>{product.title}</h3>
                        <p>{product.description}</p>
                        <img src={product.imageUrl} alt={product.title} width="100" />
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default App;

3. Starting the Application

  1. Backend:

    cd backend
    npm install express mongoose axios cors
    node app.js
  2. Frontend:

    cd frontend
    npm start

Notes

  1. Replace "your-shop-id" in the Printify API endpoint with your actual shop ID.
  2. Set up environment variables in .env for API keys and MongoDB URI.
  3. Implement proper error handling and validation for production use.
  4. Adjust the data mapping between Printify and Etsy as per your needs.

This setup will create a basic web application that allows users to sync products from Printify, view them in a simple interface, and export those products to Etsy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment