GithubHelp home page GithubHelp logo

swellstores / swell-js Goto Github PK

View Code? Open in Web Editor NEW
134.0 10.0 28.0 7.13 MB

JS library for building storefronts and checkouts with Swell ecommerce.

Home Page: https://swell.is

License: MIT License

JavaScript 99.60% CSS 0.10% HTML 0.30%
isomorphic ecommerce checkout storefront jamstack javascript

swell-js's People

Contributors

awwit avatar belphegorprime avatar bonofiglio avatar by-tim avatar ceceppa avatar dependabot[bot] avatar dimazhukovsky avatar dmitrijop avatar dmitry-vakulski-es avatar ericingram avatar greph avatar igoraugustynski avatar itzcrazykns avatar jdmathew avatar m59peacemaker avatar mustafaswell avatar papertokyo avatar robwalkerco avatar rodrigo-swell avatar rodrigoddalmeida avatar stafyniaksacha avatar swellmike avatar thmsmtylr avatar vmarkevich avatar vstudenichnik-insoft 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

swell-js's Issues

Require is not defined | Vite issue

I sadly stumble across an issue with Nuxt 3 and Vite, because "require" is not supported (Webpack only).

ReferenceError: require is not defined

And swell-js makes use of require for the isomorphic fetch package afaik.
As stated in this discussion: (nuxt/nuxt#12797)
is it possible to use import instead of require? :)

Custom_Fields not showing up Product.Variants

I added a New custom field "sort_order" under Product.Variants and its not being return with the other variant values.

{
  id: "61bda8f4eee7af013d7950e9"
  name: "large"
  option_value_ids: ['61bda2b02af2a172378242f1']
  price: 25.5
  stock_level: 0
  stock_status: "out_of_stock"
}

Bundle product details

bundle and bundle_items are not returned when requesting products list or product details.
Is there an expand value that could be used?

Problem with loading GLTF/GLB files within Next.js

Hi there!

Loving Swell so far! However, I ran into an issue when I created a new content field to a product.
I want to upload 3D models of some products and displays them, the uploading part goes fine, but the displaying is where the errors start.

I am pretty sure it's related to the CDN, as I've tried using different CDN's to display the same 3D model, and it shows up fine.
I am using Next.js v13.1.0, if that is any help.

If you have any insights into why this might happen, it would be an enormous help!

Getting full list of categories from a product record.

I'm trying to create breadcrumbs in my store by getting a list of categories from a product record, but only the top level category is returned in the query.

Im my specific example, my product is under Products > Parts > X-6. When I get the product with categories expanded, I'm only returned Products.

Is there a way to get the full category list when doing a product query? Or is there another method I can use to create breadcrumb links from a product?

Cannot create card token

const response = await swell.card.createToken({
  number: '4242 4242 4242 4242',
  exp_month: 1,
  exp_year: 2099,
  cvc: 321,
  // Note: some payment gateways may require a Swell `account_id` and `billing` for card verification (Braintree)
  account_id: '5c15505200c7d14d851e510f',
  billing: {
    address1: '1 Main Dr.',
    zip: 90210
    // Other standard billing fields optional
  }
})

how should I get the number, exp_month, exp_year and cvc from the form input?

Thanks

Custom filed type boolean with wrong response

I created a custom filed to my Products named is_new
Using the swell console the field is false, like set in the swell dashboard. But using swell.js the value is true.

Response exemple from the consoles

From https://<-name->.swell.store/admin/console?get/products

"is_new": false,
"id": "60f6885f9fd1616cab3d1aad",

And from my basic react app

id: "60f6885f9fd1616cab3d1aad"
is_new: true

Interface AddressSnake is missing account_address_id

In your types in SwellJs you have Interface AddressSnake, and this is called for the shipping object in AccountSnake. However, shipping object on the account is allowed to have a field called account_address_id, but if you attempt to do that, you get an TS error. You should add: account_address_id?:string to the AddressSnake. Thanks.

Error when tokenizing Stripe element card

I've posted this at the swell discussion, but I think this should come here instead.

