Skip to content

WesleySmits/agent-skills / .agent/skills/marketplace-integration-helper

scaffolding-marketplace-integrations

Verified

Generates boilerplate for e-commerce API integrations. Use when the user asks about WooCommerce, Shopify, Bol.com, or Etsy APIs, webhooks, product sync, or order handling.

FileKindSize
SKILL.mdskill md17.4 KB
examples/bol-etsy-clients.mdmarkdown11.7 KB

examples/bol-etsy-clients.md

View on GitHub
# Bol.com and Etsy API Clients

## Bol.com Client

```typescript
// lib/marketplace/bol-client.ts
import { BaseMarketplaceClient } from "./base-client";

interface BolProduct {
  ean: string;
  condition: "NEW" | "AS_NEW" | "GOOD" | "REASONABLE" | "MODERATE";
  price: number;
  stock: { amount: number; managedByRetailer: boolean };
  fulfilment: { method: "FBR" | "FBB" };
}

interface BolOrder {
  orderId: string;
  orderItems: BolOrderItem[];
  shipmentDetails: {
    firstName: string;
    surname: string;
    streetName: string;
    houseNumber: string;
    zipCode: string;
    city: string;
    countryCode: string;
  };
}

interface BolOrderItem {
  orderItemId: string;
  ean: string;
  quantity: number;
  unitPrice: number;
}

export class BolClient extends BaseMarketplaceClient {
  private clientId: string;
  private clientSecret: string;
  private accessToken: string | null = null;
  private tokenExpiry: Date | null = null;

  constructor(clientId: string, clientSecret: string) {
    super("https://api.bol.com/retailer", { maxRequests: 25, windowMs: 10000 });
    this.clientId = clientId;
    this.clientSecret = clientSecret;
  }

  protected getAuthHeaders(): Record<string, string> {
    if (!this.accessToken) {
      throw new Error("Not authenticated. Call authenticate() first.");
    }
    return { Authorization: `Bearer ${this.accessToken}` };
  }

  async authenticate(): Promise<void> {
    if (this.accessToken && this.tokenExpiry && this.tokenExpiry > new Date()) {
      return;
    }

    const response = await fetch(
      "https://login.bol.com/token?grant_type=client_credentials",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`,
        },
      },
    );

    if (!response.ok) {
      throw new Error(`Bol.com authentication failed: ${response.status}`);
    }

    const data = await response.json();
    this.accessToken = data.access_token;
    this.tokenExpiry = new Date(Date.now() + (data.expires_in - 60) * 1000);
  }

  // Products/Offers
  async getOffer(offerId: string): Promise<BolProduct> {
    await this.authenticate();
    return this.request("GET", `/offers/${offerId}`);
  }

  async createOffer(
    offer: Partial<BolProduct>,
  ): Promise<{ processStatusId: string }> {
    await this.authenticate();
    return this.request("POST", "/offers", offer);
  }

  async updateOfferPrice(
    offerId: string,
    price: number,
  ): Promise<{ processStatusId: string }> {
    await this.authenticate();
    return this.request("PUT", `/offers/${offerId}/price`, {
      pricing: {
        bundlePrices: [{ quantity: 1, unitPrice: price }],
      },
    });
  }

  async updateOfferStock(
    offerId: string,
    amount: number,
  ): Promise<{ processStatusId: string }> {
    await this.authenticate();
    return this.request("PUT", `/offers/${offerId}/stock`, {
      amount,
      managedByRetailer: true,
    });
  }

  // Orders
  async getOrders(
    status: "OPEN" | "ALL" = "OPEN",
  ): Promise<{ orders: BolOrder[] }> {
    await this.authenticate();
    return this.request("GET", `/orders?status=${status}`);
  }

  async getOrder(orderId: string): Promise<BolOrder> {
    await this.authenticate();
    return this.request("GET", `/orders/${orderId}`);
  }

  async shipOrderItem(
    orderItemId: string,
    shipmentReference: string,
    trackAndTrace?: string,
  ): Promise<{ processStatusId: string }> {
    await this.authenticate();
    return this.request("PUT", "/shipments", {
      orderItems: [{ orderItemId }],
      shipmentReference,
      transport: trackAndTrace ? { trackAndTrace } : undefined,
    });
  }

  // Process status (async operations)
  async getProcessStatus(processStatusId: string): Promise<{
    status: "PENDING" | "SUCCESS" | "FAILURE";
    errorMessage?: string;
  }> {
    await this.authenticate();
    return this.request("GET", `/process-status/${processStatusId}`);
  }

  async waitForProcessStatus(
    processStatusId: string,
    maxWaitMs = 30000,
  ): Promise<boolean> {
    const startTime = Date.now();

    while (Date.now() - startTime < maxWaitMs) {
      const status = await this.getProcessStatus(processStatusId);

      if (status.status === "SUCCESS") return true;
      if (status.status === "FAILURE") {
        throw new Error(`Process failed: ${status.errorMessage}`);
      }

      await new Promise((resolve) => setTimeout(resolve, 2000));
    }

    throw new Error("Process status check timed out");
  }
}
```

## Etsy Client

```typescript
// lib/marketplace/etsy-client.ts
import { BaseMarketplaceClient } from "./base-client";

