Giter Club home page Giter Club logo

js-buy-sdk's Introduction

Shopify JavaScript Buy SDK

Build

Note: For help with migrating from v0 of JS Buy SDK to v1 check out the Migration Guide.

The JS Buy SDK is a lightweight library that allows you to build ecommerce into any website. It's based on Shopify's Storefront API and provides the ability to retrieve products and collections from your shop, add products to a cart, and checkout.

Full API docs are available here.

Changelog

View our Changelog for details about our releases.

SDK Version Support

Each version of the JS Buy SDK uses a specific Storefront API version and the support of an SDK version is directly linked to the support of the corresponding Storefront API version. Storefront API versioning information can be found here.

Table Of Contents

Installation

With Yarn:

$ yarn add shopify-buy

With NPM:

$ npm install shopify-buy

CDN:

There is a minified UMD build of the latest release available via CDN (see the Changelog for details about the latest release):

<script src="https://sdks.shopifycdn.com/js-buy-sdk/v2/latest/index.umd.min.js"></script>

If you don't want to use the latest version, you can use a specific older release version:

<script src="https://sdks.shopifycdn.com/js-buy-sdk/1.11.0/index.umd.min.js"></script>

You can also fetch the unoptimized release for a version (2.0.1 and above). This will be larger than the optimized version, as it will contain all fields that are available in the Storefront API:

<script src="https://sdks.shopifycdn.com/js-buy-sdk/2.0.1/index.unoptimized.umd.min.js"></script>

Builds

The JS Buy SDK has four build versions: ES, CommonJS, AMD, and UMD.

ES, CommonJS:

import Client from 'shopify-buy';

AMD:

import Client from 'shopify-buy/index.amd';

UMD:

import Client from 'shopify-buy/index.umd';

UMD Unoptimized: This will be larger than the optimized version, as it will contain all fields that are available in the Storefront API. This should only be used when you need to add custom queries to supplement the JS Buy SDK queries.

import Client from 'shopify-buy/index.unoptimized.umd';

Examples

Initializing the Client

If your store supports multiple languages, Storefront API can return translated resource types and fields. Learn more about translating content.

import Client from 'shopify-buy';

// Initializing a client to return content in the store's primary language
const client = Client.buildClient({
  domain: 'your-shop-name.myshopify.com',
  storefrontAccessToken: 'your-storefront-access-token'
});

// Initializing a client to return translated content
const clientWithTranslatedContent = Client.buildClient({
  domain: 'your-shop-name.myshopify.com',
  storefrontAccessToken: 'your-storefront-access-token',
  language: 'ja-JP'
});

Fetching Products

// Fetch all products in your shop
client.product.fetchAll().then((products) => {
  // Do something with the products
  console.log(products);
});

// Fetch a single product by ID
const productId = 'gid://shopify/Product/7857989384';

client.product.fetch(productId).then((product) => {
  // Do something with the product
  console.log(product);
});

// Fetch a single product by Handle
const handle = 'product-handle';

client.product.fetchByHandle(handle).then((product) => {
  // Do something with the product
  console.log(product);
});

Fetching Collections

// Fetch all collections, including their products
client.collection.fetchAllWithProducts().then((collections) => {
  // Do something with the collections
  console.log(collections);
  console.log(collections[0].products);
});

// Fetch a single collection by ID, including its products
const collectionId = 'gid://shopify/Collection/369312584';
// Set a parameter for first x products, defaults to 20 if you don't provide a param

client.collection.fetchWithProducts(collectionId, {productsFirst: 10}).then((collection) => {
  // Do something with the collection
  console.log(collection);
  console.log(collection.products);
});

Creating a Checkout

// Create an empty checkout
client.checkout.create().then((checkout) => {
  // Do something with the checkout
  console.log(checkout);
});

Updating checkout attributes

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8';
const input = {customAttributes: [{key: "MyKey", value: "MyValue"}]};

client.checkout.updateAttributes(checkoutId, input).then((checkout) => {
  // Do something with the updated checkout
});

