Skip to content

About

Go client for the Shopify API

Resources

Stars

394 stars

Watchers

19 watching

Forks

 
 

Latest commit

 

History

278 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-shopify

The new home of Conversio's Shopify Go library.

Note: The library does not have implementations of all Shopify resources, but it is being used in production and should be stable for usage. PRs for new resources and endpoints are welcome, or you can simply implement some yourself as-you-go. See the section "Using your own models" for more info.

Build Status codecov Join the chat at https://gitter.im/bold-commerce/go-shopify

Response fields without a documented fixed shape use json.RawMessage (or a slice of it). This preserves their JSON, including large IDs, for callers to decode into their own types.

Supported Go Versions

The Go versions tested by CI are listed in the test workflow. Older versions are not covered by CI.

Install v4

$ go get github.com/bold-commerce/go-shopify/v4

Use v4

import "github.com/bold-commerce/go-shopify/v4"

This gives you access to the goshopify package.

Install v3

$ go get github.com/bold-commerce/go-shopify/v3

Use v3

import "github.com/bold-commerce/go-shopify/v3"

This gives you access to the goshopify package.

Install v2

$ go get github.com/bold-commerce/go-shopify

Use v2

import "github.com/bold-commerce/go-shopify"

This gives you access to the goshopify package.

Oauth

If you don't have an access token yet, you can obtain one with the OAuth flow. The handler fragments below show the library calls. Generate a random, single-use state value for each authorization attempt and store it in the user's session. In the callback, verify that the returned state matches the stored value before exchanging the code. The fixed state below is only a placeholder.

// Create an app somewhere.
var app = goshopify.App{
    ApiKey: "abcd",
    ApiSecret: "efgh",
    RedirectUrl: "https://example.com/shopify/callback",
    Scope: "read_products,read_orders",
}

// Create an oauth-authorize url for the app and redirect to it.
// In some request handler, you probably want something like this:
func MyHandler(w http.ResponseWriter, r *http.Request) {
    shopName := r.URL.Query().Get("shop")
    state := "nonce"
    authUrl, err := app.AuthorizeUrl(shopName, state)
    if err != nil {
        http.Error(w, "Invalid shop", http.StatusBadRequest)
        return
    }
    http.Redirect(w, r, authUrl, http.StatusFound)
}

// Fetch a permanent access token in the callback
func MyCallbackHandler(w http.ResponseWriter, r *http.Request) {
    // Validate the single-use state against the user's session here.
    // Check that the callback signature is valid
    if ok, _ := app.VerifyAuthorizationURL(r.URL); !ok {
        http.Error(w, "Invalid Signature", http.StatusUnauthorized)
        return
    }

    query := r.URL.Query()
    shopName := query.Get("shop")
    code := query.Get("code")
    ctx := r.Context()
    token, err := app.GetAccessToken(ctx, shopName, code)
    if err != nil {
        http.Error(w, "Token exchange failed", http.StatusBadGateway)
        return
    }

    // Do something with the token, like store it in a DB.
}
Expiring offline access tokens

Shopify is replacing permanent offline access tokens with expiring offline access tokens for public apps. An expiring token comes with a refresh token:

// In the callback, fetch an expiring token instead of a permanent one.
token, err := app.GetExpiringAccessToken(ctx, shopName, code)
// Store token.AccessToken, token.RefreshToken and both lifetimes
// (token.ExpiresIn and token.RefreshTokenExpiresIn, in seconds).

// Before the access token expires, refresh it. The refresh token is rotated,
// so store the returned token again.
token, err = app.RefreshAccessToken(ctx, shopName, token.RefreshToken)

// Exchange a permanent token that was stored earlier for an expiring one.
// Shopify invalidates the permanent token.
token, err = app.MigrateToExpiringAccessToken(ctx, shopName, permanentToken)

Api calls with a token

With a valid access token, you can make API calls like this. These snippets use the v4 package. Import context and use a request context when available, or context.Background() for a standalone call.

// Create an app somewhere.
app := goshopify.App{
    ApiKey: "abcd",
    ApiSecret: "efgh",
    RedirectUrl: "https://example.com/shopify/callback",
    Scope: "read_products",
}

// Create a new API client
client, err := goshopify.NewClient(app, "shopname", "token")

// Fetch the number of products.
numProducts, err := client.Product.Count(context.Background(), nil)

Private App Auth

Private Shopify apps use basic authentication and do not require going through the OAuth flow. Here is an example:

// Create an app somewhere.
app := goshopify.App{
	ApiKey: "apikey",
	Password: "apipassword",
}

// Create a new API client (notice the token parameter is the empty string)
client, err := goshopify.NewClient(app, "shopname", "")

// Fetch the number of products.
numProducts, err := client.Product.Count(context.Background(), nil)

Client Options