interface EtsyListing {
  listing_id: number;
  title: string;
  description: string;
  price: { amount: number; divisor: number; currency_code: string };
  quantity: number;
  state: "active" | "inactive" | "draft" | "expired";
  tags: string[];
  sku: string[];
}

interface EtsyReceipt {
  receipt_id: number;
  status: "paid" | "completed" | "open" | "canceled";
  buyer_email: string;
  transactions: EtsyTransaction[];
  grandtotal: { amount: number; divisor: number; currency_code: string };
}

interface EtsyTransaction {
  transaction_id: number;
  listing_id: number;
  quantity: number;
  price: { amount: number; divisor: number; currency_code: string };
}

export class EtsyClient extends BaseMarketplaceClient {
  private apiKey: string;
  private accessToken: string;
  private shopId: string;

  constructor(apiKey: string, accessToken: string, shopId: string) {
    super("https://openapi.etsy.com/v3/application", {
      maxRequests: 10,
      windowMs: 1000,
    });
    this.apiKey = apiKey;
    this.accessToken = accessToken;
    this.shopId = shopId;
  }

  protected getAuthHeaders(): Record<string, string> {
    return {
      "x-api-key": this.apiKey,
      Authorization: `Bearer ${this.accessToken}`,
    };
  }

  // Listings
  async getListings(
    state: "active" | "inactive" | "draft" = "active",
  ): Promise<{
    count: number;
    results: EtsyListing[];
  }> {
    return this.request(
      "GET",
      `/shops/${this.shopId}/listings?state=${state}&limit=100`,
    );
  }

  async getListing(listingId: number): Promise<EtsyListing> {
    return this.request("GET", `/listings/${listingId}`);
  }

  async createListing(listing: Partial<EtsyListing>): Promise<EtsyListing> {
    return this.request("POST", `/shops/${this.shopId}/listings`, listing);
  }

  async updateListing(
    listingId: number,
    listing: Partial<EtsyListing>,
  ): Promise<EtsyListing> {
    return this.request(
      "PATCH",
      `/shops/${this.shopId}/listings/${listingId}`,
      listing,
    );
  }

  async updateListingInventory(
    listingId: number,
    quantity: number,
    price: number,
  ): Promise<void> {
    await this.request("PUT", `/listings/${listingId}/inventory`, {
      products: [
        {
          offerings: [
            {
              quantity,
              price: { amount: Math.round(price * 100), divisor: 100 },
              is_enabled: true,
            },
          ],
        },
      ],
    });
  }

  // Receipts (Orders)
  async getReceipts(status?: "paid" | "completed" | "open"): Promise<{
    count: number;
    results: EtsyReceipt[];
  }> {
    const query = status
      ? `?was_paid=true&was_shipped=${status === "completed"}`
      : "";
    return this.request("GET", `/shops/${this.shopId}/receipts${query}`);
  }

  async getReceipt(receiptId: number): Promise<EtsyReceipt> {
    return this.request("GET", `/shops/${this.shopId}/receipts/${receiptId}`);
  }