Adding Line Items

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'; // ID of an existing checkout
const lineItemsToAdd = [
  {
    variantId: 'gid://shopify/ProductVariant/29106064584',
    quantity: 5,
    customAttributes: [{key: "MyKey", value: "MyValue"}]
  }
];

// Add an item to the checkout
client.checkout.addLineItems(checkoutId, lineItemsToAdd).then((checkout) => {
  // Do something with the updated checkout
  console.log(checkout.lineItems); // Array with one additional line item
});

Updating Line Items

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'; // ID of an existing checkout
const lineItemsToUpdate = [
  {id: 'gid://shopify/CheckoutLineItem/194677729198640?checkout=e3bd71f7248c806f33725a53e33931ef', quantity: 2}
];

// Update the line item on the checkout (change the quantity or variant)
client.checkout.updateLineItems(checkoutId, lineItemsToUpdate).then((checkout) => {
  // Do something with the updated checkout
  console.log(checkout.lineItems); // Quantity of line item 'gid://shopify/Product/7857989384' updated to 2
});

Removing Line Items

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'; // ID of an existing checkout
const lineItemIdsToRemove = [
  'gid://shopify/CheckoutLineItem/194677729198640?checkout=e3bd71f7248c806f33725a53e33931ef'
];

// Remove an item from the checkout
client.checkout.removeLineItems(checkoutId, lineItemIdsToRemove).then((checkout) => {
  // Do something with the updated checkout
  console.log(checkout.lineItems); // Checkout with line item 'gid://shopify/CheckoutLineItem/194677729198640?checkout=e3bd71f7248c806f33725a53e33931ef' removed
});

Fetching a Checkout

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'

client.checkout.fetch(checkoutId).then((checkout) => {
  // Do something with the checkout
  console.log(checkout);
});

Adding a Discount

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'; // ID of an existing checkout
const discountCode = 'best-discount-ever';

// Add a discount code to the checkout
client.checkout.addDiscount(checkoutId, discountCode).then(checkout => {
  // Do something with the updated checkout
  console.log(checkout);
});

Removing a Discount

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'; // ID of an existing checkout

// Removes the applied discount from an existing checkout.
client.checkout.removeDiscount(checkoutId).then(checkout => {
  // Do something with the updated checkout
  console.log(checkout);
});

Updating a Shipping Address

const checkoutId = 'gid://shopify/Checkout/e3bd71f7248c806f33725a53e33931ef?key=47092e448529068d1be52e5051603af8'; // ID of an existing checkout

const shippingAddress = {
   address1: 'Chestnut Street 92',
   address2: 'Apartment 2',
   city: 'Louisville',
   company: null,
   country: 'United States',
   firstName: 'Bob',
   lastName: 'Norman',
   phone: '555-625-1199',
   province: 'Kentucky',
   zip: '40202'
 };

// Update the shipping address for an existing checkout.
client.checkout.updateShippingAddress(checkoutId, shippingAddress).then(checkout => {
  // Do something with the updated checkout
});

Completing a checkout

The simplest way to complete a checkout is to use the webUrl property that is returned when creating a checkout. This URL redirects the customer to Shopify's online checkout to complete the purchase.

Expanding the SDK

Not all fields that are available on the Storefront API are exposed through the SDK. If you use the unoptimized version of the SDK, you can easily build your own queries. In order to do this, use the UMD Unoptimized build.

Initializing the Client

// fetch the large, unoptimized version of the SDK
import Client from 'shopify-buy/index.unoptimized.umd';

const client = Client.buildClient({
  domain: 'your-shop-name.myshopify.com',
  storefrontAccessToken: 'your-storefront-access-token'
});

Fetching Products

// Build a custom products query using the unoptimized version of the SDK
const productsQuery = client.graphQLClient.query((root) => {
  root.addConnection('products', {args: {first: 10}}, (product) => {
    product.add('title');
    product.add('tags');// Add fields to be returned
  });
});

