Giter VIP home page Giter VIP logo

chec / commerce.js Goto Github PK

View Code? Open in Web Editor NEW
378.0 13.0 83.0 2.1 MB

Open source, JS eCommerce SDK for building headless, Jamstack applications. Build custom storefronts, carts, and checkouts in any frontend framework, platform, or device. Integrates with Stripe, Square, PayPal, Paymill and Razorpay with support for 135+ currencies.

Home Page: https://commercejs.com

License: BSD 3-Clause "New" or "Revised" License

JavaScript 100.00%
sdk ecommerce commercejs chec headless jamstack js open-source checkout commerce

commerce.js's People

Contributors

ahmadwaleed avatar amaau avatar amnahkhatun avatar anugya-gogoi avatar better-boy avatar daniloff200 avatar dependabot-preview[bot] avatar dependabot[bot] avatar dvnkshl avatar eufandem avatar fmendoza avatar guykh avatar hariom1625 avatar imagentleman avatar jaepass avatar john-raymon avatar karansinghbisht avatar kitfud avatar kvisca avatar mananchawla2005 avatar michizhou avatar notrab avatar paitoanderson avatar robbieaverill avatar sanket143 avatar sanketnaik99 avatar scopeynz avatar sinithh avatar sudiptog81 avatar vocalfan 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

commerce.js's Issues

Managed inventory not working

When you have your inventory as managed people can still buy as much as they want, the value just becomes negative

customer.getOrders Error 500

Hi,

When i call manually "https://api.chec.io//v1/customers/{customer_id}/orders" endpoint without params, i can get orders for my customer correctly.

But when i use commerce.customer.getOrders() method from commerce library i get an error 500.
I've seen that this method call the endpoint with parameters "?sortBy=created&sortDirection=desc". When i try to call the endpoint with that params in Postman i get the error 500.

So i guess there is a problem with the sort filter on this endpoint.

i'm using the "@chec/commerce.js": "^2.3.2"

Thanks

Prevent obviously unnecessary requests

Sometimes we know before we even make a request that there'll be a 422 response. For instance, if you ask for subdivisions without providing a country, you will always get a 422 from the API. We should catch this Commerce.js and prevent the extra API request.

Hacktoberfest -> Some errors in swag redeem form

hack

I noticed that the contributors can edit the number of bundles they can get while submitting the swag redeem form(I'm not sure if its purposeful ). Also once a form is submitted it is not locked for the next time. I was able to make a successful order even after doing it for more that twice. (That PR was invalid and still the order wasn't cancelled)

Now I'm resubmitting the form with the link of a merged PR.

Add error container for API response failures

Given the following example:

commerce.checkout.capture().error(error => this.handleError);

The error object looks like this (in the console):

error
Error: Request failed with status code 422
    at createError (bundle.js:1968)
    at settle (bundle.js:2214)
    at XMLHttpRequest.handleLoad (bundle.js:1481)

The network response is this:

{"error":{"type":"not_valid","message":"Requested quantity not available"},"status_code":422}

In order to get that message, you must use error.response.data.error.message (via Axios). This is a pretty verbose way to get the message from our response, which is a standardised structure from the API.

Perhaps we should wrap these errors in our own container class with easier access to the response data?

cc @chec/engineering

Adding a product with invalid variant option to cart returns 404 and generates a new cart

Commerce.js 2.0.1

  • Add a product to cart, or initialise a cart
  • Add a product to cart with an invalid variant ID or option ID

The response is:

{
  "error": {
    "type": "not_found",
    "message": "This product doesn't have this variant option."
  },
  "status_code":404
}

However since it returns a 404, it also regenerates the cart ID, meaning you lose everything in your cart.

Possible solutions:

  • Detect this response specifically in Commerce.js and do not regenerate the cart ID in this case
  • Change the API to return a 422 validation error instead of a 404 not found error

can't retrieve products after passing category_slug as additional parameter

steps to reproduce,
pass category slug as a additional parameter to retrieve some products but returns this error

error

and the code to reproduce this is,
const limit = 50; const categorySlug = 'men-sneakers'; commerce.products .list({ limit: limit, category_slug: categorySlug, }) .then((response) => response.data);

produces same result when passing category id instead of category slug

Ensure auto-deployments purge the CDN cache

We have auto-deployments when we push tags which is nice, but the CDN doesn't update without an explicit request to purge the file from the edges. There's probably some way to configure this in the AWS CLI that we use. I'm not sure if that will be compatible with the CDN provider we use, or whether we'll need to do something else.