When creating a client there are configuration options you can pass to NewClient. Simply use the last variadic param and pass in the built in options or create your own and manipulate the client. See options.go for more details.

WithVersion

Read more details on the Shopify API Versioning to understand the format and release schedules. You can use WithVersion to specify a specific version of the API. If you do not use this option you will be defaulted to the oldest stable API.

client, err := goshopify.NewClient(app, "shopname", "token", goshopify.WithVersion("2026-10"))

WithRetry

Shopify Rate Limits their API and if this happens to you they will send a back off (usually 2s) to tell you to retry your request. To support this functionality seamlessly within the client a WithRetry option exists where you can pass an int of how many times you wish to retry per-request before returning an error. WithRetry additionally supports retrying HTTP503 errors.

client, err := goshopify.NewClient(app, "shopname", "", goshopify.WithRetry(3))

Read recorded rate-limit information with client.RateLimits(). This method replaces the client.RateLimits field and returns an independent snapshot that is safe to read while other requests are in progress. Changes to the snapshot do not change the client.

Query options

Most API functions take an options interface{} as parameter. You can use one from the library or create your own. For example, to fetch the number of products created after January 1, 2016, you can do:

// Create standard CountOptions
date := time.Date(2016, time.January, 1, 0, 0, 0, 0, time.UTC)
options := goshopify.CountOptions{CreatedAtMin: date}

// Use the options when calling the API.
numProducts, err := client.Product.Count(context.Background(), options)

The options are parsed with Google's go-querystring library so you can use custom options like this:

// Create custom options for the orders.
// Notice the `url:"status"` tag
options := struct {
    Status string `url:"status"`
}{"any"}

// Fetch the order count for orders with status="any"
orderCount, err := client.Order.Count(context.Background(), options)

Pagination

List returns one page. Use ListWithPagination to retrieve a page and its next/previous options, or ListAll to collect every page matching the initial filters. Existing List signatures are unchanged, including gift cards, price rules, and discount codes; their new pagination methods accept options.

cards, page, err := client.GiftCard.ListWithPagination(ctx, goshopify.ListOptions{Limit: 100})
if err != nil {
    return err
}
// Process cards here.
if page.NextPageOptions != nil {
    cards, page, err = client.GiftCard.ListWithPagination(ctx, page.NextPageOptions)
    // Handle err and process the next page.
}

// Or collect all matching pages in memory.
cards, err = client.GiftCard.ListAll(ctx, goshopify.ListOptions{Limit: 100})

Pass the returned options unchanged to the same method with the same parent IDs. For a previous page, use PreviousPageOptions. A nil page option means there is no page in that direction. Do not merge the original filters into a cursor request. The returned options preserve the cursor, limit, and any field selection supplied in Shopify's link.

The following existing operations now expose both page-by-page and all-page methods:

Service / operation Page method All-page method
AbandonedCheckout, Article, Blog, Collect, CustomCollection, CustomerAddress, DiscountCode, DraftOrder, GiftCard, InventoryItem, InventoryLevel, Location, Metafield, Page, PriceRule, Redirect, ScriptTag, SmartCollection, Variant, Webhook ListWithPagination ListAll
Customer search SearchWithPagination SearchAll
Customer orders ListOrdersWithPagination ListOrdersAll
Collection products ListProductsWithPagination ListProductsAll
Order fulfillments ListFulfillmentsWithPagination ListFulfillmentsAll
Article tags ListTagsWithPagination / ListBlogTagsWithPagination ListTagsAll / ListBlogTagsAll
ProductListing IDs GetProductIdsWithPagination GetProductIdsAll
Existing metafield owners: Customer, CustomCollection, DraftOrder, Location, Order, Page, Product, Shop, SmartCollection, Variant ListMetafieldsWithPagination ListMetafieldsAll

Product, Customer, Order, ProductListing, Payouts, PaymentsTransactions, and OrderRisk retain their existing ListWithPagination and ListAll methods. Parent IDs are still required for nested resources. For example:

variants, err := client.Variant.ListAll(ctx, productID, goshopify.ListOptions{Limit: 100})
metafields, err := client.Product.ListMetafieldsAll(ctx, productID, nil)

The all-page methods return items from completed pages if a later request fails; always check the error. Use a context with a timeout or cancellation for long traversals. These methods collect results in memory; use page-by-page calls for large datasets. Required initial filters still apply: inventory-item lists need item IDs, and inventory-level lists need item IDs or location IDs.

The affected service interfaces have new methods. Custom implementations and mocks must implement them. No new Go version or dependency is required.

This covers existing operations documented with cursor pagination or a limit parameter, following Shopify's pagination guide. It does not add missing resource endpoints. List methods without a documented pagination contract, such as themes, assets, product images, fulfillment orders, and billing charges, are unchanged.

Fulfillment API migration

Fulfillment method signatures and service interfaces are unchanged. Writes use Shopify's current REST endpoints. See Shopify's migration guide and the Fulfillment reference.

