goshopify

package module
v0.0.0-...-39a362c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 10, 2016 License: MIT Imports: 14 Imported by: 0

README

go-shopify

Another Shopify Api Library in Go.

Warning: This library is not ready for primetime :-)

Build Status

Install

$ go get github.com/receiptful/go-shopify

Use

import "github.com/receiptful/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. Something like this will work:

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

// Create an oauth-authorize url for 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")
    authUrl := app.AuthorizeURL(shopName)
    http.Redirect(w, r, authUrl, http.StatusFound)
}

// Fetch a permanent access token in the callback
func MyCallbackHandler(w http.ResponseWriter, r *http.Request) {
    // Check that the callback signature is valid
    if !app.VerifyAuthorizationURL(r.URL) {
        http.Error(w, "Invalid Signature", http.StatusUnauthorized)
        return
    }

    query := r.URL.Query()
    shopName := query.Get("shop")
    code := query.Get("code")
    token, err := app.GetAccessToken(shopName, code)

    // Do something with the token, like store it in a DB.
}
Api calls

With a permanent access token, you can make API calls like this:

// 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 := goshopify.NewClient(app, "shopname", "token")

// Fetch the number of products.
numProducts, err := client.Product.Count(nil)
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(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(options)
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 NewRequest with the API client. This is how the existing endpoints are implemented.

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() ([]Webhook, error) {
    path := "admin/webhooks.json"
    resource := new(WebhooksResoure)
    client := goshopify.NewClient(app, "shopname", "token")

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

    return resource.Webhooks, err
}

Develop and test

There's nothing special to note about the tests except that if you have Docker and Compose installed, you can test like this:

$ docker build -t goshopify .
$ docker-compose run test

Documentation

Index

Constants

View Source
const (
	UserAgent = "goshopify/0.1.0"
)

Variables

This section is empty.

Functions

func CheckResponseError

func CheckResponseError(r *http.Response) error

func ShopBaseUrl

func ShopBaseUrl(name string) string

Return the Shop's base url.

func ShopFullName

func ShopFullName(name string) string

Return the full shop name, including .myshopify.com

func ShopShortName

func ShopShortName(name string) string

Return the short shop name, excluding .myshopify.com

Types

type Address

type Address struct {
	ID           int     `json:"id"`
	Address1     string  `json:"address1"`
	Address2     string  `json:"address2"`
	City         string  `json:"city"`
	Company      string  `json:"company"`
	Country      string  `json:"country"`
	CountryCode  string  `json:"country_code"`
	FirstName    string  `json:"first_name"`
	LastName     string  `json:"last_name"`
	Latitude     float64 `json:"latitude"`
	Longitude    float64 `json:"longitude"`
	Name         string  `json:"name"`
	Phone        string  `json:"phone"`
	Province     string  `json:"province"`
	ProvinceCode string  `json:"province_code"`
	Zip          string  `json:"zip"`
}

type App

type App struct {
	ApiKey      string
	ApiSecret   string
	RedirectUrl string
	Scope       string
}

Basic app settings such as Api key, secret, scope, and redirect url. See oauth.go for OAuth related helper functions.

func (App) AuthorizeUrl

func (app App) AuthorizeUrl(shopName string, state string) string

Returns a Shopify oauth authorization url for the given shopname and state.

State is a unique value that can be used to check the authenticity during a callback from Shopify.

func (App) GetAccessToken

func (app App) GetAccessToken(shopName string, code string) (string, error)

func (App) VerifyAuthorizationURL

func (app App) VerifyAuthorizationURL(u *url.URL) bool

Verifying URL callback parameters.

func (App) VerifyMessage

func (app App) VerifyMessage(message, messageMAC string) bool

Verify a message against a message HMAC

type Client

type Client struct {

	// Services used for communicating with the API
	Product  ProductService
	Customer CustomerService
	Order    OrderService
	Shop     ShopService
	Webhook  WebhookService
	// contains filtered or unexported fields
}

Client manages communication with the Shopify API.

func NewClient

func NewClient(app App, shopName, token string) *Client

Returns a new Shopify API client with an already authenticated shopname and token.

func (*Client) Count

func (c *Client) Count(path string, options interface{}) (int, error)

func (*Client) CreateAndDo

func (c *Client) CreateAndDo(method, path string, data, options, resource interface{}) error

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) error

Do sends an API request and populates the given interface with the parsed response. It does not make much sense to call Do without a prepared interface instance.

func (*Client) Get

func (c *Client) Get(path string, resource, options interface{}) error

