goshopify

package module
v0.0.0-...-a563c19 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2022 License: MIT Imports: 7 Imported by: 0

README

goshopify

Open source Shopify Golang library. I will be very happy and welcome if you would like to provide your contribution to this library.

Note: This library only supports below resource right now:

  • Access Scopes
  • Access Token
  • Address
  • Application Charge
  • Application Credit
  • Customer
  • Discount Code
  • Draft Order
  • Event
  • Inventory Item
  • Metafield
  • Order
  • Price Rule
  • Product
  • Product Image
  • Recurring Application Charge
  • Report
  • Script Tag
  • Storefront Access Token
  • Theme
  • Variant

Install

$ go get github.com/lengzuo/goshopify

Use

import "github.com/lengzuo/goshopify"

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 to init OAuth.
app := goshopify.App{
    Credentials: common.Credentials{
        APIKey:    "abcd",
        APISecret: "abcd_1234",
    },
    RedirectURL: "https://authorized-redirect-url.com",
    Scope:       "read_products", 
}

// Perform OAuth Authentication for your app and redirect client to the authorizedURL 
func ShopOAuth(w http.ResponseWriter, r *http.Request) {
    shopName := r.URL.Query().Get("shop")
    state := "nonce"
    authUrl := app.AuthorizeURL(shopName, state)
    http.Redirect(w, r, authUrl, http.StatusFound)
}

// Retrieve a permanent access token from OAuth callback
func OAuthCallback(w http.ResponseWriter, r *http.Request) {
    // Validate callback URL 
    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")
    
	// Init /admin/oauth shopify client with your shopName
    adminOAuthClient := app.AdminClient(shopName)

    ctx := context.TODO()
	// Request admin access token from shopify
    resp, err := app.GetAccessToken(shopName, code)
    if err != nil {
        http.Error(w, fmt.Sprintf("error while calling app.GetAccessToken: %s", err), http.StatusInternalServerError)
		return
	}
	
    // Do something with the token, like store it in a DB.
	fmt.Printf("token is: %s", resp.AccessToken)

	// Access admin/oauth get access scopes API 
    _, err = adminOAuthClient.GetAccessScopes(ctx)
    if err != nil {
        http.Error(w, fmt.Sprintf("err oauthClient.GetAccessScopes(ctx) is : %s", err), http.StatusInternalServerError)
        return
    }
}
API calls with the access token

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

    ctx := context.TODO()
    client := adminapi.New("ShopName",
        adminapi.WithToken("Token"),
        adminapi.WithVersion("2022-01"),
    )

    productsResp, err := client.Product.Get(ctx, dto.GetProductRequest{})
    if err != nil {
        fmt.Printf("err client.GetProducts is : %s", err)
        return
    }

    fmt.Printf("Get products response is : %+v", productsResp.Products)

    productCount, err := client.Product.Count(ctx, dto.CountProductRequest{})
    if err != nil {
        fmt.Printf("err client.Product is : %s", err)
        return
    }

    fmt.Printf("Get product count response is : %d", productCount.Count)
Private App Auth

Private Shopify apps use basic authentication.

// Create an app somewhere.
ctx := context.TODO()
client := adminapi.New("ShopName",
    adminapi.WithCredentials(common.Credentials{
        Password:  "password",
        APIKey:    "APIKey",
	}),
)

// Fetch the products.
productsResp, err := client.Product.Get(ctx, dto.GetProductRequest{}))
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 := adminapi.New("ShopName",
    adminapi.WithToken("Token"),
    adminapi.WithVersion("2022-01"),
)
Define you own shopify resources API

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"`
}

client := adminapi.New("ShopName",
    adminapi.WithToken("Token"),
)
ctx := context.TODO()
path := "admin/webhooks.json"
resp := new(WebhooksResource)
err := client.Call(ctx, http.MethodGet, path, nil, resp)
if err != nil {
    fmt.Printf("error is: %s\n", err)
    return
}

bytes, _ := json.Marshal(resp)
fmt.Printf("resp: %s", bytes)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	Credentials common.Credentials
	RedirectURL string
	Scope       string
}

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

func (App) AdminClient

func (a App) AdminClient(shopName string) adminoauth.API

func (App) AuthorizeURL

func (a App) AuthorizeURL(shopName string, state string) string

func (App) VerifyAuthorizationURL

func (a App) VerifyAuthorizationURL(u *url.URL) (bool, error)

VerifyAuthorizationURL use to check callback parameters from url.

func (App) VerifyMessage

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

VerifyMessage uses to verify message against a message HMAC

type Authorize

type Authorize struct {
	ClientID    string `url:"client_id"`
	RedirectURI string `url:"redirect_uri"`
	Scope       string `url:"scope"`
	State       string `url:"state"`
}

Jump to

Keyboard shortcuts

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