When running the following code, I've ran into some error "Missing value for stripe.confirmCardSetup intent secret: value should be a client_secret string."

            await swell.payment.tokenize({
                card: {
                    onError: (err) => {
                        // inform the customer there was an error
                        console.log({ err });
                    },
                    onSuccess: async () => {
                        console.log("success");
                        //finally submit the form
                    },
                },
            });

Upon more debugging and testing, i found that the particular confirmCardSetup function does not take into consideration of camelCase response that causes this.

image


Also, I did some patch locally and it works perfectly on camelCase. However, it doesn't seems to be attaching the tokenized card to the cart session as per the doc.

Upon checking the responses, I found a couple of things that are causing it, but i am not sure if it was intended or not.

Part 1: If capture amount is less than 1, then update the tokenized to the billing detail. (Obviously my capture amount is 52, and it wont be updated)

Quoting the doc: In order to tokenize successfully, there must be a product in the cart with a grand total greater than 1.

Screenshot 2023-01-03 at 11 27 35 PM

Part 2: If the intent_status is requires_confirmation, then it should confirm the card with Stripe and update the billing detail. (Obviously the response that I got back is requires_capture, and it never get updates)
Screenshot 2023-01-03 at 11 32 31 PM

Up to this point the tokenization was a success but the cart session did not get any payment information attached. Wondering if it will only be attached automatically after submitting the order?

Filter via $filters for attributes doesn't work for frontend sdk

I've been messing my brain around filtering products on client side by using swell-js sdk but it doesn't work.

const productsList = await swell.products.list({
    $filters: {
       featured_products: 'yes',
    },
  });

Somehow a different workaround that I found over internet is working -

const productsList = await swell.products.list({
    'attributes.featured_products': 'yes',
});

Is it a bug or is the docs out of sync for front-end APIs ?
Swell version - "swell-js": "^3.17.4",

Filter a product by nested object array values

I have a products like this:

[
  {
    name: 'Product 1',
    attributes: {
      width: '15',
      minimum_required_images: '1',
      height: '20',
      channels: ['web', 'mobile']
    }
  },
    {
    name: 'Product 2',
    attributes: {
      width: '25',
      minimum_required_images: '2',
      height: '30',
      channels: ['mobile']
    },
  }
]

I want to filter it by a channel or list of channels,
for ex. I want to list only products with channels : ['mobile']

how should I achieve this?

Not getting category_index property in the products list on frontend

I am fetching the products list by using swell front-end APIs - https://developers.swell.is/frontend-api/products

In the developer console, I checked that product model contains a category_index key which contains a list of category ids. I was getting this field earlier, but since yesterday, the frontend-API has been returning my error saying that I don't have permission to expand this field.

I'm attaching console error log and my code that I've been using below.

image

image

CJS in swell-esm.js

Could you please transpile the esm module without require so we can use swell-client with Vite for example?