[2.0] Cannot update item quantity in cart

Using the react-shoe-store and seeded products within it as an example here, adding a product to cart then trying to change its quantity doesn't actually update its quantity.

Make the cart lifetime configurable

It's currently hard coded in the carts.add() method as 30 days. This ideally should be an option in the Commerce constructor options:

new Commerce(key, true, {
  cartLifetime: 2, // days
});

customer.getOrders() Promise

When calling customer.getOrders() / customer.getOrder() I've noticed you get a bunch of the information regarding the request included instead of just the data prop.

Can I open a PR to fix or is this intended? I understand it would be a breaking change.

commerce.customer.getOrders()
  .then((response) => {
   console.log(response);
  });

Screen Shot 2021-06-08 at 10 31 16 AM

Be more declarative with adding products to the cart

Currently the API for adding products to cart is:

add(item = {
  id,
  quantity,
  variant,
});

Given the fact that carts and products share the quantity attribute, but they mean different things, I suggest we change it to be:

add(
  id,
  quantity = 1,
  variant = null
)

We should also try to extract the ID from the first argument if the whole product entry is passed. This would mean you can do:

const product = await products.get(productId);

cart.add(product)
// Or
cart.add(product.id)

Improve minification of dist file

The minification of the build files could be improved so it minifies more than it currently does. There are many empty lines and spaces, as well as non-uglified property and function names.

Fetching products by category_slug or category_id not working

Whenever I'm fetching the products by category_slug or category_id in next js then it's throwing an error.

This is the code that I've written

export const getStaticProps = async ({ params }) => {
	const { slug } = params;
	console.log(slug);
	const products = await commerce.products.list({ category_slug: slug });
	console.log(products);
	return {
		props: {
			products,
		},
	};
};

The error that I'm getting

{
  message: 'Unsuccessful response (422: Unprocessable Entity) received',
  statusCode: 422,
  statusText: 'Unprocessable Entity',
  data: {
    status_code: 422,
    error: {
      message: 'The given data was invalid.',
      type: 'unprocessable_entity',
      errors: [Object]
    }
  },
  originalError: Error: Request failed with status code 422
      at createError (E:\Web Development\Projects\Main Projects\startup\frontend\node_modules\axios\lib\core\createError.js:16:15)
      at settle (E:\Web Development\Projects\Main Projects\startup\frontend\node_modules\axios\lib\core\settle.js:17:12)
      at IncomingMessage.handleStreamEnd (E:\Web Development\Projects\Main Projects\startup\frontend\node_modules\axios\lib\adapters\http.js:260:11)
      at IncomingMessage.emit (events.js:214:15)
      at endReadableNT (_stream_readable.js:1178:12)
      at processTicksAndRejections (internal/process/task_queues.js:77:11) {
    config: {
      url: 'products',
      method: 'get',
      data: null,
      headers: [Object],
      params: [Object],
      baseURL: 'https://api.chec.io/v1/',
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 60000,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus]
    },
    request: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      connection: [TLSSocket],
      _header: 'GET /v1/products?category_slug=potrait HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'X-Authorization: <My Public Key>\r\n' +
        'X-Chec-Agent: commerce.js/v2\r\n' +
        'Content-Type: application/json\r\n' +
        'User-Agent: axios/0.21.1\r\n' +
        'Host: api.chec.io\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      path: '/v1/products?category_slug=potrait',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      _redirectable: [Writable],
      [Symbol(kNeedDrain)]: false,
      [Symbol(isCorked)]: false,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    response: {
      status: 422,
      statusText: 'Unprocessable Entity',
      headers: [Object],
      config: [Object],
      request: [ClientRequest],
      data: [Object]
    },
    isAxiosError: true,
    toJSON: [Function: toJSON]
  }
}

Console debugger: notes and improvements

The console debugger was piped over from CJS v1 to v2, but doesn't work as well as it probably used to for a few reasons:

  • Not all API responses provide the metadata necessary for the console debugger to show things
  • Browsers now have dark mode, CJS helper looks best in light mode
  • 422s cause uncaught promise exceptions in the console which pollutes the CJS debugger output

My suggestions would be that we remove debugger output from the API and move it entirely into Commerce.js. We know what all of the API calls are because we initiate them, and we know whether they were successful or not, because we can monitor the HTTP status code of each request. We should be able to achieve this with an Axios interceptor, or something similar.