// Call the send method with the custom products query
client.graphQLClient.send(productsQuery).then(({model, data}) => {
  // Do something with the products
  console.log(model);
});

Example Apps

For more complete examples of using JS Buy SDK, check out our storefront-api-examples project. There are JS Buy SDK specific example apps in Node, Ember, and React. You can use these examples as a guideline for creating your own custom storefront.

Documentation

Contributing

For help on setting up the repo locally, building, testing, and contributing please see CONTRIBUTING.md.

Code of Conduct

All developers who wish to contribute through code or issues, take a look at the CODE_OF_CONDUCT.md.

License

MIT, see LICENSE.md for details.

js-buy-sdk's People

Contributors

abishekrsrikaanth avatar agos avatar andrewjtech123 avatar byroot avatar cursedcoder avatar glumb avatar gregdodd avatar harisaurus avatar ilievskizoran avatar itsdarrylnorris avatar jamiemtdwyer avatar jmignac avatar jzjiang avatar lyninx avatar melissaluu avatar mikkoh avatar minasmart avatar rebeccajfriedman avatar richgilbank avatar ryanbrushett avatar sbfaulkner avatar shopify-services avatar stefanslehta avatar stoufa88 avatar swalkinshaw avatar tanema avatar tessalt avatar tristan-potter avatar wvanbergen avatar yomexzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-buy-sdk's Issues

Setting "Continue Shopping" button via js-buy-sdk?

If you make an order via a shopify store, when you complete checkout there is a "Continue Shopping" button that takes you back to the storefront.

If you make an order that was created via the js-buy-sdk, this button is not shown. Is it possible to somehow set a value for this button and have it be shown? It would be good to be able to provide a link back to my shop.

Thanks!

postinstall script exhausts the CPU and eventually fails on Windows 10

Trying to install shopify-buy on a Windows 10 PC straight from the Github repo (f085e51)

npm install https://github.com/Shopify/js-buy-sdk --save

When the postinstall script starts running, massive amounts of CPU processing power and memory start to get used:

image

and eventually the script fails with this:

> ./scripts/postinstall

'.' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "https://github.com/Shopify/js-buy-sdk" "--save"
npm ERR! node v5.1.0
npm ERR! npm  v3.3.12
npm ERR! code ELIFECYCLE

npm ERR! [email protected] postinstall: `./scripts/postinstall`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script './scripts/postinstall'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the shopify-buy package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ./scripts/postinstall
npm ERR! You can get their info via:
npm ERR!     npm owner ls shopify-buy
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     D:\foo\npm-debug.log

Occurs on both cmd.exe and Git Bash.

Unable to initialise cart with variants. Documentation example not working.

Hi, I'm following official documentation from Javascript Buy SDK Guide - initialising cart with variants in fact does nothing for me, apart from creating an empty cart:

//these are actual products
var productId = 5863604999;
var variantId = 18525309447;

//code from the docs: http://shopify.github.io/js-buy-sdk/guide/
shopClient.createCart({id: variantId, quantity: 1}).then(function (cart) {
    console.log('CREATED CART:', cart.lineItems.length); //0
});


//doing it like this doesn't help either
shopClient.fetchProduct(productId).then(function (product) {
    shopClient.createCart({id: product.selectedVariant.id, quantity: 1}).then(function (cart) {
        console.log('CREATED CART:', cart.lineItems.length); //0
    });
 });

using: shopify-buy.polyfilled.globals.min.js

[DOC] Document supported node and npm versions.

Currently, node 5.x with npm 3 work.

  • Figure out what's currently supported.
  • Determine effort to extend support back to v0.12.x + NPM 2.
  • Document support and usage as an npm package in gh-pages.

[docs] Switch between versions

Currently the docs are independent of the lib version - we should be able to switch between versions and display the docs from each one.

[FEATURE] Asset license

Assets are distributed as minified and non-minified js file without any preamble. We should be prepending the LICENSE file to the assets that we distribute.

Thanks for bringing it up @t-kelly!

Multi Variant Issue.

Hi,