try{var t=n&&n.require&&n.require("util").types

Cant be able to fetch the only fields of products.

Hi there, If I want to only fetch the required fields then there is no documentation of how we can implement this on swell-js documentation.
https://{{swell-id}}:{{publicKey}}@api.swell.store/products?fields=slug

I'm using this custom way to get the only fields
but This npm package is not providing any way to fetch the selected fields

API: Unable to create address.

Issue description

Unable to create a new address via swell.account.createAddress.

Steps to reproduce the issue

  1. Call using data from https://swell.store/docs/js/account/#create-an-address.
await swell.account.createAddress({
  name: "Julia Sanchez",
  address1: "Apartment 16B",
  address2: "2602 Pinewood Drive",
  city: "Jacksonville",
  state: "FL",
  zip: "32216",
  country: "United States",
  phone: "904-504-4760"
});
  1. Log result.

What's the expected result?

  • The object of the newly created address.

What's the actual result?

  • Logged:
errors: {
  address1: {message: "Required", code: "REQUIRED"}
  country: {message: "Exceeds max length (2)", code: "LENGTH", length: 2} 
}

type issue in products.list productQuery type

This is shown as a type error, however it is a valid API call:

// returns matching product results
const productResponse = await swell.products.list({
	id: { $in: productIds } // productIds is an array of IDs
})

image

And trying to do this same thing with the "where" flag actually doesn't properly return any products.

// this doesn't work even though it seems like it should (returns no results)
const productResponse = await swell.products.list({
	where: { id: { $in: productIds } }
})

Expose API.stripe publicly

Rationale: use stripe methods that are not proxied / facaded by Swell (e.g elements to specify custom font face for credit card inputs).

Cannot run/build the app (using Angular)

I am building a store and using swell-js 3.19.6 and I have to modify the following SnakeToCamelCase type in node_modules/swell-js/types/index.js to get the app running locally:

Modified from:

type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
  ? `${T}${Capitalize<SnakeToCamelCase<U>>}`
  : S;

to:

export type SnakeToCamelCase<S extends any> = S extends `${infer T}_${infer U}`
  ? `${T}${Capitalize<SnakeToCamelCase<U>>}`
  : S;

but when I try to build using netlify I cannot modify the code in the node_modules and it fails the build with the following error:

3:00:40 PM: Error: node_modules/swell-js/types/account/camel.d.ts:1:10 - error TS2459: Module '".."' declares 'SnakeToCamelCase' locally, but it is not exported.
3:00:40 PM: 
3:00:40 PM: 1 import { SnakeToCamelCase } from '..';
3:00:40 PM:            ~~~~~~~~~~~~~~~~
3:00:40 PM: 
3:00:40 PM:   node_modules/swell-js/types/index.d.ts:54:6
3:00:40 PM:     54 type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
3:00:40 PM:             ~~~~~~~~~~~~~~~~
3:00:40 PM:     'SnakeToCamelCase' is declared here.
3:00:40 PM: 
3:00:40 PM: 
3:00:40 PM: Error: node_modules/swell-js/types/attribute/camel.d.ts:1:10 - error TS2459: Module '".."' declares 'SnakeToCamelCase' locally, but it is not exported.
3:00:40 PM: 
3:00:40 PM: 1 import { SnakeToCamelCase } from '..';
3:00:40 PM:            ~~~~~~~~~~~~~~~~
3:00:40 PM: 
3:00:40 PM:   node_modules/swell-js/types/index.d.ts:54:6
3:00:40 PM:     54 type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
3:00:40 PM:             ~~~~~~~~~~~~~~~~
3:00:40 PM:     'SnakeToCamelCase' is declared here.
3:00:40 PM: 
3:00:40 PM: 
3:00:40 PM: Error: node_modules/swell-js/types/card/camel.d.ts:1:10 - error TS2459: Module '".."' declares 'SnakeToCamelCase' locally, but it is not exported.
3:00:40 PM: 
3:00:40 PM: 1 import { SnakeToCamelCase } from '..';

any help? this is my init function:

    swell.init(environment.swell.storeId, environment.swell.publicApi, {
      useCamelCase: false,
    });

`cart.addItem` mutates input options objects

The key name is replaced with id. I would be on the lookout for other such mutations. This is a source of devastating and very difficult to track down bugs.

Example:

const item = { product_id, quantity: 1, options: [ { name: 'Size', value: '1 cup' } ] }
swell.cart.addItem(item)
item.options[0] // => { id: 'Size', value: '1 cup' }

I use the item object for more than just the call to addItem, and having it mutated is a big issue. I have to pass swell a copy to avoid this.

Error using the library

In our team, we have an enterprise Swell account and we tried to install this package and use it but after following the first step we are getting a CORS error.

Screen Shot 2020-03-04 at 00 25 34

This is the code we want to test:

Screen Shot 2020-03-04 at 00 26 04

We also try with a plugin to disable CORS and we get the next error:

Screen Shot 2020-03-04 at 00 27 49

That error does not make sense as we have that configured.

Product without all fields

Hi. I use your library, but product doesn't have fields from swell. I don't have in response 'tags' field (default) and my custom fields from models.

Query:

const query = await swell.products.list({
    limit: 25,
    page: 1
})
console.log(query['results']);

Response:

  {
    id: '61a0adf66802371e0eaa37a5',
    content: {
      product_benefits: [Array],
      enable_quantity: true,
      max_quantity: 99
    },
    currency: 'PLN',
    description: 'skład<br>',
    bundle: null,
    images: [ [Object] ],
    name: 'Power of nature',
    options: [],
    price: 60,
    purchase_options: { subscription: [Object] },
    sku: null,
    slug: 'power-of-nature',
    stock_status: null,
    stock_tracking: false,
    attributes: {},
    meta_title: null,
    meta_description: null,
    home: true
  }

Is it possible to make a 'OR' request with $filter?

I have products like this:

[
  {
    name: 'Product 1',
    attributes: {
      width: '15',
      height: '20',
      channels: ['web', 'mobile']
    }
  },
    {
    name: 'Product 2',
    attributes: {
      width: '25',
      height: '30',
    },
  },
  {
    name: 'Product 3',
    attributes: {
      width: '10',
      height: '10',
      channels: ['web']
    }
  },
]

I want to filter products without the channels field OR a specified channels.
In server side I can achieve this with swell-node like this:

await swell.get('/products', {
  limit: 50,
  where: {
    active: true,
    $or: [
      { 'attributes.channels': { $exists: false } }, // if no channels defined, take the product for everyone
      { 'attributes.channels': { $in: ['web'] } }, // for specified channels
    ],
  },
});

Is it possible to make this OR request with swell-js?

Allow to provide custom setCookie / getCookie methods

Hi there!

It would be great to have a way to provide our own setCookie / getCookie method, so we can customize domain, expiration, or handle SSR on our own.

Here would be the usage:

import swell from 'swell-js'

swell.init('storeId', 'publicKey', {
  // ...
  setCookie: (name: string, value: string) => {
    // ...
  },
  getCookie: (name: string) => {
    // ...
    return 'value'
  },
})

I've made it working using pnpm (with patch/patch-commit) and [email protected] with this patch:

diff --git a/dist/api-bb3bfec8.js b/dist/api-bb3bfec8.js
index f5c5925e8fb76d2e8232a97ae3507ad6ae467649..0acb726cefb7f9fe0c6ad742bc0a8fc2188f2e86 100644
--- a/dist/api-bb3bfec8.js
+++ b/dist/api-bb3bfec8.js
@@ -43,6 +43,8 @@ const api = {
     options.locale = opt.locale;
     options.currency = opt.currency;
     options.api = api;
+    options.getCookie = opt.getCookie || getCookie;
+    options.setCookie = opt.setCookie || setCookie;
     setOptions(options);
   },
 
@@ -108,9 +110,9 @@ async function request(
     ...opt,
   };
 
-  const session = allOptions.session || getCookie('swell-session');
-  const locale = allOptions.locale || getCookie('swell-locale');
-  const currency = allOptions.currency || getCookie('swell-currency');
+  const session = allOptions.session || allOptions.getCookie('swell-session');
+  const locale = allOptions.locale || allOptions.getCookie('swell-locale');
+  const currency = allOptions.currency || allOptions.getCookie('swell-currency');
 
   const baseUrl = `${allOptions.url}${allOptions.base || ''}/api`;
   const reqMethod = String(method).toLowerCase();
@@ -167,7 +169,7 @@ async function request(
   const responseSession = response.headers.get('X-Session');
 
   if (typeof responseSession === 'string' && session !== responseSession) {
-    setCookie('swell-session', responseSession);
+    allOptions.setCookie('swell-session', responseSession);
   }
 
   const result = await response.json();
diff --git a/dist/currency-85151e0d.js b/dist/currency-85151e0d.js
index a738ee61537a2c8c297479da8104b95714bc1e46..48b0006bf8afbc70bc3045fd093c6f7b46d36af7 100644
--- a/dist/currency-85151e0d.js
+++ b/dist/currency-85151e0d.js
@@ -2,7 +2,6 @@ import 'qs';
 import { f as find, g as get, r as round } from './index-bee7164f.js';
 import 'deepmerge';
 import 'fast-case';
-import { g as getCookie, s as setCookie } from './cookie-dff5d694.js';
 
 const FORMATTERS = {};
 
@@ -25,7 +24,7 @@ function methods(request, opt) {
     selected() {
       if (!this.code) {
         this.set(
-          getCookie('swell-currency') || opt.api.settings.get('store.currency'),
+          opt.getCookie('swell-currency') || opt.api.settings.get('store.currency'),
         );
       }
 
@@ -53,7 +52,7 @@ function methods(request, opt) {
         ),
       );
 
-      setCookie('swell-currency', code);
+      opt.setCookie('swell-currency', code);
 
       return this.state;
     },
diff --git a/dist/locale-abdc14e0.js b/dist/locale-abdc14e0.js
index 2eee80646b6979c33193a87c495e7b59598b15c3..7cd4b4209a92a5b23b7dadd9d93153c96488871b 100644
--- a/dist/locale-abdc14e0.js
+++ b/dist/locale-abdc14e0.js
@@ -2,7 +2,6 @@ import 'qs';
 import { f as find } from './index-bee7164f.js';
 import 'deepmerge';
 import 'fast-case';
-import { s as setCookie, g as getCookie } from './cookie-dff5d694.js';
 
 function methods(request, opt) {
   return {
@@ -15,7 +14,7 @@ function methods(request, opt) {
 
     async select(locale) {
       this.set(locale);
-      setCookie('swell-locale', locale);
+      opt.setCookie('swell-locale', locale);
       opt.api.settings.locale = locale;
       return await request('put', '/session', { locale });
     },
@@ -25,7 +24,7 @@ function methods(request, opt) {
         return this.code;
       }
       const storeLocale = opt.api.settings.getStoreLocale();
-      const cookieLocale = getCookie('swell-locale');
+      const cookieLocale = opt.getCookie('swell-locale');
       opt.api.settings.locale = cookieLocale || storeLocale;
       return cookieLocale || storeLocale;
     },

React Native support

I am currently integrating the SDK in a React Native app written mainly with TypeScript.
So far Swell JS SDK works well, there are only two blocking issues:

  1. Buffer has to be set as a global variable to that SDK works correctly
  2. Session management relies exclusively on browser cookies. Maybe there is an abstraction layer to add for supporting both web and React Native?

For the moment, I have created a quick and dirty workaround to emulate document object (cookies are saved separately using AsyncStorage).

This is main index.js :

import buffer from 'buffer';
global.Buffer = buffer.Buffer;

import SwellDocument from 'utils/SwellDocument';
global.document = new SwellDocument();

And this is SwellUtils.tsfile for the cookie workaround:

class SwellCookie {
  public stringValue: string = '';

  public match = (re: RegExp): RegExpMatchArray | null => {
    return this.stringValue.match(re);
  }

  public toString = (): string => {
    return this.stringValue;
  }
};

export default class SwellDocument {
  private _cookie: SwellCookie = new SwellCookie();

  get cookie(): SwellCookie | string {
    return this._cookie;
  }

  set cookie(value: SwellCookie | string) {
      this._cookie.stringValue = value as string;
  }
};

Unable to get or update `account.metadata`

Since November 5, we are not allowed to update account.medadata. Even more problematic, we get an empty object for existing account metadata. Our registration form and custom checkout are broken because of this.

Here is the Next.js error message when we call swell.account.create() and try to update metadata:

Capture d’écran 2022-11-05 at 21 33 59

swell.payment.createElements is throwing error: cartApi.methods is not a function

Hey! :) As written in the title, I get an error when calling swell.payment.createElements.

Error: TypeError: da.methods is not a function (da = cartApi)
It get's thrown here.

My (very short) code-snippet:

swell.payment.createElements({
  card: {
    elementId: 'card-element-id'
  }
})

Is anyone else experiencing this or am I the only one and should investigate this issue further?

Stripe error when upgrading from 3.17.10 to 3.18.2

Hello,

When upgrading from version 3.17.10 to 3.18.2, I'm getting the following error when trying to pay by card with Stripe.

Missing value for stripe.confirmCardSetup intent secret: value should be a client_secret string.

I believe it's due to change coming in version 3.17.11 but I have no idea how to fix this as I see no changes in the documentation.
No problem when downgrading to version 3.17.10.

Thanks for you help.

Type definitions missing error object in return type

When an api call doesn't succeed, there is an "errors" property returned from swellj-s. For example:

const cart = await swell.cart.get()
if(cart.errors){
 // handle errors
}

This isn't accounted for the in the type definitions. The return type is just Promise<swell.Cart> and Cart doesn't include errors so trying to handle errors is showing a type error warning as of swell-js 3.21.2

Add paypal button onCancel/onInit/onClick events handlers

It seems not possible for now to use onCancel/onInit/onClick/onShippingChange paypal buttons options in swell:

Replacing the payPalButton function of src/payment.js does the tricks, but we can not make PR to add it.

async function payPalButton(request, cart, payMethods, params) {
  const paypal = window.paypal;
  const { paypal: { locale, style, elementId } = {} } = params;
  const { capture_total, currency, guest } = cart;

  const onError = (error) => {
    const errorHandler = get(params, 'paypal.onError');
    if (isFunction(errorHandler)) {
      return errorHandler(error);
    }
    throw new Error(error.message);
  };
  const onSuccess = () => {
    const successHandler = get(params, 'paypal.onSuccess');
    return isFunction(successHandler) && successHandler();
  };
+ const onInit = (data, actions) => {
+   const initHandler = get(params, 'paypal.onInit');
+   return isFunction(initHandler) && initHandler(data, actions);
+ };
+ const onClick = (data, actions) => {
+   const clickHandler = get(params, 'paypal.onClick');
+   return isFunction(clickHandler) && clickHandler(data, actions);
+ };
+ const onCancel = (data, actions) => {
+   const cancelHandler = get(params, 'paypal.onCancel');
+   return isFunction(cancelHandler) && cancelHandler(data, actions);
+ };
+ const onShippingChange = (data, actions) => {
+   const shippingChangeHandler = get(params, 'paypal.onShippingChange');
+   return isFunction(shippingChangeHandler) && shippingChangeHandler(data, actions);
+ };

  if (!(capture_total > 0)) {
    throw new Error(
      'Invalid PayPal button amount. Value should be greater than zero.',
    );
  }

  paypal
    .Buttons(
      {
        locale: locale || 'en_US',
        style: style || {
          layout: 'horizontal',
          height: 45,
          color: 'gold',
          shape: 'rect',
          label: 'paypal',
          tagline: false,
        },
+       onInit,
+       onClick,
+       onCancel,
+       onShippingChange,
        createOrder: (data, actions) =>
          actions.order.create({
            intent: 'AUTHORIZE',
            purchase_units: [
              {
                amount: {
                  value: +capture_total.toFixed(2),
                  currency_code: currency,
                },
              },
            ],
          }),
        onApprove: (data, actions) =>
          actions.order
            .get()
            .then(async (order) => {
              const orderId = order.id;
              const payer = order.payer;
              const shipping = get(order, 'purchase_units[0].shipping');

              const usePayPalEmail = await shouldUsePayPalEmail(
                guest,
                request,
                options,
              );

              return cartApi(request).update({
                ...(usePayPalEmail && {
                  account: {
                    email: payer.email_address,
                  },
                }),
                billing: {
                  method: 'paypal',
                  paypal: { order_id: orderId },
                },
                shipping: {
                  name: shipping.name.full_name,
                  address1: shipping.address.address_line_1,
                  address2: shipping.address.address_line_2,
                  state: shipping.address.admin_area_1,
                  city: shipping.address.admin_area_2,
                  zip: shipping.address.postal_code,
                  country: shipping.address.country_code,
                },
              });
            })
            .then(onSuccess)
            .catch(onError),
      },
      onError,
    )
    .render(elementId || '#paypal-button');
}

Can you add this on the next release?

Support Braintree CVV (CVC)

We really want to use Swell for multiple sites, but we still can't do so because your Braintree checkout on your checkout page is broken because it does not send the CVV (you call it CVC) to Braintree. Who do we contact to have you fix your Braintree Bug on your checkout URL (swell.store/checkout/)?

Braintree only works if Braintree is not set up to verify the CVV (a setting in the actual Braintree admin). However, if you set CVV verification in Braintree admin (a requirement nowadays), your Braintree Payment fails on checkout, with the error code (CVV not sent). This is clearly just some small problem in your code, where you are not sending the CVV correctly to Braintree.

To RECREATE

To recreate this on your end, simply set up a Braintree account. Go into the Sandbox and click on the Settings Gear Icon -> Fraud Settings - > CVV Section and check off "CVV does not match" "CVV Not Provided" (see attached screenshot). Then after these settings are done, try to checkout with Swell. It will not work, as Swell does not send the CVV correctly. You will get an error message as follows on the Swell checkout page: Billing method: Payment authorization failed (cvv is required.)

Proposed Solution

In looking at your code, you are obviously using the Braintree SDK. In which case, there are 2 things that might be wrong:

  1. You are not actually sending the CVV to the SDK when you submit your form. or
  2. You are sending the wrong id. In fact, I think this is the problem. You have named the field "CVC" in your code, but Braintree requires a field called CVV ( see: https://github.com/braintree/braintree-web)
    So to solve this just correclty send the CVV to Braintree. Probably needs to add one line to your code send CVV and not CVC.

braintreeScreenshot 2021-07-06 at 8 22 35 AM

Can't update shipping.price (permission error)

Hi there,

We are trying to update the shipping price for our checkout. We are using the following code.

      await swell.cart.update({

        shipping: {
          service: deliveryArray.join(),
          price: 1000,
          deliveries,
          instructions,
        },
      });

However it seems that with storefront token we are not able to update the price of the shipping?

{
    "code": "permission_error",
    "message": "You are not allowed to update `price`",
    "param": "price"
}

Please let us know what is to be done to fix this.

Thanks

Type issues in 3.19.3

I've noticed a few type issues in the latest package with embedded types:

  1. swell.cart.submitOrder is missing, even though documented at https://developers.swell.is/frontend-api/orders#submit-an-order
  2. On swell.payment.createElements all functions are synchronous, not accepting async functions. I'd suggest changing to () => Promise<void> as it makes sense to do asynchronous actions in methods such as onSuccess or onError, Actually all the InputPaymentElementCard are syncronous.
  3. Still on swell.payment.createElements, the method onError for payPal only accepts void, shouldn't it be a (error) => void so we can read the error in error?
  4. On swell.payment.createElements, for card, it is not recognising separateElements: boolean, as specified here: https://developers.swell.is/frontend-api/payments#render-a-stripe-card-element
  5. Swell.init forces me to explicitly declare all options if I have an option, probably because the type is:
interface InitOptions {
  currency: string;
  key: string;
  locale: string;
  previewContent: boolean;
  session: string;
  store: string;
  timeout: number;
  useCamelCase: boolean;
  url: string;
  vaultUrl: string;
}

Should actually be:

interface InitOptions {
  currency?: string;
  key?: string;
  locale?: string;
  previewContent?: boolean;
  session?: string;
  store?: string;
  timeout?: number;
  useCamelCase?: boolean;
  URL?: string;
  vaultUrl?: string;
}
  1. Swell.cart.applyCoupon doesn't have applyCoupon, but it's part of the specs: https://developers.swell.is/frontend-api/coupons#apply-a-coupon
  2. Swell.cart.setItems([]) is invalid because it only accepts an array with CartItem inside, but this should be accepted as specified https://developers.swell.is/frontend-api/carts#empty-the-cart
  3. Types are not explicitly exported. So if I try to use any typecasting for example for Products I can't because Swell only exports: BaseModel, Discount, InitOptions, ResultResponse, SnakeToCamelCase and Tax. If I want to use specific types that were already in the root export in @types/swell-js, I need to change my import to import type { Product } from "swell-js/types/product" instead of just using import type { Product } from "swell-js"

Please publish 3.17.7 on npm

3.17.7 contains fix for isomorphic fetch, can you release it on npm ?

Also, where is the development branch ? I only see stale branches

types missing in latest version

Hi, there are some type definitions, in the currenty released version, mssing.

I tried to upgrade from 3.18.2 to 3.20.1

the type definition for InputPayment here

interface InputPaymentElement extends InputPayment {
is undefined.

also InputPaymentElementApple and InputPaymentRedirect are not exported here

InputPaymentElementApple,
from the payments definition, because they aren't defined.

Without that the library is not useable.

Problems updating the paiment status at Swell

Hello, we are having some troubles updating the cart/order based on billing property at the end of the process.

We have followed the iDeal integration. We have completed the process, but when we goes to swell the status are iDeal - Unpaid:
image

When we access to the order, we can charge the order:
image

However this process should be made manually, so we would like to make it on a more automatically way. We suppose that it happens because at billing object we use the property requires_confirmation, but we don't know wich other status can we use at this field to change the order status to paid.

Our payment intent creation is the following:

const paymentIntent = await stripe.paymentIntents.create({
  payment_method: paymentMethod ? paymentMethod.id : undefined,
  amount: order.sub_total * 100, //it should receive integers
  receipt_email: user.email,
  currency: 'eur', // ideal method only accept eur currency
  payment_method_types: ['ideal'],
});

Instead using handleCartAction method we are usign confirmIdealPayment like this (we can't set the url at backend because we handle multiple front-end applications with diferent urls, but I think that It's not the issue):

const cardAction = await paymentService?.confirmIdealPayment(paymentSecret, {
  return_url: `${window.location.origin}/purchase-status/${cartId}`
})

And our current billing object looks like this:

const billing = {
  method: 'ideal',
    ideal: {
      token: paymentIntent.payment_method,
    },
    stripe_payment_intent: {
      id: paymentIntent.id,
        status: 'requires_confirmation',
    },
};

Can you help us? Maybe we are doing things on the wrong way, or we miss something about the process.

Thank you!

TypeScript support

I'm writing my application in TypeScript and would like to see TypeScript typing support.

CORS error on removeItem from cart

I started a new project with Swell, I am able to fetch products and categories, fetch carts, add items to cart, but whenever I try to remove an Item from the cart I get the following error:

image

any help would be greatly appreciated.

I am using swell-js@^3.19.4 and angular

Deduplication in Cart is still very buggy

First of, what I mean by deduplication is that if you add an item to the cart, where the exact same item is already in the cart, the cart should increment the quantity of that item, instead of adding it a new item to the cart. So let's say you have 5 of product ABC in the cart. If you add 2 more of ABC to the cart, the cart should simply add quantity of 2 to ABC for 7 ABC in cart, instead of adding another item of 2 of ABC, and then ABC is in the cart twice.

Unfortunately, deduplication of a cart in Swell with the API is still very buggy and can't be trusted. I posted about this bug a long time ago and I am dismayed that the API still doesn't have this fixed, and we need to still dedupe at the client level, which slows everything down. Deduplication is a simple concept and should happen at the API level.

I have tested extensively and the API still doesn't dedupe, though I think the claim is that it does. From my testing the dedupe will only occur after there are 2 of the same item in the cart, and/or if there is already something else in the cart. So what happens is that if you have an empty cart and Add 1 of ABC to the cart and then Add another 1 of ABC to the cart, it will not dedupe. Thereafter, if you add 1 of ABC, it will dedupe, though, which item in the cart it adds it to, seems to be totally random. I am not sure what the source of this issue is in the code, but I can state that the above definitely happens (dedupe only occurs after 2 of the same item are in the cart).

Of course, if you just dedupe at the client level, you can eliminate the errors from the API, but this is far from ideal. Please add proper deduplication to the API.

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.