Use FulfillmentOrder.List(ctx, orderID, nil) to get the fulfillment orders that your app can access. Select the fulfillment orders and quantities to ship, then pass their IDs to Fulfillment.Create or Order.CreateFulfillment:

fulfillment, err := client.Order.CreateFulfillment(ctx, orderID, goshopify.Fulfillment{
    LineItemsByFulfillmentOrder: []goshopify.LineItemByFulfillmentOrder{{
        FulfillmentOrderId: fulfillmentOrderID,
        FulfillmentOrderLineItems: []goshopify.LineItemByFulfillmentOrderItemQuantity{{
            Id:       fulfillmentOrderLineItemID,
            Quantity: 1,
        }},
    }},
    TrackingInfo: goshopify.FulfillmentTrackingInfo{Number: "123456789"},
})

Fulfillment-order IDs and line-item IDs differ from order IDs and order line-item IDs. Omitting FulfillmentOrderLineItems fulfills all remaining items in that fulfillment order. Legacy LineItems are rejected. LocationId is not sent; Shopify uses the fulfillment orders' assigned location. Apps need the relevant fulfillment-order access scopes described in the linked documentation.

Update and Order.UpdateFulfillment now update tracking information and NotifyCustomer only. A nonempty TrackingInfo takes precedence over all legacy tracking fields. Otherwise, the singular legacy fields or single-element tracking slices are converted. Multiple tracking numbers or URLs require GraphQL and return an error instead of being truncated.

Order-scoped create, update and cancel calls make an additional read to check order membership before writing. Read errors stop the write. Use Order.ListFulfillments, Order.CountFulfillments and Order.GetFulfillment for order reads, or FulfillmentOrder.Fulfillments for a fulfillment order. Unscoped Fulfillment.List, Count and Get return ErrFulfillmentRequiresOrder.

Complete, Transition and their order wrappers return ErrFulfillmentOperationUnsupported without sending a request. Shopify removed these operations; a fulfillment ID must not be passed to fulfillment-order operations as a substitute.

Optional boolean settings

Writable boolean settings use *bool when omission and false have different meanings. Leave the field nil to omit it, or use goshopify.BoolPtr(false) to explicitly disable it. Use goshopify.BoolPtr(true) to enable it. This includes variant tax, article visibility, customer tax exemptions, and fulfillment-service settings. When reading an optional boolean, check for nil before dereferencing.

Using your own models

Not all endpoints are implemented right now. In those case, feel free to implement them and make a PR, or you can create your own struct for the data and use the client's Get, Post, Put, or Delete helpers. These helpers add the configured API path prefix. Pass a resource path such as webhooks.json, without admin/ or admin/api/<version>/.

For example, let's say you want to fetch webhooks. There's a helper function Get specifically for fetching stuff so this will work:

// Declare a model for the webhook
type Webhook struct {
    Id int         `json:"id"`
    Address string `json:"address"`
}

// Declare a model for the resource root.
type WebhooksResource struct {
    Webhooks []Webhook `json:"webhooks"`
}

func FetchWebhooks(ctx context.Context) ([]Webhook, error) {
    path := "webhooks.json"
    resource := new(WebhooksResource)
    client, err := goshopify.NewClient(app, "shopname", "token")
    if err != nil {
        return nil, err
    }

    // resource gets modified when calling Get
    err = client.Get(ctx, path, resource, nil)

    return resource.Webhooks, err
}

Webhooks verification

In order to be sure that a webhook is sent from ShopifyApi you could easily verify it with the VerifyWebhookRequest method.

For example:

func ValidateWebhook(httpRequest *http.Request) (bool) {
    shopifyApp := goshopify.App{ApiSecret: "ratz"}
    return shopifyApp.VerifyWebhookRequest(httpRequest)
}

Develop and test

docker and docker-compose must be installed

Mac/Linux/Windows with make

Using the make file is the easiest way to get started with the tests and wraps the manual steps below with easy to use make commands.

make && make test

Makefile goals

  • make or make container: default goal is to make the go-shopify:latest build container
  • make test: run go test in the container
  • make clean: deletes the go-shopify:latest image and coverage output
  • make coverage: generates the coverage.html and opens it

Manually

To run the tests you will need the go-shopify:latest image built to run your tests, to do this run

docker-compose build test

To run tests you can use run

docker-compose run --rm test

To create a coverage profile run the following to generate a coverage.html

docker-compose run --rm test sh -c 'go test -coverprofile=coverage.out ./... && go tool cover -html coverage.out -o coverage.html'

When done testing and you want to cleanup simply run

docker image rm go-shopify:latest

Read the docker-compose.yml and Dockerfile for further details.

About

Go client for the Shopify API

Resources

Stars

394 stars

Watchers

19 watching

Forks

Releases

Packages

Used by

Contributors

Languages