Perform a Get request for the given path and save the result in the given resource.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body, options interface{}) (*http.Request, error)

Creates an API request. A relative URL can be provided in urlStr, which will be resolved to the BaseURL of the Client. Relative URLS should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body.

func (*Client) Post

func (c *Client) Post(path string, data, resource interface{}) error

Perform a POST request for the given path and save the result in the given resource.

func (*Client) Put

func (c *Client) Put(path string, data, resource interface{}) error

Perform a PUT request for the given path and save the result in the given resource.

type CountOptions

type CountOptions struct {
	CreatedAtMin time.Time `url:"created_at_min,omitempty"`
	CreatedAtMax time.Time `url:"created_at_max,omitempty"`
}

General count options that can be used for most collection counts.

type Customer

type Customer struct {
	ID        int    `json:"id"`
	Email     string `json:"email"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
}

Customer represents a Shopify customer

type CustomerResource

type CustomerResource struct {
	Customer *Customer `json:"customer"`
}

Represents the result from the customers/X.json endpoint

type CustomerService

type CustomerService interface {
	List(interface{}) ([]Customer, error)
	Count(interface{}) (int, error)
	Get(int, interface{}) (*Customer, error)
}

CustomerService is an interface for interfacing with the customers endpoints of the Shopify API. See: https://help.shopify.com/api/reference/customer

type CustomerServiceOp

type CustomerServiceOp struct {
	// contains filtered or unexported fields
}

CustomerServiceOp handles communication with the product related methods of the Shopify API.

func (*CustomerServiceOp) Count

func (s *CustomerServiceOp) Count(options interface{}) (int, error)

Count customers

func (*CustomerServiceOp) Get

func (s *CustomerServiceOp) Get(customerID int, options interface{}) (*Customer, error)

Get customer

func (*CustomerServiceOp) List

func (s *CustomerServiceOp) List(options interface{}) ([]Customer, error)

List customers

type CustomersResource

type CustomersResource struct {
	Customers []Customer `json:"customers"`
}

Represents the result from the customers.json endpoint

type DiscountCode

type DiscountCode struct {
	Amount *decimal.Decimal `json:"amount"`
	Code   string           `json:"code"`
	Type   string           `json:"type"`
}

type LineItem

type LineItem struct {
	ID            int              `json:"id"`
	ProductID     int              `json:"product_id"`
	VariantID     int              `json:"variant_id"`
	Quantity      int              `json:"quantity"`
	Price         *decimal.Decimal `json:"price"`
	TotalDiscount *decimal.Decimal `json:"total_discount"`
	Title         string           `json:"title"`
	VariantTitle  string           `json:"variant_title"`
	Name          string           `json:"name"`
	SKU           string           `json:"sku"`
	Vendor        string           `json:"vendor"`
	GiftCard      bool             `json:"gift_card"`
	Taxable       bool             `json:"taxable"`
}

type LineItemProperty

type LineItemProperty struct {
	Message string `json:"message"`
}

type ListOptions

type ListOptions struct {
	Page         int       `url:"page,omitempty"`
	Limit        int       `url:"limit,omitempty"`
	SinceID      int       `url:"since_id,omitempty"`
	CreatedAtMin time.Time `url:"created_at_min,omitempty"`
	CreatedAtMax time.Time `url:"created_at_max,omitempty"`
}

General list options that can be used for most collections of entities.

type NoteAttribute

type NoteAttribute struct {
	Name  string `json:"Name"`
	Value string `json:"Value"`
}

type Order

type Order struct {
	ID                    int              `json:"id"`
	Name                  string           `json:"name"`
	Email                 string           `json:"email"`
	CreatedAt             *time.Time       `json:"created_at"`
	UpdatedAt             *time.Time       `json:"updated_at"`
	ClosedAt              *time.Time       `json:"closed_at"`
	ProcessedAt           *time.Time       `json:"processed_at"`
	Customer              *Customer        `json:"customer"`
	BillingAddress        *Address         `json:"billing_address"`
	ShippingAddress       *Address         `json:"shipping_address"`
	Currency              string           `json:"currency"`
	TotalPrice            *decimal.Decimal `json:"total_price"`
	SubtotalPrice         *decimal.Decimal `json:"subtotal_price"`
	TotalDiscounts        *decimal.Decimal `json:"total_discounts"`
	TotalLineItemsPrice   *decimal.Decimal `json:"total_line_items_price"`
	TotalTax              *decimal.Decimal `json:"total_tax"`
	TotalWeight           int              `json:"total_weight"`
	FinancialStatus       string           `json:"financial_status"`
	FulfillmentStatus     string           `json:"fulfillment_status"`
	Token                 string           `json:"token"`
	CartToken             string           `json:"cart_token"`
	Number                int              `json:"number"`
	OrderNumber           int              `json:"order_number"`
	Note                  string           `json:"note"`
	Test                  bool             `json:"test"`
	BrowserIp             string           `json:"browser_ip"`
	BuyerAcceptsMarketing bool             `json:"buyer_accepts_marketing"`
	CancelReason          string           `json:"cancel_reason"`
	NoteAttributes        []NoteAttribute  `json:"note_attributes"`
	DiscountCodes         []DiscountCode   `json:"discount_codes"`
	LineItems             []LineItem       `json:"line_items"`
}

Order represents a Shopify order

type OrderListOptions

type OrderListOptions struct {
	Page              int       `url:"page,omitempty"`
	Limit             int       `url:"limit,omitempty"`
	SinceID           int       `url:"since_id,omitempty"`
	Status            string    `url:"status,omitempty"`
	FinancialStatus   string    `url:"financial_status,omitempty"`
	FulfillmentStatus string    `url:"fulfillment_status,omitempty"`
	CreatedAtMin      time.Time `url:"created_at_min,omitempty"`
	CreatedAtMax      time.Time `url:"created_at_max,omitempty"`
	UpdatedAtMin      time.Time `url:"updated_at_min,omitempty"`
	UpdatedAtMax      time.Time `url:"updated_at_max,omitempty"`
	ProcessedAtMin    time.Time `url:"processed_at_min,omitempty"`
	ProcessedAtMax    time.Time `url:"processed_at_max,omitempty"`
	Fields            string    `url:"fields,omitempty"`
}

A struct for all available order list options. See: https://help.shopify.com/api/reference/order#index

type OrderResource

type OrderResource struct {
	Order *Order `json:"order"`
}

Represents the result from the orders/X.json endpoint

type OrderService

type OrderService interface {
	List(interface{}) ([]Order, error)
	Count(interface{}) (int, error)
	Get(int, interface{}) (*Order, error)
}

OrderService is an interface for interfacing with the orders endpoints of the Shopify API. See: https://help.shopify.com/api/reference/order

type OrderServiceOp

type OrderServiceOp struct {
	// contains filtered or unexported fields
}

OrderServiceOp handles communication with the order related methods of the Shopify API.

func (*OrderServiceOp) Count

func (s *OrderServiceOp) Count(options interface{}) (int, error)

Count orders

func (*OrderServiceOp) Get

func (s *OrderServiceOp) Get(orderID int, options interface{}) (*Order, error)

Get individual order

func (*OrderServiceOp) List

func (s *OrderServiceOp) List(options interface{}) ([]Order, error)

List orders

type OrdersResource

type OrdersResource struct {
	Orders []Order `json:"orders"`
}

Represents the result from the orders.json endpoint

type Product

type Product struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

Product represents a Shopify product

type ProductResource

type ProductResource struct {
	Product *Product `json:"product"`
}

Represents the result from the products/X.json endpoint

type ProductService

type ProductService interface {
	List(interface{}) ([]Product, error)
	Count(interface{}) (int, error)
	Get(int, interface{}) (*Product, error)
}

ProductService is an interface for interfacing with the product endpoints of the Shopify API. See: https://help.shopify.com/api/reference/product

type ProductServiceOp

type ProductServiceOp struct {
	// contains filtered or unexported fields
}

ProductServiceOp handles communication with the product related methods of the Shopify API.

func (*ProductServiceOp) Count

func (s *ProductServiceOp) Count(options interface{}) (int, error)

Count products

func (*ProductServiceOp) Get

func (s *ProductServiceOp) Get(productID int, options interface{}) (*Product, error)

Get individual product

func (*ProductServiceOp) List

func (s *ProductServiceOp) List(options interface{}) ([]Product, error)

List products

type ProductsResource

type ProductsResource struct {
	Products []Product `json:"products"`
}

Represents the result from the products.json endpoint

type ResponseError

type ResponseError struct {
	Status  int
	Message string
	Errors  []string
}

A general response error that follows a similar layout to Shopify's response errors, i.e. either a single message or a list of messages.

func (ResponseError) Error

func (e ResponseError) Error() string

type Shop

type Shop struct {
	ID                      int        `json:"id"`
	Name                    string     `json:"name"`
	ShopOwner               string     `json:"shop_owner"`
	Email                   string     `json:"email"`
	CreatedAt               *time.Time `json:"created_at"`
	UpdatedAt               *time.Time `json:"updated_at"`
	Address1                string     `json:"address1"`
	City                    string     `json:"city"`
	Country                 string     `json:"country"`
	CountryCode             string     `json:"country_code"`
	CountryName             string     `json:"country_name"`
	Currency                string     `json:"currency"`
	Domain                  string     `json:"domain"`
	Latitude                float64    `json:"latitude"`
	Longitude               float64    `json:"longitude"`
	Phone                   string     `json:"phone"`
	Province                string     `json:"province"`
	ProvinceCode            string     `json:"province_code"`
	Zip                     string     `json:"zip"`
	MoneyFormat             string     `json:"money_format"`
	MoneyWithCurrencyFormat string     `json:"money_with_currency_format"`
	MyshopifyDomain         string     `json:"myshopify_domain"`
	PlanName                string     `json:"plan_name"`
	PlanDisplayName         string     `json:"plan_display_name"`
	PasswordEnabled         bool       `json:"password_enabled"`
	PrimaryLocale           string     `json:"primary_locale"`
	Timezone                string     `json:"timezone"`
	IanaTimezone            string     `json:"iana_timezone"`
	ForceSSL                bool       `json:"force_ssl"`
	HasStorefront           bool       `json:"has_storefront"`
	HasDiscounts            bool       `json:"has_discounts"`
	HasGiftcards            bool       `json:"has_gift_cards"`
	SetupRequire            bool       `json:"setup_required"`
	CountyTaxes             bool       `json:"county_taxes"`
}

Shop represents a Shopify shop

type ShopResource

type ShopResource struct {
	Shop *Shop `json:"shop"`
}

Represents the result from the admin/shop.json endpoint

type ShopService

type ShopService interface {
	Get(options interface{}) (*Shop, error)
}

ShopService is an interface for interfacing with the shop endpoint of the Shopify API. See: https://help.shopify.com/api/reference/shop

type ShopServiceOp

type ShopServiceOp struct {
	// contains filtered or unexported fields
}

ShopServiceOp handles communication with the shop related methods of the Shopify API.

func (*ShopServiceOp) Get

func (s *ShopServiceOp) Get(options interface{}) (*Shop, error)

Get shop

type Webhook

type Webhook struct {
	ID                  int        `json:"id"`
	Address             string     `json:"address"`
	Topic               string     `json:"topic"`
	Format              string     `json:"format"`
	CreatedAt           *time.Time `json:"created_at,omitempty"`
	UpdatedAt           *time.Time `json:"updated_at,omitempty"`
	Fields              []string   `json:"fields"`
	MetafieldNamespaces []string   `json:"metafield_namespaces"`
}

Webhook represents a Shopify webhook

type WebhookOptions

type WebhookOptions struct {
	Address string `url:"address,omitempty"`
	Topic   string `url:"topic,omitempty"`
}

type WebhookResource

type WebhookResource struct {
	Webhook *Webhook `json:"webhook"`
}

Represents the result from the admin/shop.json endpoint

type WebhookService

type WebhookService interface {
	List(interface{}) ([]Webhook, error)
	Count(interface{}) (int, error)
	Get(int, interface{}) (*Webhook, error)
	Create(Webhook) (*Webhook, error)
	Update(Webhook) (*Webhook, error)
}

WebhookService is an interface for interfacing with the webhook endpoints of the Shopify API. See: https://help.shopify.com/api/reference/webhook

type WebhookServiceOp

type WebhookServiceOp struct {
	// contains filtered or unexported fields
}

ShopServiceOp handles communication with the shop related methods of the Shopify API.

func (*WebhookServiceOp) Count

func (s *WebhookServiceOp) Count(options interface{}) (int, error)

Count webhooks

func (*WebhookServiceOp) Create

func (s *WebhookServiceOp) Create(webhook Webhook) (*Webhook, error)

Create a new webhook

func (*WebhookServiceOp) Get

func (s *WebhookServiceOp) Get(webhookdID int, options interface{}) (*Webhook, error)

Get individual webhook

func (*WebhookServiceOp) List

func (s *WebhookServiceOp) List(options interface{}) ([]Webhook, error)

List webhooks

func (*WebhookServiceOp) Update

func (s *WebhookServiceOp) Update(webhook Webhook) (*Webhook, error)

Update an existing webhook.

type WebhooksResource

type WebhooksResource struct {
	Webhooks []Webhook `json:"webhooks"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL