This guide explains how to convert your ebay-store from static products to a fully API-driven affiliate system using the eBay Browse API.
Your repository now includes all the necessary infrastructure for eBay API integration with proper affiliate tracking using Campaign ID: 5338903178.
✅ OAuth Token Management - Automatic token generation and refresh ✅ eBay Browse API Integration - Search and fetch products ✅ Affiliate URL Creation - Automatic tracking parameter injection ✅ Custom ID Support - Granular tracking by category/source ✅ Error Handling - Fallback to search links if API fails ✅ Caching - 1-hour revalidation to reduce API calls
- Visit developer.ebay.com
- Sign up or log in to your account
- Navigate to My Keys
- Create a Production keyset (not Sandbox)
- Save your credentials:
- Client ID (App ID)
- Client Secret (Cert ID)
You already have Campaign ID 5338903178 which is configured throughout the codebase.
- Verify your account at partnernetwork.ebay.com
- Ensure Campaign ID
5338903178is active - Monitor your dashboard for traffic and earnings
Create a .env.local file in your project root:
# eBay API Credentials (Production)
EBAY_CLIENT_ID=YourAppId-YourApp-PRD-xxxxxxxxx-xxxxxxxx
EBAY_CLIENT_SECRET=PRD-xxxxxxxxxxxxxxxxx-xxxxxxxx
# Optional: Marketplace (defaults to EBAY_US)
EBAY_MARKETPLACE_ID=EBAY_US
# Optional: OAuth Scope (defaults to standard scope)
EBAY_OAUTH_SCOPE=https://api.ebay.com/oauth/api_scopeIf you prefer to manage tokens yourself:
EBAY_OAUTH_TOKEN=v^1.1#i^1#r^0#p^3#f^0#t^H4sIAAA...Replace hardcoded product arrays with API calls:
import { searchEbayProducts, mapEbayItemToProduct } from '@/lib/ebay-api';
import { allProducts } from '@/lib/products'; // Fallback
export default async function ProductsPage() {
let products = [];
try {
// Fetch live products from eBay API
const electronicsData = await searchEbayProducts('electronics trending', 20);
products = electronicsData.itemSummaries
?.map((item, index) => mapEbayItemToProduct(item, index, 'Electronics'))
.filter(Boolean) || [];
} catch (error) {
console.error('eBay API error, using static products:', error);
// Fallback to static products if API fails
products = allProducts.filter(p => p.category === 'Electronics');
}
return <ProductGrid products={products} />;
}const categoryKeywords = {
'Electronics': 'smartphone laptop tablet electronics',
'Gaming': 'playstation xbox nintendo gaming console',
'Sneakers': 'nike jordan adidas sneakers shoes',
'Smart Home': 'echo alexa smart home devices',
'Beauty': 'beauty cosmetics skincare makeup',
'Fitness': 'fitness equipment exercise gym',
// ... add more categories
};
async function fetchCategoryProducts(category: string, limit = 20) {
const keyword = categoryKeywords[category] || category;
const response = await searchEbayProducts(keyword, limit);
return response.itemSummaries
?.map((item, index) => mapEbayItemToProduct(item, index, category))
.filter(Boolean) || [];
}All API-fetched products automatically include:
- mkcid:
1(eBay Partner Network) - mkrid:
711-53200-19255-0(Routing ID) - siteid:
0(eBay US) - campid:
5338903178(Your Campaign ID) - customid:
api-{category}(e.g.,api-electronics,api-gaming)
The implementation uses custom IDs to differentiate:
- API Products:
api-electronics,api-gaming, etc. - Static Products:
static-electronics,static-gaming, etc. - Search Results:
fallback-{category}(when API URL is unavailable)
This allows you to analyze in your EPN dashboard:
- Which categories perform best
- API vs static product conversion rates
- User behavior patterns
Add an API status endpoint to monitor your integration:
// app/api/ebay-status/route.ts
import { getEbayIntegrationStatus } from '@/lib/ebay-api';
import { NextResponse } from 'next/server';
export async function GET() {
const status = getEbayIntegrationStatus();
return NextResponse.json(status);
}Access at: https://your-site.vercel.app/api/ebay-status
Expected response:
{
"mode": "client_credentials",
"marketplaceId": "EBAY_US",
"missing": []
}npm run devCheck console for:
- ✅ Successful API token generation
- ✅ Product fetch without errors
- ✅ Affiliate links with correct parameters
Click a product link and check the URL includes:
https://www.ebay.com/itm/123456789?mkcid=1&mkrid=711-53200-19255-0&siteid=0&campid=5338903178&customid=api-electronics
Install Link Redirect Trace browser extension:
- Click a product on your site
- Verify redirect chain includes
campid=5338903178 - Confirm final destination is eBay product page
After going live:
- Log in to partnernetwork.ebay.com
- Navigate to Reports > Campaign Reports
- Filter by Campaign ID
5338903178 - Check for incoming clicks and conversions
- Review Custom ID breakdown for category performance
- Push your changes to GitHub
- Go to vercel.com dashboard
- Navigate to your project settings
- Add Environment Variables:
EBAY_CLIENT_IDEBAY_CLIENT_SECRETEBAY_MARKETPLACE_ID(optional)
- Redeploy your application
.env.local to GitHub
- Your
.gitignoreshould include.env*.local - Only add variables through Vercel dashboard
- Rotate credentials if accidentally exposed
- Production accounts: 5,000 calls/day (standard)
- Premium accounts: Higher limits available
-
Caching (Already Implemented):
next: { revalidate: 3600 } // 1-hour cache
-
Strategic Product Selection:
- Fetch trending/popular items only
- Use static products for lesser categories
- Rotate API categories daily
-
Fallback System:
- Keep static products as backup
- Gracefully handle API failures
- Monitor error rates
For optimal performance and reliability:
// Featured products: Live API (high traffic)
const featuredProducts = await searchEbayProducts('trending electronics', 8);
// Category pages: Mix API + static
const apiProducts = await searchEbayProducts(category, 12);
const staticProducts = allProducts.filter(p => p.category === category).slice(0, 8);
const mixedProducts = [...apiProducts, ...staticProducts];
// Less popular categories: Static only
const staticOnly = allProducts.filter(p => p.category === 'Collectibles');import { track } from '@vercel/analytics';
try {
const data = await searchEbayProducts(keyword, limit);
track('ebay_api_success', { category, count: data.total });
} catch (error) {
track('ebay_api_error', { category, error: error.message });
}Monitor weekly:
- Click-through Rate: Clicks / Impressions
- Conversion Rate: Sales / Clicks
- EPC (Earnings Per Click): Revenue / Clicks
- Category Performance: Via Custom ID breakdown
const status = getEbayIntegrationStatus();
console.log('Integration Status:', status);
if (status.mode === 'disabled') {
console.log('Missing credentials:', status.missing);
}- Verify credentials are correct
- Check if Production (not Sandbox) keys are used
- Ensure no extra spaces in environment variables
- Check API permissions in developer account
- Verify marketplace ID matches your account region
- Wait 24-48 hours for data to appear
- Verify
campid=5338903178in actual click URLs - Check that Campaign is active in EPN
- eBay API Docs: developer.ebay.com/api-docs
- EPN Help: partnerhelp.ebay.com
- API Status: developer.ebay.com/status
- Community: eBay Developer Forums
- ✅ Get eBay API credentials
- ✅ Configure environment variables
- ✅ Update pages to fetch from API
- ✅ Test affiliate links locally
- ✅ Deploy to Vercel with production variables
- ✅ Monitor EPN dashboard for clicks
- ✅ Optimize based on performance data
Questions? Open an issue in this repository or check the eBay Developer documentation.