如何用PHP调用eBay API将自有商品上传至eBay店铺?
Got it, let’s walk through a practical, actionable demo to get this working. I’ll use Node.js for the backend since it’s super common for web apps, but the core logic translates to other languages too.
1. 前置准备
Before writing any code, you’ll need to get these sorted first:
- Sign up for an eBay Developer account and create a Production (or Sandbox for testing) application
- Grab these credentials from your eBay app dashboard:
- Client ID
- Client Secret
- Refresh Token (you can generate this via eBay’s OAuth tool in the developer portal)
- Make sure your database stores these essential product fields: title, description, price, stock quantity, image URL, and eBay Category ID (look this up for your product type using eBay’s category finder tool in the dev portal)
2. 项目初始化
Start by setting up a new project and installing dependencies:
mkdir ebay-upload-demo cd ebay-upload-demo npm init -y npm install axios dotenv express
Create a .env file to store your sensitive credentials (never hardcode these!):
EBAY_CLIENT_ID=your_client_id_here EBAY_CLIENT_SECRET=your_client_secret_here EBAY_REFRESH_TOKEN=your_refresh_token_here EBAY_API_BASE=https://api.ebay.com
3. 核心逻辑实现
Create ebay-upload.js with the key functions to fetch tokens, pull products from your DB, and upload to eBay:
require('dotenv').config(); const axios = require('axios'); // 1. Fetch eBay API access token (OAuth 2.0 flow) async function getAccessToken() { const authString = Buffer.from(`${process.env.EBAY_CLIENT_ID}:${process.env.EBAY_CLIENT_SECRET}`).toString('base64'); try { const response = await axios.post(`${process.env.EBAY_API_BASE}/identity/v1/oauth2/token`, null, { params: { grant_type: 'refresh_token', refresh_token: process.env.EBAY_REFRESH_TOKEN, scope: 'https://api.ebay.com/oauth/api_scope/sell.inventory https://api.ebay.com/oauth/api_scope/sell.account' }, headers: { 'Authorization': `Basic ${authString}`, 'Content-Type': 'application/x-www-form-urlencoded' } }); return response.data.access_token; } catch (error) { console.error('Failed to get access token:', error.response?.data || error.message); throw error; } } // 2. Simulate fetching products from your database // Replace this with your actual DB query logic (e.g., using MySQL, MongoDB, etc.) function getProductsFromDB() { return [ { id: 'prod_001', title: 'Handmade Ceramic Coffee Mug', description: 'Unique hand-painted ceramic mug, dishwasher and microwave safe. Perfect for coffee lovers!', price: 24.99, quantity: 30, imageUrl: 'https://your-web-app.com/images/mug-001.jpg', categoryId: '1400', // eBay Home & Garden category ID - replace with your product's category condition: 'NEW' } ]; } // 3. Upload a single product to eBay using Inventory API async function uploadSingleProduct(product, accessToken) { try { // Step 1: Create an Inventory Item (basic product details) await axios.post( `${process.env.EBAY_API_BASE}/sell/inventory/v1/inventory_item`, { sku: product.id, // Use your internal product ID as SKU (must be unique) title: product.title, description: product.description, condition: product.condition, product: { categoryId: product.categoryId, aspects: { Material: ['Ceramic'], Capacity: ['12 oz'] } }, images: [{ imageUrl: product.imageUrl }] }, { headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json', 'X-EBAY-C-MARKETPLACE-ID': 'EBAY_US' // Replace with your target marketplace (e.g., EBAY_GB) } } ); // Step 2: Create an Inventory Offer (sets price, stock, and selling policies) await axios.post( `${process.env.EBAY_API_BASE}/sell/inventory/v1/inventory_offer`, { sku: product.id, marketplaceId: 'EBAY_US', price: { value: product.price, currency: 'USD' }, quantity: product.quantity, fulfillmentPolicyId: 'DEFAULT_FULFILLMENT_POLICY', // Use your store's default policy ID paymentPolicyId: 'DEFAULT_PAYMENT_POLICY', returnPolicyId: 'DEFAULT_RETURN_POLICY' }, { headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' } } ); console.log(`Successfully uploaded: ${product.title}`); } catch (error) { console.error(`Failed to upload ${product.title}:`, error.response?.data || error.message); throw error; } } // 4. Main function to trigger when admin clicks the "Upload to eBay" button async function handleUploadTrigger() { try { console.log('Starting eBay upload process...'); const accessToken = await getAccessToken(); const products = getProductsFromDB(); for (const product of products) { await uploadSingleProduct(product, accessToken); } console.log('All products uploaded successfully!'); } catch (error) { console.error('Upload process failed:', error); } } module.exports = { handleUploadTrigger };
4. Integrate with Your Web App
Add an API endpoint for your frontend button to call (using Express here):
Create server.js:
const express = require('express'); const app = express(); const { handleUploadTrigger } = require('./ebay-upload'); app.use(express.json()); // Admin-only upload endpoint - add your own admin auth (e.g., JWT) here! app.post('/admin/upload-to-ebay', async (req, res) => { try { await handleUploadTrigger(); res.status(200).json({ message: 'Products uploaded to eBay successfully!' }); } catch (error) { res.status(500).json({ error: 'Upload failed - check server logs for details' }); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Then add a simple frontend button to trigger the upload (vanilla JS example):
// Add this to your admin page's JS document.getElementById('ebay-upload-btn').addEventListener('click', async () => { try { const response = await fetch('/admin/upload-to-ebay', { method: 'POST', headers: { 'Content-Type': 'application/json' // Add your admin auth header here (e.g., Authorization: Bearer YOUR_ADMIN_JWT) } }); const data = await response.json(); alert(data.message); } catch (error) { alert('Upload failed - please try again later'); } });
Key Notes to Remember
- Category IDs: Always use valid eBay category IDs for your target marketplace - wrong IDs will cause upload failures
- Scopes: Make sure your refresh token includes the
sell.inventoryscope (and others if needed) - Testing: Use eBay’s Sandbox environment first to avoid live listing mistakes
- Error Handling: Add retry logic for failed uploads and detailed logging for debugging
- Policy Compliance: Ensure your product listings follow eBay’s seller policies to avoid account issues
内容的提问来源于stack exchange,提问作者Ris Peterson