  async createShipment(
    receiptId: number,
    trackingCode: string,
    carrierName: string,
  ): Promise<void> {
    await this.request(
      "POST",
      `/shops/${this.shopId}/receipts/${receiptId}/tracking`,
      {
        tracking_code: trackingCode,
        carrier_name: carrierName,
      },
    );
  }
}
```

## Etsy OAuth 2.0 PKCE Flow

```typescript
// lib/marketplace/etsy-oauth.ts
import crypto from "crypto";

export function generateCodeVerifier(): string {
  return crypto.randomBytes(32).toString("base64url");
}

export function generateCodeChallenge(verifier: string): string {
  return crypto.createHash("sha256").update(verifier).digest("base64url");
}

export function getEtsyAuthUrl(
  clientId: string,
  redirectUri: string,
  codeChallenge: string,
  state: string,
): string {
  const params = new URLSearchParams({
    response_type: "code",
    client_id: clientId,
    redirect_uri: redirectUri,
    scope: "listings_r listings_w transactions_r transactions_w",
    code_challenge: codeChallenge,
    code_challenge_method: "S256",
    state,
  });

  return `https://www.etsy.com/oauth/connect?${params}`;
}

export async function exchangeCodeForToken(
  clientId: string,
  redirectUri: string,
  code: string,
  codeVerifier: string,
): Promise<{
  access_token: string;
  refresh_token: string;
  expires_in: number;
}> {
  const response = await fetch("https://api.etsy.com/v3/public/oauth/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      client_id: clientId,
      redirect_uri: redirectUri,
      code,
      code_verifier: codeVerifier,
    }),
  });

  if (!response.ok) {
    throw new Error(`Token exchange failed: ${await response.text()}`);
  }

  return response.json();
}

export async function refreshAccessToken(
  clientId: string,
  refreshToken: string,
): Promise<{
  access_token: string;
  refresh_token: string;
  expires_in: number;
}> {
  const response = await fetch("https://api.etsy.com/v3/public/oauth/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "refresh_token",
      client_id: clientId,
      refresh_token: refreshToken,
    }),
  });

  if (!response.ok) {
    throw new Error(`Token refresh failed: ${await response.text()}`);
  }

  return response.json();
}
```

## Webhook Verification

### Bol.com Push Notifications

Bol.com uses a different model—you poll for events or use push notifications:

```typescript
// lib/marketplace/bol-webhooks.ts
import { BolClient } from "./bol-client";

export async function processBolSubscriptions(
  client: BolClient,
): Promise<void> {
  // Bol.com requires setting up subscriptions via API
  // Then they send push notifications to your endpoint

  // Register for push notifications
  await client.request("POST", "/subscriptions", {
    resources: ["PROCESS_STATUS", "OFFER_STOCK_CHANGED"],
    url: "https://your-domain.com/api/webhooks/bol",
  });
}

// Bol.com signs webhooks with a signature header
export function verifyBolWebhook(
  body: string,
  signature: string,
  publicKey: string,
): boolean {
  const verify = crypto.createVerify("SHA256");
  verify.update(body);
  return verify.verify(publicKey, signature, "base64");
}
```

### Etsy Webhooks

Etsy doesn't provide webhooks—use polling:

```typescript
// lib/marketplace/etsy-polling.ts
import { EtsyClient } from "./etsy-client";
import { db } from "@/lib/db";

export async function pollEtsyOrders(client: EtsyClient): Promise<void> {
  const lastCheck = await db.syncState.findUnique({
    where: { platform: "etsy" },
  });

  const receipts = await client.getReceipts("paid");

  for (const receipt of receipts.results) {
    // Check if already processed
    const existing = await db.order.findUnique({
      where: { externalId: `etsy_${receipt.receipt_id}` },
    });

    if (!existing) {
      await processNewEtsyOrder(receipt);
    }
  }

  // Update last check time
  await db.syncState.upsert({
    where: { platform: "etsy" },
    update: { lastChecked: new Date() },
    create: { platform: "etsy", lastChecked: new Date() },
  });
}
```
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 323kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 323kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 323kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 323kUpdated Claude CodeCodexVerifiedInstall