I'm currently testing the Buy SDK on a local machine.

I've installed it and ran on localhost:4200 as advised. and then standard cart example works fine.

When i have updated the api key and the shop domain and the product in the fetchProduct that loads the correct product details.

The Issue:

Our product has 3 variants (size name, product size, box size) which using the standard cart example loops through the variants and pulls in the 3 select drop downs.

But now only the default loaded selection works. Even if i choose the specific valid options on the other options it causes an error in console.

[Error] TypeError: undefined is not an object (evaluating 'this.selectedVariant.image')
get (shopify-buy.polyfilled.globals.js:3545)
(anonymous function) (index.js:132)
dispatch (jquery-2.2.1.min.js:3:7522)
handle (jquery-2.2.1.min.js:3:5603)
[Error] Error: Invalid option selection for Matress dimensions.
set (shopify-buy.polyfilled.globals.js:3612)
(anonymous function) (index.js:129)
dispatch (jquery-2.2.1.min.js:3:7522)
handle (jquery-2.2.1.min.js:3:5603)
[Error] TypeError: undefined is not an object (evaluating 'product.selectedVariant.id')
buyButtonClickHandler (index.js:168)
dispatch (jquery-2.2.1.min.js:3:7522)
handle (jquery-2.2.1.min.js:3:5603)
[Error] Error: Invalid option selection for Box dimensions.
set (shopify-buy.polyfilled.globals.js:3612)
(anonymous function) (index.js:129)
dispatch (jquery-2.2.1.min.js:3:7522)
handle (jquery-2.2.1.min.js:3:5603)
[Error] TypeError: undefined is not an object (evaluating 'product.selectedVariant.id')
buyButtonClickHandler (index.js:168)
dispatch (jquery-2.2.1.min.js:3:7522)
handle (jquery-2.2.1.min.js:3:5603)

SO i tried to then only grab the first Variant row. (size name) as this would the preferred option for a user to select their option.

so Line 60 on index.js in the cart example i changed

    return elements;

to

     return elements[0];

This then only returns the one select drop down as required, although it still doesn't update the product details as required with the same errors.

Does the code need updating to account for the 3 variants originally? is this a bug?

Confusing example for addVariants in documentation

The example for calling the addVariants method shows an object with an ID and a quantity.
screen shot 2016-05-13 at 12 30 46 pm
However, the parameters for the item object state that you must pass a 'variant' and a 'quantity'.
screen shot 2016-05-13 at 12 30 56 pm
Maybe it's just me, but I found this really confusing. At first I thought I was supposed to pass the ID of the product. Then I thought it was the variant ID. Eventually I realized that I needed to pass the selectedVariant object, so now I have it working.

[FEATURE] Run node tests

Right now, all of our tests are browser based, but this package is isomorphic. We should run some, if not all tests against node as well, to validate that the work we're doing doesn't blow up in node.

  • See if it's possible to run our existing test suite in node. This would require some proxying of localStorage and browser APIs.
  • Add node specific tests.
  • Run tests in CI

docs

  • link to docs for getting API key and channel ID from admin
  • link to shopify docs for admin stuff
  • link to NPM

can't get createCart() to work

Can't figure this out. (Most of the below code is for test purposes)

