AnointedAutomation.Shopify
3.1.0
dotnet add package AnointedAutomation.Shopify --version 3.1.0
NuGet\Install-Package AnointedAutomation.Shopify -Version 3.1.0
<PackageReference Include="AnointedAutomation.Shopify" Version="3.1.0" />
<PackageVersion Include="AnointedAutomation.Shopify" Version="3.1.0" />
<PackageReference Include="AnointedAutomation.Shopify" />
paket add AnointedAutomation.Shopify --version 3.1.0
#r "nuget: AnointedAutomation.Shopify, 3.1.0"
#:package AnointedAutomation.Shopify@3.1.0
#addin nuget:?package=AnointedAutomation.Shopify&version=3.1.0
#tool nuget:?package=AnointedAutomation.Shopify&version=3.1.0
AnointedAutomation.Shopify
Jesus is King ✝️
Plain POCO models for the Shopify Admin REST API, with Newtonsoft.Json attributes. Customers, addresses, marketing consent, orders, line items, refunds, transactions, products, variants, images, fulfillments, fulfillment orders, inventory items and levels, locations, webhooks, price rules, gift cards, payouts, disputes and the rest of the REST resource set.
Models plus two small helpers: ShopifyGid (format and parse gid://shopify/<Resource>/<id>) and ShopifyMoney (read a GraphQL MoneyBag from a System.Text.Json JsonElement). Since 2.0.0 ShopifyMoney.Read throws a FormatException naming the missing field and TryRead/TryReadAmount return false; a missing or unparseable amount is never 0 (see CHANGELOG.md). Deserialize the JSON you already have:
using AnointedAutomation.Shopify;
using Newtonsoft.Json;
Customer customer = JsonConvert.DeserializeObject<Customer>(json);
long? id = customer.Id;
- Target framework:
net10.0 - Dependencies:
Newtonsoft.Json,AnointedAutomation.Serialization,AnointedAutomation.Logging(every log goes throughLogMessage; subscribe toLogMessage.LogAddedto route them) - Namespace:
AnointedAutomation.Shopify(converters inAnointedAutomation.Shopify.Converters)
GraphQL client (AnointedAutomation.Shopify.GraphQL)
A transport-neutral Admin GraphQL client over your own HttpClient. Tenancy and token storage stay in your code: implement IShopifyStoreContext (shop domain, API version, access-token provider).
using AnointedAutomation.Shopify.GraphQL;
ShopifyGraphQlClient client = new ShopifyGraphQlClient(httpClient, storeContext);
ShopifyGraphQlResponse shop = await client.QueryAsync(new ShopifyGraphQlRequest("query Shop { shop { name } }", null), ct);
await foreach (JsonElement order in ShopifyPager.EnumerateNodesAsync(client,
"query Orders($first: Int!, $after: String) { orders(first: $first, after: $after) { nodes { id } pageInfo { hasNextPage endCursor } } }",
null, data => data.GetProperty("orders"), 250, ct))
{
}
SendAsyncreturns the raw envelope;QueryAsyncthrows on top-level errors without data;MutateAsyncthrows onuserErrorsand returns the payload.- Pacing:
ShopifyCostBucket(one per shop,ShopifyCostBucketRegistry) waits onextensions.cost.throttleStatusbefore each send. - Retries (
ShopifyRetryPolicy): 429 honorsRetry-After; HTTP 200THROTTLEDwaits what the bucket needs, on its own round budget; 5xx and network failures back off exponentially. - A mutation is resent after a 5xx or network failure ONLY when it carries an
@idempotentkey (ShopifyIdempotency). Otherwise the client throwsShopifyGraphQlExceptionwithOutcome = Indeterminate: it may have applied, so read the store before acting again. IShopifyRequestSchedulerwraps each send so you can plug in your own queue (default: run now). Cancellation is rethrown; every failure is logged with the operation name and status, never the token.
Final answer without throwing, resend veto, delegated logging, priority (3.1.0, additive)
Existing code keeps working unchanged. Four opt-in additions for a consumer that owns its own queue, retries and central log:
SendFinalAsyncruns the same pacing and retries asSendAsyncbut never throws for an answer: theShopifyGraphQlFinalResultcarries the lastStatusCodeand rawBody(4xx and 5xx included), the parsedResponsewhen the body is JSON, and anOutcome:Answered(2xx, not THROTTLED),Failed(any other final answer, THROTTLED included, seeThrottled),Indeterminate(a mutation that may have applied and was not resent) orNotSent(see below).ShopifyGraphQlClientOptions.ResendGuard(IShopifyResendGuard) is asked before every resend the retry policy decided on, with the reason (RateLimited,Throttled,UnknownOutcome). Return false to refuse: a refused resend of a mutation afterUnknownOutcomeendsIndeterminate, any other endsFailed. The guard can only restrict, so a mutation without an@idempotentkey is still never resent. Use it to never resend a capture or void even when it carries a key.ShopifyGraphQlClientOptions.LogSink(IShopifyGraphQlLogSink): when set, the client writes none of its ownLogMessagerows (retry Warning, give-up Error, indeterminate Critical, network and parse rows) and hands each one to the sink as aShopifyGraphQlLogEvent(kind, level, operation, status, message, body snippet, exception), so the consumer keeps one central, gated log line. Unset keeps today's logging.ShopifyGraphQlRequest.Priority(ShopifyBucketPriority):Interactive(a person waits) is paced as if the outstandingBackgroundreservations were not there;Backgroundis the default and today's behavior.ShopifyGraphQlRequest.MaxPreSendWaitis a wait budget: when the bucket needs longer, nothing is reserved or sent and the call endsNotSentwithRetryNotBefore(aShopifyGraphQlExceptionwithOutcome = NotSentfromSendAsync), so the caller requeues itself instead of sleeping. The same is available directly on the bucket asReserve(cost, now, priority, maxWait),TryReserve(...)andRelease(cost, priority).
Bulk operations (AnointedAutomation.Shopify.Bulk)
ShopifyBulkOperationRunner bulk = new ShopifyBulkOperationRunner(client, plainHttpClient);
ShopifyBulkOperation op = await bulk.RunQueryAsync("{ products { edges { node { id title } } } }", ct);
await foreach (JsonElement line in bulk.ReadResultsAsync(op, ct)) { } // streamed, never loaded whole
ShopifyBulkOperation m = await bulk.RunMutationAsync(mutationText, jsonlStream, "updates.jsonl", ct);
ShopifyStagedUploadsis the onestagedUploadsCreatebuilder; the JSONL is uploaded once and itskeybecomesstagedUploadPath.- The start mutations are unkeyed, so an unknown outcome throws
Indeterminateand is never resent. Only a definite "already in progress" refusal is retried, after a backoff wait. - Polling reads
node(id:)of YOUR operation with backoff (2 s doubling to 30 s, 25 h budget). The terminal state is returned: checkIsCompleted; FAILED, CANCELED and EXPIRED carryErrorCode, andResultUrlfalls back topartialDataUrl.
Webhooks (AnointedAutomation.Shopify.Webhooks)
ShopifyWebhookHmac.Verify(rawBodyBytes, request.Headers["X-Shopify-Hmac-Sha256"], secret): base64 HMAC-SHA256 of the RAW body, constant-time compare. A missing or malformed header isfalse; a missing secret throws.ShopifyWebhookRegistrar.SyncAsync(wanted, managedUriPrefix, ct): lists every subscription, keeps matches, creates missing ones and deletes stale ones ONLY under your prefix.Diffis the pure plan. UsesWebhookSubscription.uri(2025-04 and newer).
Typed operations and models (AnointedAutomation.Shopify.Operations, .GraphQL.Models)
await client.ExecuteAsync(ShopifyCatalogOperations.TagsAdd(productGid, new[] { "sale" }), ct);
ShopifyProduct p = await client.ExecuteAsync(ShopifyCatalogOperations.ProductById(productGid), ct); // null when not found
await foreach (ShopifyOrder o in ShopifyCatalogOperations.EnumerateOrdersAsync(client, "status:open", 250, ct)) { }
- Builders:
TagsAdd,TagsRemove,MetafieldsSet,ProductUpdate,ProductSet,ProductVariantsBulkUpdate,CustomerUpdate,InventoryActivate,InventorySetQuantities,ProductById,OrderById,CustomerById, plus paged product/order/customer enumeration. Each pins its query text (tests assert it byte for byte). ShopifyPublishingOperations(2.1.0):Publish/Unpublish(Publication gids only, validated),ProductPublications,CollectionPublications,SellingPlanGroupCreate/SellingPlanGroupUpdate/SellingPlanGroupDelete,OrderFulfillmentOrders. Run them withclient.ExecuteAsynclike the catalog builders.ShopifyStagedUploadsstays the onestagedUploadsCreatebuilder.- Money paths (
orderCancel,refundCreate,orderCapture,orderEdit*,draftOrderCreate) are deliberately not included. - Schema target 2026-10. On older versions:
productUpdate(product:)needs 2024-10+;@idempotentis accepted from 2026-01 and required for the inventory mutations from 2026-04;changeFromQuantityreplacesignoreCompareQuantityfrom 2026-04. - Models (
ShopifyProduct,ShopifyProductVariant,ShopifyMetafield,ShopifyCustomer,ShopifyOrder,ShopifyUserError,ShopifyConnection<T>withShopifyPageInfo,ShopifyMoneyV2/ShopifyMoneyBag; cost staysShopifyQueryCost) read withShopifyGraphQlJson.Options. Money isdecimal;NumericIdusesShopifyGid. - Hand-written, not schema-generated (decision): a generated Admin schema is thousands of types and changes every quarter, while consumers only need the fields these operations select. Small hand-written models stay stable, reviewable and dependency-free. Revisit if the operation set grows past what is reasonable to keep by hand.
Nullable reference types (3.0.0)
Compiled with nullable reference types enabled (nullable was disabled before). Consumers with nullable enabled can see new warnings, and TreatWarningsAsErrors makes them errors.
- Entities (
Order,Customer,Product,Address, every REST object): each scalar and reference property that Shopify may omit or null is now nullable (string?, a nested entityT?). Collections the constructor fills stay non-null. Read nested objects with a null check or?.. ShopifyGraphQlClientOptionsandShopifyBulkOperationRunnerOptions: every collaborator property is now arequirednon-nullable member, so an object initializer that omits one no longer compiles (before, the constructor threwArgumentExceptionat run time). UseStandard(...).ShopifyGraphQlRequest(string query, IReadOnlyDictionary<string, object?>? variables): values may be null (a GraphQL variable can be null); build the dictionary asDictionary<string, object?>.ShopifyPager.EnumerateNodesAsyncandShopifyCatalogOperations.Enumerate*Asynctake the same nullable dictionary orstring? search.ShopifyGraphQlResponse.ErrorSummaryisstring?andCostisShopifyQueryCost?;ShopifyGraphQlException.Reasonisstring?and its constructor takesstring? reason, Exception? inner.ShopifyBulkOperation:Type,ErrorCode,Url,PartialDataUrl,ResultUrlarestring?;ShopifyBulkOperationRunner.GetAsyncandGetCurrentAsyncreturnShopifyBulkOperation?.ShopifyStagedTarget.ResourceUrlisstring?.ShopifyPageInfo.EndCursorandShopifyRetryDecision.Reasonarestring?;ShopifyPager.WalkAsynctakesFunc<string?, Task<ShopifyPageInfo>>.ShopifyWebhookOutcome.SubscriptionIdandErrorarestring?.ShopifyWebhookRegistrar.ListAsyncthrowsInvalidOperationExceptionfor a subscription without id, topic or uri (before it passed null on).ShopifyGidparsers acceptstring?(TryParsehas[NotNullWhen(true)] out string? resource);ShopifyMoney.TryReadhas[NotNullWhen(true)] out string? currency.ShopifyCatalogOperations.ExecuteAsync<T>returnsTask<T?>; a null node inEnumerate*Asyncnow throwsInvalidOperationException.ShopifyMetafieldsSetInput.Type,ShopifyInventorySetQuantitiesInput.ReferenceDocumentUriandSellingPlanGroupCreate(resources)are nullable.ShopifyCostBucket.EstimateCost,ShopifyIdempotency.UsesDirective,ShopifyGraphQlErrors.OperationNameandShopifyWebhookHmac.Verify(..., string? hmacHeader, ...)accept null.FalseToNullConverteroverrides matchJsonConverter. XML doc fixes only otherwise.
License
MIT. The models are derived from ShopifySharp (Copyright (c) 2015 Joshua Harms, MIT). See THIRD-PARTY-NOTICES.md.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- AnointedAutomation.Logging (>= 3.0.1)
- AnointedAutomation.Serialization (>= 2.0.1)
- Newtonsoft.Json (>= 13.0.4)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on AnointedAutomation.Shopify:
| Package | Downloads |
|---|---|
|
AnointedAutomation.Objects
Plain POCO models for user accounts, billing and payments, single sign-on identities (Google, Microsoft, Apple, Facebook, Discord, GitHub, LinkedIn, Twitch, Yahoo, Amazon, Reddit, Shopify), and standard API response envelopes. |
GitHub repositories
This package is not used by any popular GitHub repositories.