I think the CJS helper should show successful requests as well as failures, at a quick test it looks like it's currently only showing some errors, but no successes (from adding to cart and completing a checkout, I didn't see any).

Custom meta fields

It would be really wonderful if you'd allow adding custom fields to objects like products and categories. A lot of shops (maybe most) could then use commerce.js on its own, without needing to sync it to another system.

We're using commercejs together with a whole custom backend, syncing products, categories and merchant info, and all because we couldn't add a few fields to a product.

Add helper to "carts" module for checking available stock level for a product

We have this helper function: https://commercejs.com/docs/api/#check-requested-quantity

It requires a checkout token ID to work, which means it can't be used before you get to the checkout.

If a developer wants to check the stock level when adding to cart, or async after doing so, they would have to fetch the product's data GET /v1/products/{id} just to get the stock level out of it, and have their own comparison logic.

We could make an equivalent of this method but in the carts namespace which won't require a checkout token.

cart.refresh() should return the cart, rather than the cart ID

Should we create a getter method within the root commerce.js class that proxies/returns the cart instance variable that's within the Features.Cart instance created within commerce.js that's assigned as this.cart?

A use-case is:
(two methods within a React.Component)

// retrieveCart
retrieveCart(){
    commerce.cart.retrieve().then(cart => {
      this.setState({
        cart
      })
    }).catch(error => console.log(error));
  }

// refreshes cart
refreshCart(){
    commerce.cart.refresh().then(resp => {
      this.retrieveCart() 
      // instead of invoking this.retrieveCart to retrieve the new/refreshed cart 
      // we should avoid an additional request (commerce.cart.retrieve internally invokes commerce.cart.request method, as does commerce.cart.refresh)
      // instead we can ref the cart object that's an  instance variable in commerce.cart (ex: commerce.cart.cart)
      // (it used to only have the cartId ex. commerce.cart.cartId)
      this.setState({
        cart: commerce.cart.cart
      })
    }).catch(error => console.log(error))
  }

The issue with this is that a developer won't know the cart instance variable exist within commerce.cart unless they debugged, or got into the source code. I think having a getter within the root commerce class like commerce.cartObject that returns the cart object instance variable living within commerce.cart as commerce.cart.cart.

Missing Customer Object

const commercejs = new CommerceSDK(commercejsAPIKEY, isDevelopmentEnvironment)

console.log(commercejs)

I get result:

cart: a {commerce: a, cartId: null}
categories: a {commerce: a}
checkout: Checkout {commerce: a}
consoleHelper: ƒ ()
merchants: a {commerce: a}
options: {version: "v1", url: "https://api.chec.io/", publicKey: "pk_xxxx", debug: true, eventCallback: ƒ}
products: a {commerce: a}
services: a {commerce: a}
storage: a {commerce: a}

There is no Customer Object, so I can't login or use others options ex. isLoggedIn()

Write a v1 to v2 migration guide, highlighting API changes such as cart.add

Should we maintain the same argument definition from v1 for the cart.add method?

I was trying to pin-point why the request to the cart endpoint, adding a product to the cart, was not providing the variant in the body.
This was because I was assuming the v2 cart.add still accepted a single argument as an object with id, quantity, and variant properties, however, now it's not an object but individual parameters.

add(productId, quantity = 1, variant = null) {

v1 cart.add looks like this
image

Typescript

Hi. Do you plan to release Typescript declarations for this library?

Add new methods for customers API support

The Chec API recently shipped support for some Customer APIs. Commerce.js is interested in the parts of these APIs that use a public API key, and allow the implementor to:

  • Initiate the login process as a customer
  • Exchange a temporary token for a customer JSON web token
  • List orders (as a customer) using the JWT
  • Get order (as a customer) using the JWT

We'll also need a method of storing the customer's JWT somehow so it's stored securely and available for Commerce.js to use on the customer's behalf.

Expose more information in console debugger when 422 errors are encountered

Example: chec/cli#39. The console debugger outputs the primary error message from this response, which is "the given data was invalid". There are nested messages which are specific errors underneath this. We could display them in a simple list in the console to help developers to find out what their problems are without having to examine the full response body.

[DOCUMENTATION] Improve documentation for pagination

The API paginates products to 25 items per page by default. We should improve the documentation around pagination (maybe only for commerce.products.list) so that it's clearer what to do when your products go over more than one page.

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.