npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

api-v2-js-sdk

v1.1.5

Published

Node module to easily integrate your JavaScript or TypeScript application with Spree API V2. You can create an entirely custom Storefront in JS/TS with this package including one page checkout, Single Page Apps, PWAs and so on

Downloads

8

Readme

Spree Commerce Storefront API v2 JavaScript / TypeScript SDK

Node module to easily integrate your JavaScript or TypeScript application with Spree API V2. You can create an entirely custom Storefront in JS/TS with this package including one page checkout, Single Page Apps, PWAs and so on.

Developed and maintained by:

Spark Solutions

Сontents:

Quick start

Installation

npm install @spree/storefront-api-v2-sdk --save

Creating a Spree client

import { makeClient } from '@spree/storefront-api-v2-sdk'
// When using the SDK in a <script> tag or as part of a Webpack bundle
// targeted for the browser, instead use:
// import { makeClient } from '@spree/storefront-api-v2-sdk/dist/client'

const client = makeClient({
  host: 'http://localhost:3000'
})

TypeScript definitions are included in the module and should be automatically used by any editor that supports them.

client allows calling Spree methods, ex.:

client.products.list({
  include: 'default_variant',
  page: 1
})

Response schema

Success schema

Client methods return a result object. When a request succeeds, the data received from Spree is retrievable using its success() method and provided in the JSON:API format. isSuccess() tells if a request succeeded.

Error schema

The SDK avoids throwing JavaScript Errors. Instead, any error is included in a result object.

To determine whether a call was successful, use isSuccess() or isFail() methods on the result. Details of a failed call can be retrieved using fail(). The method returns a SpreeSDKError instance, which is the primary type for all errors returned by the SDK and extends the native JavaScript Error type.

Available SpreeSDKError subtypes:

|Class Name|Purpose| |---|---| |MisconfigurationError|Signifies the SDK's Client was created with improper options. Make sure the values of host and other options (if any) provided to Client have the correct format.| |NoResponseError|Spree store could not be reached. Ensure it's running and available under the host address provided to the Client instance.| |SpreeError|Spree responded with an error. To debug the issue, check the error's serverResponse field. It contains details about the response from Spree, such as the HTTP status code and headers.| |BasicSpreeError|Extends SpreeError with a summary field provided by Spree and containing a summary of the issue.| |ExpandedSpreeError|Extends BasicSpreeError with a errors field. errors contains a detailed explanation of the issue, ex. all the validation errors when trying to add shipping details to a Spree order. The getErrors method can be used to retrieve a concrete value inside errors, ex. expSpreeError.getErrors(['bill_address', 'firstname']).|

The specific type of error returned by fail() can be determined using instanceof, ex. if(response.fail() instanceof BasicSpreeError){...}.

Tokens

Most endpoints require a token for authentication. It can be either an Order Token or Bearer Token.

Order token

Identifies a guest user's cart and order.

const response = await client.cart.create()

const orderToken: string = response.success().data.attributes.token

Bearer token

Identifies a logged in user.

const response = await client.authentication.getToken({
  username: '[email protected]',
  password: 'spree123'
})

const bearerToken: string = response.success().access_token

Endpoints

Spree Storefront API SDK contains each endpoint according to Spree Guides

OAuth Authentication

getToken

Creates a Bearer token required to authorize OAuth API calls.

Parameters schema:

username: string
password: string

Success response schema:

access_token: string
token_type: string = 'Bearer'
expires_in: number
refresh_token: string
created_at: number

Failure response schema: Error schema

Example:

const token = await client.authentication.getToken({
  username: '[email protected]',
  password: 'spree123'
})

refreshToken

Method refreshToken refreshes a Bearer token required to authorize OAuth API calls.

Parameters schema:

refresh_token: string

Success response schema:

access_token: string
token_type: string = 'Bearer'
expires_in: number
refresh_token: string
created_at: number

Failure response schema: Error schema

Example:

const token = await client.authentication.refreshToken({
  refresh_token: 'aebe2886d7dbba6f769e20043e40cfa3447e23ad9d8e82c632f60ed63a2f0df1'
})

Account

accountInfo

Returns current user information.

Required token: Bearer token

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.account.accountInfo({ bearerToken })

creditCardsList

Returns a list of Credit Cards for the signed in User.

Required token: Bearer token

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.account.creditCardsList({ bearerToken })

defaultCreditCard

Return the User's default Credit Card.

Required token: Bearer token

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.account.defaultCreditCard({ bearerToken })

