Custom WooCommerce REST Integration
A production-grade, ground-up REST client built in C# on .NET 10 — dual-auth strategy, complete product sync, order processing, and webhook lifecycle management.
Overview
The WooCommerce integration is a fully custom REST client library built in C# on .NET 10. Rather than relying on third-party WooCommerce SDKs, this library communicates directly with the WooCommerce REST API (v3) using a purpose-built HTTP transport layer, giving complete control over authentication, error handling, and domain-specific business logic for print-on-demand fulfillment.
The library powers every aspect of the WooCommerce integration — from credential-based connection setup to product synchronization, order processing, webhook management, and real-time store monitoring.
Core Architecture
REST Transport Layer
A custom WooCommerceHttpClient serves as the abstract base for all WooCommerce API communication:
- Centralized auth-health tracking — every request is monitored for 401/403 responses, automatically flagging channels that need reauthorization
- Dual authentication strategy — attempts Basic Auth first, then transparently falls back to query-parameter credentials for hosts that reject the
Authorizationheader IHttpClientFactoryintegration — proper HTTP client lifecycle management via .NET's built-in factory pattern- Consistent error propagation — all API methods return strongly-typed
Result<T>objects with structured error messages
Typed API Clients
Two dedicated API clients inherit from the shared transport:
WooCommerceApi— orders, webhooks, and general product/variation queriesWooProductApi— product CRUD, variation CRUD, paginated listings, and search
Both clients use System.Text.Json with a shared WooAppConfig.JsonOptions configuration tuned for WooCommerce's JSON conventions — nullable decimals, case-insensitive property names, and string-to-number coercion.
Authentication & Connection Management
Manual Credential Flow
WooCommerce connections are established via consumer key/secret pairs entered directly by the merchant:
- Domain normalization — store URLs are cleaned and standardized before persistence
- Upsert logic — reconnecting an existing store domain updates credentials in place rather than creating duplicates
- Immediate webhook setup — after persisting credentials, the system automatically provisions required webhooks
OAuth Authorization (Alternative)
- Authorization URL generation — constructs the
wc-auth/v1/authorizeURL with app name, scopes, callback, and return parameters - Callback processing — the
/api/woocommerce/authorizeendpoint receives the consumer key/secret and persists them via the sameAddConnectionAsyncpath - CSRF-safe state — cryptographically random state tokens generated via
RandomNumberGenerator
Auth Health Tracking
- Automatic 401/403 detection — the HTTP transport tracks failed auth attempts and sets a
NeedsReauthflag on the sales channel - Webhook-level auth handling — incoming webhooks that carry
woocommerce_rest_cannot_viewerror codes trigger automatic reauthorization marking - Recovery on success — successful API calls clear the auth failure state, restoring the channel to healthy status
Product Management
Product Creation
The WooProductManager orchestrates the full product lifecycle between the local catalog and WooCommerce:
- Product creation via the WooCommerce Products API with variable product type, attributes, images, and tags
- Full variant mapping — Color/Size attribute matrix with per-variant SKU, price, weight, and image assignment
- Automatic linked product records — a local
LinkedProduct→LinkedVariantrelational model maintains the bidirectional mapping between internal merchant products and WooCommerce products
Product Updates
- Incremental variant sync — detects new, existing, and removed variants; adds missing ones and updates existing ones in place
- Remote variant cleanup — variants deleted locally are removed from WooCommerce and their linked records are cleaned up
- Attribute preservation — existing WooCommerce attribute IDs are reused when updating Color/Size option values
- SKU-based primary matching with Color/Size fallback for variant linking during import
Product Linking
- Duplicate prevention — validates that a remote product isn't already linked to a different merchant product
- SKU-first matching — links variants by WooCommerce SKU, falling back to Color + Size name matching
- Temporary ID cleanup — utility method removes legacy migration IDs after successful linking
Order Processing
Webhook-Driven Order Creation
Orders flow into PrintAura automatically via WooCommerce webhooks:
- Idempotency — duplicate orders are detected by external ID before processing
- Line item resolution — each WooCommerce line item is matched to a linked variant via
RemoteVariantId - Price calculation — per-line subtotals, weights, and taxes are computed through
CalculatePrintAuraOrderLineAsync - Shipping calculation — pluggable
IShippingCalculatorwith automatic fallback to the legacyOrderHelper.CalculateShippingmethod - Tax exemption — respects store-level tax exemption settings
- Shipping discounts — applies percentage-based shipping discounts when configured on the merchant store
- Address normalization — shipping addresses are converted to ISO-2 country codes via
ConversionUtility
Tracking Number Posting
- Order status update — sets the WooCommerce order status to
completed - Metadata injection — adds or updates a
tracking_numbermetadata entry on the order - Minimal payload — sends only the fields being changed to avoid overwriting unrelated order data
Webhook System
Automatic Setup & Cleanup
The SetupWebhooksAsync method performs intelligent webhook lifecycle management:
- Legacy cleanup — identifies and removes webhooks pointing to deprecated PrintAura domains
- Per-topic deduplication — ensures exactly one webhook per topic with the correct delivery URL for the current environment
- Missing webhook creation — provisions any webhooks that don't yet exist
- Environment-aware URLs — delivery URLs are constructed from the current environment's base URL plus the channel ID
Required Event Topics
order.created | Triggers order creation and fulfillment processing |
product.updated | Syncs variant removals and SKU changes from WooCommerce back to linked products |
product.deleted | Removes linked product records when products are deleted in WooCommerce |
Webhook Endpoint Processing
- Product updates — reconciles linked variants against the remote product's current variation list, removing stale links and syncing SKU changes
- Product deletions — cascades removal of linked product and variant records while preserving the merchant product
- Auth failure detection — webhooks carrying authorization error payloads automatically mark the channel for reauthorization
Admin Dashboard Components (Blazor)
Connection Management
- Connect WooCommerce — manual credential entry form with domain, consumer key, and consumer secret fields, including input validation and autocomplete suppression
- WooCommerce Connection — full channel management: webhook status display, permissions listing, reauthorization flow, order fetching, and channel deletion with confirmation modal
Monitoring Tools
- Store Monitor — paginated display of all WooCommerce products with linked variant counts, color-coded discrepancy indicators, and direct edit links
- Migration Status — admin-only dashboard showing products with temporary WooCommerce IDs, unlinked products, and partial linkage counts for migration tracking
Technical Highlights
| Target Framework | .NET 10 / C# 14 |
| API Version | WooCommerce REST API v3 |
| HTTP Transport | Custom abstract WooCommerceHttpClient with IHttpClientFactory |
| Authentication | Basic Auth with automatic query-parameter fallback |
| JSON Processing | System.Text.Json with custom converters and WooCommerce-tuned options |
| Database | Entity Framework Core with IDbContextFactory for scoped contexts |
| Resilience | Dual-auth fallback, auth-health tracking, graceful degradation on API failures |
| Observability | Structured logging with ILogger<T>, activity log service for audit trails |
| Security | Credential isolation per channel, CSRF-safe OAuth state, reauthorization detection |
| UI Framework | Blazor Server with interactive components and real-time state management |
This library processes real merchant orders daily alongside its Shopify and Etsy counterparts — no third-party SDK wrappers, complete control over every layer.