Fetching all products works: (The reason I am showing the working code is so you can see everything else is right, the cart route immediately follows the products route.

myRouter.route('/products')
  .get(function(req, res){
    shopClient.fetchQueryProducts({collection_id: 233148358})
      .then(function (product) {
         console.log(product);
      })
      .catch(function () {
        console.log('Request failed');
      })
});

The following to createCart and log the cart ID does not work.

myRouter.route('/cart').get(function(req, res){
  shopClient.createCart()
    .then(function (newCart) {
      console.log(newCart.id);
  })
  .catch(function () {
    console.log('Request failed');
  })
});

npm install shopify-buy fails

I have an issue installing the dependency in my project, it is related to the postinstall script of the library.
I think that the issue could be somehow related to babel version.

To reproduce it:
git clone https://github.com/anorudes/redux-easy-boilerplate.git
npm install
(sorry for a lot of dependecies) and then
npm install shopify-buy

you will get

  • export BROCCOLI_ENV=production
  • BROCCOLI_ENV=production
  • '[' -d dist ']'
  • broccoli build dist
    File: ajax.js
    ReferenceError: [BABEL] ajax.js: Unknown option: /PATHTOFILE/redux-easy-boilerplate/.babelrc.presets

Buy Button Customization

We would like to understand if we can fully customize the new Buy Buttons to function like the following link? https://www.wickedgoodcupcakes.com/

We want the customer to be able to choose the quantity of each product from the "collection" page, and we would like for them to have to buy a minimum number and maximum number of products. The flow would follow this exactly...we believe the new buy button would be the best way to achieve this. Would love some feedback if this is possible...

  1.  Home page.  Click on shop our cupcakes from the selection of categories on the left
    
  2.  Select a collection to buy, clicking on the picture or buy now button
    
  3.  Select the individual flavors that make up the X pack (X = 2 or 4 or 6).  The page automatically indicates when a sufficient quantity has been selected and provides the “Add to cart” button
    
  4.  Immediately asked for zip code
    
  5.  Immediately sent to form for shipping info and calendar for delivery date
    
  6.  Shipping details confirmation page
    
  7.  Shopping cart confirmation page with “Checkout” button
    
  8.  Billing information page
    
  9.  Abandoned process here, but you see the flow
    

Multiple Buy Buttons on a page?

Hey guys,

Trying to set up two different buy buttons on the same page with different products that add variants to the same cart. I was a bit surprised that the cart example didn't do this. Is there an example anywhere of how to do this?

Redirect to cart instead of checkout

Is there a way that I can generate a URL to the cart instead of the checkout? It looks like you can do this with the embedded buy button, but I don't see a way to do this with the Buy SDK.

The reason that I need to do this is that our store's cart page adds tracking as well as custom properties and attributes to our products before going to checkout. In the future we'll be looking at a better way of doing this so that we can send users straight to checkout. But for the time being it would be great to be able to generate a cart URL with products added from the Buy SDK.

Collects

The ability to retrieve collection and product collect data using the SDK would be really helpful. For my project I had to display collections in a custom sort order, which is only possible if you can get the collect data — GET /admin/collects.json?collection_id={id} in the Shopify API.

On the product detail page I needed to show related products, which meant I needed to know what collections the product was in — GET /admin/collects.json?product_id={id}.

Custom line item attributes

Is there any way to pass custom line item attributes, like we can pass attributes array in query when using permalinks?

Line Item Properties to Cart

As per a discussion I had with the team at Unite-- I know this is coming, but this will help our team know when the update has been pushed.

Thanks!

Image sizes

Images returned from the API are the raw image size uploaded to Shopify, i.e.
https://cdn.shopify.com/s/files/1/1015/1595/products/blackhelmet_store.png?v=1446233645

We should be able to return these in the various sizes Shopify produces, which requires adding a suffix to the file name matching these sizes.

i.e. instead of product.selectedVariantImage.src, maybe product.selectedVariantImage('thumb')?

@minasmart @tessalt @harismahmood89

v0.2.0 punch list

  • As a quick stopgap, provide a convenience method to fetch the most recent cart if it exists, or create one. client.fetchRecentCart() -> Promise | CartModel
  • Allow full domains, over just myshopify domains. Going forward we will be supporting different TLDs.
  • cart.lineItems should be list of class instances, rather than a regular hash representation. Underscores should go away.
  • Add cart.lineItemCount for total number of items in cart, not just lineItems.length (Inspired by #57 and https://github.com/Shopify/js-buy-sdk/pull/57/files#diff-2252a2513e98df574dd8383c6bbfc5dbR242)
  • Images sizes (see #10)
  • Safely handle no product images. Currently, things fail out on IE9 when there are no images.
  • Add Version Header to requests
  • Add version mark to artifact.
  • Support line item properties

@alexaitken, @richgilbank, @tessalt, @harismahmood89: If you know of things that should be changed going forward please add them here.

Error in IE when accessing selectedVariant.price

When attempting to access a property on a selectedVariant before selectedVariant has ever ben accessed, shopify-buy throws error Invalid option selection for storage.

Unhandled rejection Error: Invalid option selection for storage.
   at selected.set (http://website/shopify/shopify-buy.globals.js:1590:11)
   at constructor (http://website/shopify/shopify-buy.globals.js:1544:7)
   at superWrapper (http://website/shopify/shopify-buy.globals.js:698:7)
   at Anonymous function (http://website/shopify/shopify-buy.globals.js:1454:11)
   at options.get (http://website/shopify/shopify-buy.globals.js:1439:9)
   at selections.get (http://website/shopify/shopify-buy.globals.js:1489:9

I can reproduce this by simply running:

console.log(product.selectedVariant.price);

I can work around this by accessing selectedVariant before any properties on the variant:

product.selectedVariant;
console.log(product.selectedVariant.price);

This is reproducable in IE11 and 10.

Edit: I can no longer work around it by accessing selectedVariant first.

[BUG] npm install fails

Trying to install from npm and getting lots of exceptions and deprecated warnings.

npm WARN package.json [email protected] No repository field.
npm WARN deprecated [email protected]: socket.io-pure is no longer maintained as the original socket.io removed all native dependencies. Please use the original.
npm WARN deprecated [email protected]: lodash@<3.0.0 is no longer maintained. Upgrade to lodash@^4.0.0.
npm WARN deprecated [email protected]: engine.io-purce is no longer maintained as the original engine.io removed all native dependencies. Please use the original.
npm WARN deprecated [email protected]: socket.io-client-pure is no longer maintained as the original socket.io removed all native dependencies. Please use the original.
npm WARN deprecated [email protected]: ws-pure is no longer maintained as the original ws removed all native dependencies. Please use the original ws.
npm WARN deprecated [email protected]: engine-io-client-pure is no longer maintained as the original engine-io-client removed all native dependencies. Please use the original.

and then finally dies with:

.../node_modules/shopify-buy/build-lib/lib.js:5
const funnel = require('broccoli-funnel');
^^^^^
SyntaxError: Use of const in strict mode.
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (.../node_modules/shopify-buy/Brocfile.js:16:12)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)

options/variants convenience methods

After using the SDK for hack days, we ended up having to add the same couple methods to each implementation to enable option and variant selection:

build tree for generation of options selectors:

https://github.com/Shopify/tobuymvc/blob/master/examples/vanillajs/src/scripts/app.js#L204
combines variants and options arrays to associate a variants option_values with the matching option items, to enable select menus like:

<label>Color</color>
<select name="option_id">
  <option value="Green">Green</option>
  <option value="Blue">Blue</option>
</select>
<label>Size</label>
<select name="option_id">
  <option value="large">large</option
</select>

get variant for selected options

https://github.com/Shopify/tobuymvc/blob/master/examples/vanillajs/src/scripts/app.js#L251
Given selected or default options, find the variant that satisfies these options.

@Shopify/buy-button

Question: Can rely on 'attrs'?

(Is this the right place for discussion and questions?)
I want to display the product description after fetching it.
I can see the description is only available under the attrs property of the product model.
Can I rely on this API or is it considered internal?

What is the best practice here? (I can see not reference to the attrs property in the docs.)

Thanks!

[INVESTIGATE] jsdoc vs yuidoc

@m-ux has been looking into automatic doc generation solutions and had some good arguments for jsdoc over yuidoc. What was the argument for yuidoc? If it's related to the website it generates, we can probably build something better than either just using the raw data from JSON. @minasmart @richgilbank

Typos

On the Getting Started page

  • The last list item "generate a checkout URL for a single product or an entire cart" should end with a .
  • "You will need your myshopify.com domain, API key, and channelId" => no space in channelId
  • "Note: You will need to publish the product/collection you wish to interact with to the “Buy Button” channel in Shopify" is missing a period. Also "publish the product/collection" should link to the docs.shopify.com link about that task. However it looks like that might have been lost during our migration, I'll get someone to reproduce it. Here's the link for publishing collections

On the Guide page

  • "Take a look at the examples" is missing punctuation. A good ol . should do.
  • "Note: The calls to both shopClient.fetchProduct and shopClient.create are a..." The word Note should not be italicized here.
  • "and synchronize this cart with Shopify to obtain an accurate checkout link." Synchronize should be synchronizing for parallel structure.
  • "Note: cart is modified by calling addVariants" - Note should not be italicized
  • "Note: Cart item IDs are strings, not integers" - Note should not be italicized
  • "A products options are accessed through product.options" products should be product's
  • "accessed through product.options, each option has a values " - should be a full stop after product.options, new sentence beginning with "Each option..."
  • "you may also wish to" => "you can also use buttons or..."
  • "we will need to set the selected property for that option" => "you will need to..."
  • "remember to use the selectedVariant ID" - how come? Should we explain the rationale here?

How to add multiple variants to cart with cart.addVariants ?

What would be the best way of adding multiple items to cart at once?
Say we have a list (length may vary):

var addUs = [{quantity: 1, variant: superWrapper...}, {quantity: 1, variant: superWrapper...}]

Looking at the cart.addVariants method documentation, it states that it accepts variable number of arguments. It would be nice if we could unpack that list into function arguments, but since this is javascript, I'm not sure that is possible.

docs font weight

I'm finding courier new really tough to read in the docs because it's so thin. Shopify docs uses a stack of Menlo, Monaco, Consolas, "Lucida Console", monospace which seems much easier to read. @d10k @harismahmood89

[DOCS] Document listings queries

For methods like fetchQueryProducts, we need to document what queries are supported. From poking around a bit, it seems a little inconsistent - collection_id: ... and product_ids: [...] work, but not handle: '...', title: '...', etc.

@awd, is there any public documentation for these queries? Also, given it's a query, we should probably be returning an empty object when no resources match, instead of the full set of products. Any reason to return everything?

Docs Notes For Launch

Getting Started

Guide

  • Add link to ShopClient instructions from Getting Started

Expose product descriptions under `bodyHtml`

We left this out from the product model. We should be proxying it so it's available as product.bodyHtml so developers don't have to rely on internal state (product.attrs.body_html).

Original issue: #100

Build `lib` directory on pre-publish, not post-install.

This would allow us to have separate dev dependencies and runtime dependencies. It would also really clean up the install process.

We will, however, need to document that installing the package through a git ref won't work fully, since lib won't get built.

If anyone has any recommendations on a nice way to make both things work, please comment!

[RFC] Cart Interface

Preface

Hey all! This issue exists to get your input on some interface design for the
js-buy-sdk. I'm asking y'all since some of you are likely to be early SDK
consumers. First, I'd like to mention that the code in this repo is still under
active development and is a bit of a prototype. Right now it supports fetching
from the publications API and fetching and persisting to the checkouts anywhere
API (TBD). This has been done in an extensible way so that at some point in the
future other data types or APIs may integrated if that serves a need.

This SDK exists as the basis for moving Buy Button away from iframes and into a
more customizable and usable open source SDK. Buy button will be replatformed
onto this SDK.

If you're not familiar with this project, what purpose it serves, and the
motivations behind it, please checkout out:

NOTE: Project name and exported global are still TBD.

User interaction

The following are some examples of interactions around adding items to a cart.

Functional modeling

const client = ShopifyBuy.createClient({ ... });
const $buyButton = $('#buy-button');

let cart = client.createCart();

client.fetchProduct(123).then(product => {

  setUpUIForVariant(product.variants[1]);

  $buyButton.on('click', () => {
    shopClient.addVariantToCart(cart, { id: product.variants[1].id, quantity: 1 });
    shopClient.save(cart).then(updateCart => {
      cart = updateCart;
    });
  });
});

In this example, mutator functions are attached to the shopClient, which is
what's responsible for interacting with a specific API.

In this case addVariantToCart could just augments the carts state. Persistence
is handled in a separate call. Another option would be to have
addVariantToCart make the call to persist the cart, and return a promise that
resolves with the new cart. If it resolves a new cart, instead of a mutated cart
this eliminates the possibility of race conditions (checking cart state while
network requests are in flight could produce inconsistent or unreliable state).

OO Modelling

const client = ShopifyBuy.createClient({ ... });
const cart = client.createCart();
const $buyButton = $('#buy-button');

client.fetchProduct(123).then(product => {

  setUpUIForVariant(product.variants[1]);

  $buyButton.on('click', () => {
    cart.addVariant({ id: product.variants[1].id, quantity: 1 });
    cart.save();
  });
});

This approach implies that the existing cart would be altered by the call, and
necessitates more state management. Whether or not addVariant saves or we
require an explicit save call, this approach necessitates state management
(the cart would have to be marked as in-flight, and subsequent calls to save
would have to be queued after the initial save resolves). We could also just not
worry about race conditions and just assume last-write-wins and the carts
internal state will eventually resolve.

How do we represent the cart?

As shown above, we can use a factory method that can create a cart, that an SDK
consumer is responsible for maintaining.

An alternative would be to have a singleton cart, that's created, resolved, or
fetched:

shopClient.myCart().then(cart => {
  // Do some work with the cart
});

myCart would check for an instance attached to the cart client; failing that
it would check a cookie or local storage for a cart token, fetch the cart and
resolve; and failing that make a create call to the server and resolve the newly
created cart. I think this approach is pretty convenient, but it may be more
opinionated than what we want to build with this API.

Simpler use cases

In other cases where a cart object isn't necessary, we can create checkout
permalinks based on variants and quantities.

const client = ShopifyBuy.createClient({ ... });
const $buyButton = $('#buy-button');

client.fetchProduct(123).then(product => {

  setUpUIForVariant(product.variants[1]);

  $buyButton.on('click', () => {
    const checkout = window.open();

    const link = shopClient.checkoutPermalink([
      { id: product.variants[1], quantity: 1 }
    ]);

    checkout.location.href = link;
  });
});

In the case of buy button, this approach would work in some cases. Variant ID
and quantity would be pre-set by the buy-button builder, and the product fetch
would only be used to get product name, price and image to fill in the display.

Other recommendations!

I'm looking for all of your input so we can come up with a decent public-facing
API. The fundamentals for either of these approaches are built, it's just a
matter of wrapping them up in some convenience methods so nobody has to work
directly with hashes.

This is just the starting point of a discussion. All of your feedback questions
and proposed use-cases are welcomed.

I look forward to hearing from you all!

Safari private mode

Hi,

I have a very annoying issue with Safari in private (incognito) mode: it's impossible to add a product in the cart.
After testing, I found that the client.createCart() function is not working in the SDK (the client variable remains undefined), again only in Safari private mode. Did anyone have the same issue?

website: www.soundbrenner.com/shop

Thanks a lot!
Julien

Docs additions

  • Downloads page
    • Link to NPM
    • Link to main CDN package
    • List of alternative packages
    • Description of polyfills and when they're needed
  • Document browser support (IE9+)
  • Documentation pass (up-to-date API?)
  • Core concepts / understanding the API
    • Products, collections, variants, options, product listings, etc

@tessalt @minasmart

"Copy to clipboard" also copies "Copy to clipboard" to the clipboard

Something seems to be up with the "Copy to Cipboard" button on the Downloads page of the docs site - the first time I clicked it, the text I expected to be copied to my clipboard was, but "Copy to clipboard" (the button text) was also appended to it. I haven't been able to replicate since though, as the button doesn't seem to be having any affect whatsoever now (not copying), and there are no console errors logged.
¯\(ツ)/¯
Any ideas @harismahmood89?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.