completedOrdersList

Returns Orders placed by the User. Only completed ones.

Required token: Bearer token

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.account.completedOrdersList({ bearerToken })

completedOrder

Return the User's completed Order.

Required token: Bearer token

Parameters schema:

orderNumber: string

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.account.completedOrder({ bearerToken }, 'R653163382')

Order

status

Returns placed Order.

Parameters schema:

orderNumber: string

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.order.status('R653163382')

Cart

create

Creates new Cart and returns it attributes.

Required token: Bearer token if logged in user

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.create({ bearerToken })

// or guest user
const response = await client.cart.create()

show

Returns contents of the cart.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.show({ bearerToken })

// or guest user
const response = await client.cart.show({ orderToken })

addItem

Adds a Product Variant to the Cart.

Required token: Bearer token or Order token

Parameters schema:

{
  variant_id: string
  quantity: number
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.addItem({ bearerToken }, {
  variant_id: '1',
  quantity: 1
})

// or guest user
const response = await client.cart.addItem({ orderToken }, {
  variant_id: '1',
  quantity: 1
})

setQuantity

Sets the quantity of a given line item. It has to be a positive integer greater than 0.

Required token: Bearer token or Order token

Parameters schema:

{
  line_item_id: string
  quantity: number
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.setQuantity({ bearerToken }, {
  line_item_id: '9',
  quantity: 100
})

// or guest user
const response = await client.cart.setQuantity({ orderToken }, {
  line_item_id: '9',
  quantity: 100
})

removeItem

Removes Line Item from Cart.

Required token: Bearer token or Order token

Parameters schema:

line_item_id: string

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.removeItem({ bearerToken }, '1')

// or guest user
const response = await client.cart.removeItem({ orderToken }, '1')

emptyCart

Empties the Cart.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.emptyCart({ bearerToken })

// or guest user
const response = await client.cart.emptyCart({ orderToken })

applyCouponCode

Applies a coupon code to the Cart.

Required token: Bearer token or Order token

Parameters schema:

{
  coupon_code: string
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Loged in user
const response = await client.cart.applyCouponCode({ bearerToken }, {
  coupon_code: 'promo_test'
})

// or guest user
const response = await client.cart.applyCouponCode({ orderToken  }, {
  coupon_code: 'promo_test'
})

removeCouponCode

Removes a coupon code from the Cart.

Required token: Bearer token or Order token

Optional parameters schema:

coupon_code?: string

Success response schema: Success schema

Filed response schema: Error schema

Example:

// Logged in user
const response = await client.cart.removeCouponCode({ bearerToken }, 'promo_test')

// or guest user
const response = await client.cart.removeCouponCode({ orderToken }, 'promo_test')

estimateShippingMethods

Returns a list of Estimated Shipping Rates for Cart.

Required token: Bearer token or Order token

Parameters schema:

country_iso: string

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.cart.estimateShippingMethods({ bearerToken }, 'USA')

// or guest user
const response = await client.cart.estimateShippingMethods({ orderToken }, 'USA')

Checkout

orderUpdate

Updates the Checkout You can run multiple Checkout updates with different data types.

Required token: Bearer token or Order token

Parameters schema:

order: {
  email: string
  bill_address_attributes?: {
    firstname: string
    lastname: string
    address1: string
    city: string
    phone: string
    zipcode: string
    state_name: string
    country_iso: string
  }
  ship_address_attributes?: {
    firstname: string
    lastname: string
    address1: string
    city: string
    phone: string
    zipcode: string
    state_name: string
    country_iso: string
  }
  shipments_attributes?: [
    {
      selected_shipping_rate_id: number
      id: number
    }
  ]
  payments_attributes?: [
    {
      payment_method_id: number
    }
  ]
}
payment_source?: {
  [payment_method_id: number]: {
    number: string
    month: string
    year: string
    verification_value: string
    name: string
  }
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.orderUpdate({ bearerToken }, { order: {...} })

// or guest user
const response = await client.checkout.orderUpdate({ orderToken }, { order: {...} })

orderNext

Goes to the next Checkout step.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.orderNext({ bearerToken })

// or guest user
const response = await client.checkout.orderNext({ orderToken })

advance

Advances Checkout to the furthest Checkout step validation allows, until the Complete step.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.advance({ bearerToken })

// or guest user
const response = await client.checkout.advance({ orderToken })

complete

Completes the Checkout.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.complete({ bearerToken })

// or guest user
const response = await client.checkout.complete({ orderToken })

addStoreCredits

Adds Store Credit payments if a user has any.

Required token: Bearer token or Order token

Parameters schema:

{
  amount: number
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.addStoreCredits({ bearerToken }, { amount: 100 })

// or guest user
const response = await client.checkout.addStoreCredits({ orderToken }, { amount: 100 })

removeStoreCredits

Remove Store Credit payments if any applied.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.removeStoreCredits({ bearerToken })

// or guest user
const response = await client.checkout.removeStoreCredits({ orderToken })

paymentMethods

Returns a list of available Payment Methods.

Required token: Bearer token or Order token

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.paymentMethods({ bearerToken })

// or guest user
const response = await client.checkout.paymentMethods({ orderToken })

shippingMethods

Returns a list of available Shipping Rates for Checkout. Shipping Rates are grouped against Shipments. Each checkout cna have multiple Shipments eg. some products are available in stock and will be send out instantly and some needs to be backordered.

Required token: Bearer token or Order token

Optional parameters schema:

{
  params?: {
    include?: string
  }
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

// Logged in user
const response = await client.checkout.shippingMethods({ bearerToken }, {
  include: 'shipping_rates'
})

// or guest user
const response = await client.checkout.shippingMethods({ orderToken }, {
  include: 'shipping_rates'
})

Products

Returns a list of Products.

list

Optional parameters schema:

{
  include?: string
  fields?: {
    [key: string]: string
  }
  filter?: {
    [key: string]: number
  }
  sort?: string
  page?: number
  per_page?: number
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.products.list()

show

Optional parameters schema:

{
  id: string
  params?: {
    include: string
    fields: {
      [key: string]: string
    }
  }
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = = await client.products.show('123')

Taxons

list

Returns a list of Taxons.

Optional parameters schema:

{
  include?: string
  fields?: {
    [key: string]: string
  }
  filter?: {
    [key: string]: number
  }
  page?: number
  per_page?: number
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

const response = await client.taxons.list()

show

Returns a single Taxon.

Optional parameters schema:

{
  id: string
  params?: {
    include: string
    fields: {
      [key: string]: string
    }
  }
}

Success response schema: Success schema

Failure response schema: Error schema

Example:

const products = await client.taxons.show('1')

Checkout Flow

One step

const cartCreateResponse = await client.cart.create()

const orderToken = cartCreateResponse.success().data.attributes.token

await client.cart.addItem({ orderToken }, { variant_id: '1' })

// Save a shipping address for shipping methods
await client.checkout.orderUpdate({ orderToken }, {
  order: {
    ship_address_attributes: {...}
  }
})

const shipping = (await client.checkout.shippingMethods({ orderToken })).success()

const payment = (await client.checkout.paymentMethods({ orderToken })).success()

// Pick a shipping and payment method

await client.checkout.orderUpdate({ orderToken }, { order: {...} })

await client.checkout.complete({ orderToken })

Three steps

const cartCreateResponse = await client.cart.create()

const orderToken = cartCreateResponse.success().data.attributes.token

await client.cart.addItem({ orderToken }, { variant_id: '1' })

// Step one - save email, billing and shipping addresses
await client.checkout.orderUpdate({ orderToken }, {
  order: {
    email,
    bill_address_attributes: {...},
    ship_address_attributes: {...}
  }
})

await client.checkout.orderNext({ bearerToken })

// Step two - pick a shipping method
const shipping = (await client.checkout.shippingMethods({ orderToken })).success()

await client.checkout.orderUpdate({ orderToken }, {
  order: {
    shipments_attributes: [{
      id: shipping.data[0].id,
      selected_shipping_rate_id: shipping.data[0].relationships.shipping_rates.data[0].id
    }]
  }
})

await client.checkout.orderNext({ orderToken })

// Step three - pick a payment method
const payment = (await client.checkout.paymentMethods({ orderToken })).success()

await client.checkout.orderUpdate({ orderToken }, {
  order: {
    payments_attributes: [{
      payment_method_id: payment.data[0].id
    }]
  },
  payment_source: {
    [payment.data[0].id]: {
      number: '4111111111111111',
      month: '1',
      year: '2022',
      verification_value: '123',
      name: 'John Doe'
    }
  }
})

// Order complete
await client.checkout.orderNext({ orderToken })

await client.checkout.complete({ orderToken })

About Spark Solutions

Spark Solutions

Spree is maintained by Spark Solutions Sp. z o.o..

We are passionate about open source software. We are available for hire.