@commercelayer/react-components 4.5.0-beta.2 → 4.5.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/components/customers/MyAccountLink.d.ts +23 -0
- package/lib/cjs/components/customers/MyAccountLink.js +1 -0
- package/lib/cjs/components/orders/AddToCartButton.js +1 -1
- package/lib/cjs/components/orders/CartLink.d.ts +15 -0
- package/lib/cjs/components/orders/CartLink.js +1 -1
- package/lib/cjs/components/orders/CheckoutLink.js +1 -1
- package/lib/cjs/components/orders/HostedCart.d.ts +30 -0
- package/lib/cjs/components/orders/HostedCart.js +1 -0
- package/lib/cjs/components/orders/PlaceOrderButton.d.ts +13 -0
- package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
- package/lib/cjs/components/payment_gateways/StripeGateway.js +1 -1
- package/lib/cjs/components/utils/PaymentCardsTemplate.d.ts +27 -2
- package/lib/cjs/utils/events.d.ts +5 -0
- package/lib/cjs/utils/events.js +1 -0
- package/lib/cjs/utils/getApplicationLink.d.ts +16 -0
- package/lib/cjs/utils/getApplicationLink.js +1 -0
- package/lib/cjs/utils/getCardDetails.js +1 -1
- package/lib/esm/components/customers/MyAccountLink.d.ts +23 -0
- package/lib/esm/components/customers/MyAccountLink.js +1 -0
- package/lib/esm/components/orders/AddToCartButton.js +1 -1
- package/lib/esm/components/orders/CartLink.d.ts +15 -0
- package/lib/esm/components/orders/CartLink.js +1 -1
- package/lib/esm/components/orders/CheckoutLink.js +1 -1
- package/lib/esm/components/orders/HostedCart.d.ts +30 -0
- package/lib/esm/components/orders/HostedCart.js +1 -0
- package/lib/esm/components/orders/PlaceOrderButton.d.ts +13 -0
- package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
- package/lib/esm/components/payment_gateways/StripeGateway.js +1 -1
- package/lib/esm/components/utils/PaymentCardsTemplate.d.ts +27 -2
- package/lib/esm/utils/events.d.ts +5 -0
- package/lib/esm/utils/events.js +1 -0
- package/lib/esm/utils/getApplicationLink.d.ts +16 -0
- package/lib/esm/utils/getApplicationLink.js +1 -0
- package/lib/esm/utils/getCardDetails.js +1 -1
- package/package.json +3 -1
- package/lib/cjs/utils/getCartLink.d.ts +0 -8
- package/lib/cjs/utils/getCartLink.js +0 -1
- package/lib/esm/utils/getCartLink.d.ts +0 -8
- package/lib/esm/utils/getCartLink.js +0 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ChildrenFunction } from '../../typings/index';
|
|
2
|
+
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
3
|
+
/**
|
|
4
|
+
* The link href
|
|
5
|
+
*/
|
|
6
|
+
href: string;
|
|
7
|
+
/**
|
|
8
|
+
* The link status
|
|
9
|
+
*/
|
|
10
|
+
disabled: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
|
|
13
|
+
/**
|
|
14
|
+
* A render function to render your own custom component
|
|
15
|
+
*/
|
|
16
|
+
children?: ChildrenFunction<ChildrenProps>;
|
|
17
|
+
/**
|
|
18
|
+
* The label of the link
|
|
19
|
+
*/
|
|
20
|
+
label?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function MyAccountLink(props: Props): JSX.Element;
|
|
23
|
+
export default MyAccountLink;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MyAccountLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain"),jwt_1=tslib_1.__importDefault(require("../../utils/jwt"));function MyAccountLink(props){const{label="Go to my account",children}=props,p=tslib_1.__rest(props,["label","children"]),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyAccountLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint),disabled=!("owner"in(0,jwt_1.default)(accessToken)),href=(0,getApplicationLink_1.getApplicationLink)({slug,accessToken,applicationType:"my-account",domain}),parentProps=Object.assign({disabled,label,href},p);function handleClick(e){disabled&&e.preventDefault()}return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({"aria-disabled":disabled,onClick:handleClick,href},p,{children:label}))}exports.MyAccountLink=MyAccountLink,exports.default=MyAccountLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddToCartButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),SkuListsContext_1=tslib_1.__importDefault(require("../../context/SkuListsContext")),ExternalFunctionContext_1=tslib_1.__importDefault(require("../../context/ExternalFunctionContext")),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddToCartButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),SkuListsContext_1=tslib_1.__importDefault(require("../../context/SkuListsContext")),ExternalFunctionContext_1=tslib_1.__importDefault(require("../../context/ExternalFunctionContext")),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),getDomain_1=require("../../utils/getDomain"),events_1=require("../../utils/events");function AddToCartButton(props){var _a;const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption}=props,p=tslib_1.__rest(props,["label","children","skuCode","bundleCode","skuListId","lineItem","buyNowMode","checkoutUrl","redirectToHostedCart","hostedCartUrl","quantity","lineItemOption"]),{accessToken,endpoint}=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=(0,react_1.useContext)(ExternalFunctionContext_1.default),{skuLists}=(0,react_1.useContext)(SkuListsContext_1.default),{sku}=(0,react_1.useContext)(SkuChildrenContext_1.default),sCode=(_a=sku?.code)!==null&&_a!==void 0?_a:skuCode,handleClick=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _b;const qty=quantity!=null?parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=(_b=skuLists?.[skuListId])===null||_b===void 0?void 0:_b.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return yield callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(res=>tslib_1.__awaiter(this,void 0,void 0,function*(){return getOrder&&orderId&&(yield getOrder(orderId)),(0,events_1.publish)("open-cart"),res})).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=yield addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=(0,getDomain_1.getDomain)(endpoint),orderId2=res?.orderId;hostedCartUrl&&orderId2?location.href=`https://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`:orderId2&&slug&&(location.href=(0,getApplicationLink_1.getApplicationLink)({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"}))}return(0,events_1.publish)("open-cart"),res}else if(url)return yield callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(res=>tslib_1.__awaiter(this,void 0,void 0,function*(){return getOrder&&orderId&&(yield getOrder(orderId)),(0,events_1.publish)("open-cart"),res})).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}),parentProps=Object.assign({handleClick,label},props);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({},p,{onClick:()=>{handleClick()},children:label}))}exports.AddToCartButton=AddToCartButton,exports.default=AddToCartButton;
|
|
@@ -1,12 +1,27 @@
|
|
|
1
1
|
import { type MouseEvent, type ReactNode } from 'react';
|
|
2
2
|
import { type ChildrenFunction } from '../../typings/index';
|
|
3
3
|
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
4
|
+
/**
|
|
5
|
+
* The url of the cart
|
|
6
|
+
*/
|
|
4
7
|
href: string;
|
|
8
|
+
/**
|
|
9
|
+
* Callback to dispatch the click event
|
|
10
|
+
* @param e: MouseEvent<HTMLAnchorElement>
|
|
11
|
+
* @returns Promise<void>
|
|
12
|
+
*/
|
|
5
13
|
handleClick?: (e: MouseEvent<HTMLAnchorElement>) => Promise<void>;
|
|
6
14
|
}
|
|
7
15
|
interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
|
|
8
16
|
children?: ChildrenFunction<ChildrenProps>;
|
|
17
|
+
/**
|
|
18
|
+
* Label to display
|
|
19
|
+
*/
|
|
9
20
|
label?: string | ReactNode;
|
|
21
|
+
/**
|
|
22
|
+
* The type of the cart. Defaults to undefined. If set to 'mini', the cart will open in a modal.
|
|
23
|
+
*/
|
|
24
|
+
type?: 'mini';
|
|
10
25
|
}
|
|
11
26
|
export declare function CartLink(props: Props): JSX.Element | null;
|
|
12
27
|
export default CartLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CartLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CartLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain"),events_1=require("../../utils/events");function CartLink(props){const{label,children,type}=props,p=tslib_1.__rest(props,["label","children","type"]),{order,createOrder}=(0,react_1.useContext)(OrderContext_1.default),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default);if(accessToken==null)throw new Error("Cannot use `CartLink` outside of `CommerceLayer`");if(endpoint==null)throw new Error("Cannot use `CartLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint),href=slug&&order?.id?(0,getApplicationLink_1.getApplicationLink)({slug,orderId:order?.id,accessToken,domain,applicationType:"cart"}):"",handleClick=event=>tslib_1.__awaiter(this,void 0,void 0,function*(){if(event.preventDefault(),type!=="mini")if(order?.id)location.href=href;else{const orderId=yield createOrder();slug&&(location.href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId,accessToken,domain,applicationType:"cart"}))}else(0,events_1.publish)("open-cart")}),parentProps=Object.assign({handleClick,label,href},p);return accessToken?children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({href},p,{onClick:e=>{handleClick(e)},children:label})):null}exports.CartLink=CartLink,exports.default=CartLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext"));function CheckoutLink(props){var _a;const{label,hostedCheckout=!0,children}=props,p=tslib_1.__rest(props,["label","hostedCheckout","children"]),{order}=(0,react_1.useContext)(OrderContext_1.default),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default);if(accessToken==null||endpoint==null)throw new Error("Cannot use `CheckoutLink` outside of `CommerceLayer`");const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutLink=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain");function CheckoutLink(props){var _a;const{label,hostedCheckout=!0,children}=props,p=tslib_1.__rest(props,["label","hostedCheckout","children"]),{order}=(0,react_1.useContext)(OrderContext_1.default),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default);if(accessToken==null||endpoint==null)throw new Error("Cannot use `CheckoutLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint),href=hostedCheckout&&order?.id?(0,getApplicationLink_1.getApplicationLink)({slug,orderId:order?.id,accessToken,applicationType:"checkout",domain}):(_a=order?.checkout_url)!==null&&_a!==void 0?_a:"",parentProps=Object.assign({checkoutUrl:order?.checkout_url,hostedCheckout,label,href},p);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("a",Object.assign({href},p,{children:label}))}exports.CheckoutLink=CheckoutLink,exports.default=CheckoutLink;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type CSSProperties } from 'react';
|
|
2
|
+
interface Styles {
|
|
3
|
+
cart?: CSSProperties;
|
|
4
|
+
container?: CSSProperties;
|
|
5
|
+
background?: CSSProperties;
|
|
6
|
+
}
|
|
7
|
+
interface Props extends Omit<JSX.IntrinsicElements['div'], 'children' | 'style'> {
|
|
8
|
+
/**
|
|
9
|
+
* The type of the cart. Defaults to undefined.
|
|
10
|
+
*/
|
|
11
|
+
type?: 'mini';
|
|
12
|
+
/**
|
|
13
|
+
* If true, the cart will open when a line item is added to the order clicking the add to cart button. Defaults to false.
|
|
14
|
+
*/
|
|
15
|
+
openAdd?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* The style of the cart.
|
|
18
|
+
*/
|
|
19
|
+
style?: Styles;
|
|
20
|
+
/**
|
|
21
|
+
* If true, the cart will be open. Defaults to false.
|
|
22
|
+
*/
|
|
23
|
+
open?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* A function that will be called when the cart is open and the background is clicked.
|
|
26
|
+
*/
|
|
27
|
+
handleOpen?: () => void;
|
|
28
|
+
}
|
|
29
|
+
export declare function HostedCart({ type, openAdd, style, open, handleOpen, ...props }: Props): JSX.Element | null;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.HostedCart=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain"),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),react_1=require("react"),iframe_resizer_1=require("iframe-resizer"),events_1=require("../../utils/events"),defaultIframeStyle={width:"1px",minWidth:"100%",minHeight:"100%",border:"none"},defaultContainerStyle={position:"fixed",top:"0",right:"-25rem",height:"100%",width:"23rem",transition:"right 0.5s ease-in-out",zIndex:"0"},defaultBackgroundStyle={opacity:"0",position:"fixed",top:"0",left:"0",height:"100%",width:"100vw",transition:"opacity 0.5s ease-in-out",zIndex:"-10",backgroundColor:"black"},defaultStyle={cart:defaultIframeStyle,container:defaultContainerStyle,background:defaultBackgroundStyle};function HostedCart(_a){var _b,_c,_d,_e,{type,openAdd=!1,style=defaultStyle,open=!1,handleOpen}=_a,props=tslib_1.__rest(_a,["type","openAdd","style","open","handleOpen"]);const[isOpen,setOpen]=(0,react_1.useState)(!1),ref=(0,react_1.useRef)(null),{accessToken,endpoint}=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"HostedCart",key:"accessToken"}),[src,setSrc]=(0,react_1.useState)();if(accessToken==null||endpoint==null)return null;const{order,createOrder}=(0,react_1.useContext)(OrderContext_1.default),{persistKey}=(0,react_1.useContext)(OrderStorageContext_1.default),{domain,slug}=(0,getDomain_1.getDomain)(endpoint);function setOrder(openCart){var _a2;return tslib_1.__awaiter(this,void 0,void 0,function*(){const orderId=(_a2=localStorage.getItem(persistKey))!==null&&_a2!==void 0?_a2:yield createOrder();orderId!=null&&accessToken!=null&&(setSrc((0,getApplicationLink_1.getApplicationLink)({slug,orderId,accessToken,domain,applicationType:"cart"})),openCart&&setTimeout(()=>{handleOpen!=null?handleOpen():setOpen(!0)},300))})}function onMessage(data){var _a2;switch(data.message.type){case"update":break;case"close":type==="mini"&&(handleOpen!=null?handleOpen():setOpen(!1));break;case"blur":type==="mini"&&isOpen&&((_a2=ref.current)===null||_a2===void 0||_a2.focus());break}}return(0,react_1.useEffect)(()=>{var _a2;const orderId=localStorage.getItem(persistKey);let ignore=!1;return open!=null&&open!==isOpen&&setOpen(open),openAdd&&type==="mini"&&(0,events_1.subscribe)("open-cart",()=>{console.log("open-cart by event",src,order?.id,orderId),src==null&&order?.id==null&&orderId==null?setOrder(!0):(src!=null&&ref.current!=null&&(ref.current.src=src),setTimeout(()=>{handleOpen!=null?handleOpen():setOpen(!0)},300))}),src==null&&order?.id==null&&orderId==null&&accessToken!=null&&!ignore&&isOpen?setOrder():src==null&&(order?.id!=null||orderId!=null)&&setSrc((0,getApplicationLink_1.getApplicationLink)({slug,orderId:(_a2=order?.id)!==null&&_a2!==void 0?_a2:orderId,accessToken,domain,applicationType:"cart"})),src!=null&&ref.current!=null&&(ref.current.src=src),()=>{ignore=!0,openAdd&&type==="mini"&&(0,events_1.unsubscribe)("open-cart",()=>{})}},[src,open,order?.id]),(0,react_1.useEffect)(()=>{ref.current!=null&&(0,iframe_resizer_1.iframeResizer)({checkOrigin:!1,bodyPadding:"20px",onMessage},ref.current)},[ref.current!=null]),src==null?null:type==="mini"?(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,jsx_runtime_1.jsx)("div",{style:Object.assign(Object.assign({},style.background),{opacity:isOpen?"0.5":(_b=style.background)===null||_b===void 0?void 0:_b.opacity,zIndex:isOpen?"1":(_c=style.background)===null||_c===void 0?void 0:_c.zIndex}),onClick:()=>{handleOpen!=null?handleOpen():setOpen(!1)}}),(0,jsx_runtime_1.jsx)("div",Object.assign({style:Object.assign(Object.assign({},style.container),{right:isOpen?"0":(_d=style.container)===null||_d===void 0?void 0:_d.right,zIndex:isOpen?"10":(_e=style.container)===null||_e===void 0?void 0:_e.zIndex})},props,{children:(0,jsx_runtime_1.jsx)("iframe",{title:"Cart",ref,style:style.cart,src,width:"100%",height:"100%"})}))]}):(0,jsx_runtime_1.jsx)("iframe",{title:"Cart",ref,style:style.cart,src,width:"100%",height:"100%"})}exports.HostedCart=HostedCart;
|
|
@@ -3,11 +3,24 @@ import { type ChildrenFunction } from '../../typings/index';
|
|
|
3
3
|
import type { BaseError } from '../../typings/errors';
|
|
4
4
|
import type { Order } from '@commercelayer/sdk';
|
|
5
5
|
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
6
|
+
/**
|
|
7
|
+
* Callback function to place the order
|
|
8
|
+
*/
|
|
6
9
|
handleClick: () => Promise<void>;
|
|
7
10
|
}
|
|
8
11
|
interface Props extends Omit<JSX.IntrinsicElements['button'], 'children' | 'onClick'> {
|
|
9
12
|
children?: ChildrenFunction<ChildrenProps>;
|
|
13
|
+
/**
|
|
14
|
+
* The label of the button
|
|
15
|
+
*/
|
|
10
16
|
label?: string | ReactNode;
|
|
17
|
+
/**
|
|
18
|
+
* If false, the button doesn't place the order automatically. Default: true
|
|
19
|
+
*/
|
|
20
|
+
autoPlaceOrder?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Callback function that is fired when the button is clicked
|
|
23
|
+
*/
|
|
11
24
|
onClick?: (response: {
|
|
12
25
|
placed: boolean;
|
|
13
26
|
order?: Order;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails"));function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="stripe_payments"&&((_a2=options?.stripe)===null||_a2===void 0?void 0:_a2.redirectStatus)==="succeeded"&&order?.status&&["draft","pending"].includes(order?.status)&&handleClick()},[(_b=options?.stripe)===null||_b===void 0?void 0:_b.redirectStatus,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g;if(order?.status!=null&&["draft","pending"].includes(order?.status))if(paymentType==="adyen_payments"&&(!((_a2=options?.adyen)===null||_a2===void 0)&&_a2.redirectResult)&&paymentSource!=null){const attributes={payment_request_details:{details:{redirectResult:(_b2=options?.adyen)===null||_b2===void 0?void 0:_b2.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode)?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_c2=options?.adyen)===null||_c2===void 0)&&_c2.MD)&&(!((_d2=options?.adyen)===null||_d2===void 0)&&_d2.PaRes)||paymentType==="adyen_payments"&&((_f=(_e=order?.payment_source)===null||_e===void 0?void 0:_e.payment_response)===null||_f===void 0?void 0:_f.resultCode)==="Authorised"&&((_g=ref?.current)===null||_g===void 0?void 0:_g.disabled)===!1)&&handleClick()},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&handleClick()},[options?.checkoutCom,paymentType]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _e,_f,_g,_h,_j;e?.preventDefault(),e?.stopPropagation();let isValid=!0;setForceDisable(!0);const checkPaymentSource=yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}),card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_e=currentPaymentMethodRef?.current)===null||_e===void 0)&&_e.onsubmit&&[!options?.paypalPayerId,!(!((_f=options?.adyen)===null||_f===void 0)&&_f.MD),!(!((_g=options?.checkoutCom)===null||_g===void 0)&&_g.session_id)].every(Boolean)?(isValid=yield(_h=currentPaymentMethodRef.current)===null||_h===void 0?void 0:_h.onsubmit(checkPaymentSource),!isValid&&((_j=checkPaymentSource.payment_response)===null||_j===void 0?void 0:_j.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0);const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource}));setForceDisable(!1),onClick&&placed&&onClick(placed)}),disabledButton=disabled!==void 0?disabled:notPermitted,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,ref});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:(0,isFunction_1.default)(label)?label():label}))}exports.PlaceOrderButton=PlaceOrderButton,exports.default=PlaceOrderButton;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails"));function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="stripe_payments"&&((_a2=options?.stripe)===null||_a2===void 0?void 0:_a2.redirectStatus)==="succeeded"&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[(_b=options?.stripe)===null||_b===void 0?void 0:_b.redirectStatus,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g;if(order?.status!=null&&["draft","pending"].includes(order?.status))if(paymentType==="adyen_payments"&&(!((_a2=options?.adyen)===null||_a2===void 0)&&_a2.redirectResult)&&paymentSource!=null){const attributes={payment_request_details:{details:{redirectResult:(_b2=options?.adyen)===null||_b2===void 0?void 0:_b2.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_c2=options?.adyen)===null||_c2===void 0)&&_c2.MD)&&(!((_d2=options?.adyen)===null||_d2===void 0)&&_d2.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&((_f=(_e=order?.payment_source)===null||_e===void 0?void 0:_e.payment_response)===null||_f===void 0?void 0:_f.resultCode)==="Authorised"&&((_g=ref?.current)===null||_g===void 0?void 0:_g.disabled)===!1&&autoPlaceOrder)&&handleClick()},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _e,_f,_g,_h,_j;e?.preventDefault(),e?.stopPropagation();let isValid=!0;setForceDisable(!0);const checkPaymentSource=yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}),card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_e=currentPaymentMethodRef?.current)===null||_e===void 0)&&_e.onsubmit&&[!options?.paypalPayerId,!(!((_f=options?.adyen)===null||_f===void 0)&&_f.MD),!(!((_g=options?.checkoutCom)===null||_g===void 0)&&_g.session_id)].every(Boolean)?(isValid=yield(_h=currentPaymentMethodRef.current)===null||_h===void 0?void 0:_h.onsubmit(checkPaymentSource),!isValid&&((_j=checkPaymentSource.payment_response)===null||_j===void 0?void 0:_j.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0);const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource}));setForceDisable(!1),onClick&&placed&&onClick(placed)}),disabledButton=disabled!==void 0?disabled:notPermitted,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,ref});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:(0,isFunction_1.default)(label)?label():label}))}exports.PlaceOrderButton=PlaceOrderButton,exports.default=PlaceOrderButton;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripeGateway=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),StripePayment_1=tslib_1.__importDefault(require("../payment_source/StripePayment")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentSourceContext_1=tslib_1.__importDefault(require("../../context/PaymentSourceContext")),PaymentMethodReducer_1=require("../../reducers/PaymentMethodReducer"),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),react_1=tslib_1.__importDefault(require("react")),PaymentCardsTemplate_1=tslib_1.__importDefault(require("../utils/PaymentCardsTemplate"));function StripeGateway(props){var _a;const{readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,loaderComponent,templateCustomerSaveToWallet}=props,p=tslib_1.__rest(props,["readonly","showCard","handleEditClick","children","templateCustomerCards","show","loading","loaderComponent","templateCustomerSaveToWallet"]),{order}=react_1.default.useContext(OrderContext_1.default),{payment,expressPayments}=react_1.default.useContext(PaymentMethodChildrenContext_1.default),{payments,isGuest}=react_1.default.useContext(CustomerContext_1.default),{currentPaymentMethodId,config,paymentSource}=react_1.default.useContext(PaymentMethodContext_1.default),paymentResource="stripe_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const publishableKey=paymentSource?.publishable_key,clientSecret=paymentSource?.client_secret,paymentSourceId=((_a=order?.payment_source)===null||_a===void 0?void 0:_a.id)||paymentSource?.id,stripeConfig=config?(0,PaymentMethodReducer_1.getPaymentConfig)(paymentResource,config):{},customerPayments=!(0,isEmpty_1.default)(payments)&&payments?payments.filter(customerPayment=>{var _a2;return((_a2=customerPayment.payment_source)===null||_a2===void 0?void 0:_a2.type)===paymentResource}):[];if(readonly||showCard){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value=Object.assign(Object.assign({},card),{showCard,handleEditClick,readonly});return(0,isEmpty_1.default)(card)?null:(0,jsx_runtime_1.jsx)(PaymentSourceContext_1.default.Provider,{value,children})}return!isGuest&&templateCustomerCards?(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,isEmpty_1.default)(customerPayments)?null:(0,jsx_runtime_1.jsx)("div",{className:p.className,children:(0,jsx_runtime_1.jsx)(PaymentCardsTemplate_1.default,{paymentResource,customerPayments,children:templateCustomerCards})}),(0,jsx_runtime_1.jsx)(StripePayment_1.default,Object.assign({show,templateCustomerSaveToWallet,publishableKey,clientSecret,expressPayments,locale},stripeConfig))]}):publishableKey&&!loading&&paymentSourceId?(0,jsx_runtime_1.jsx)(StripePayment_1.default,Object.assign({show,publishableKey,clientSecret,locale,expressPayments},stripeConfig)):loaderComponent}exports.StripeGateway=StripeGateway,exports.default=StripeGateway;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripeGateway=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),StripePayment_1=tslib_1.__importDefault(require("../payment_source/StripePayment")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentSourceContext_1=tslib_1.__importDefault(require("../../context/PaymentSourceContext")),PaymentMethodReducer_1=require("../../reducers/PaymentMethodReducer"),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),react_1=tslib_1.__importDefault(require("react")),PaymentCardsTemplate_1=tslib_1.__importDefault(require("../utils/PaymentCardsTemplate"));function StripeGateway(props){var _a;const{readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,loaderComponent,templateCustomerSaveToWallet}=props,p=tslib_1.__rest(props,["readonly","showCard","handleEditClick","children","templateCustomerCards","show","loading","loaderComponent","templateCustomerSaveToWallet"]),{order}=react_1.default.useContext(OrderContext_1.default),{payment,expressPayments}=react_1.default.useContext(PaymentMethodChildrenContext_1.default),{payments,isGuest}=react_1.default.useContext(CustomerContext_1.default),{currentPaymentMethodId,config,paymentSource}=react_1.default.useContext(PaymentMethodContext_1.default),paymentResource="stripe_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const publishableKey=paymentSource?.publishable_key,clientSecret=paymentSource?.client_secret,paymentSourceId=((_a=order?.payment_source)===null||_a===void 0?void 0:_a.id)||paymentSource?.id,stripeConfig=config?(0,PaymentMethodReducer_1.getPaymentConfig)(paymentResource,config).stripePayment:{};console.log("stripeConfig",stripeConfig);const customerPayments=!(0,isEmpty_1.default)(payments)&&payments?payments.filter(customerPayment=>{var _a2;return((_a2=customerPayment.payment_source)===null||_a2===void 0?void 0:_a2.type)===paymentResource}):[];if(readonly||showCard){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value=Object.assign(Object.assign({},card),{showCard,handleEditClick,readonly});return(0,isEmpty_1.default)(card)?null:(0,jsx_runtime_1.jsx)(PaymentSourceContext_1.default.Provider,{value,children})}return!isGuest&&templateCustomerCards?(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[(0,isEmpty_1.default)(customerPayments)?null:(0,jsx_runtime_1.jsx)("div",{className:p.className,children:(0,jsx_runtime_1.jsx)(PaymentCardsTemplate_1.default,{paymentResource,customerPayments,children:templateCustomerCards})}),(0,jsx_runtime_1.jsx)(StripePayment_1.default,Object.assign({show,templateCustomerSaveToWallet,publishableKey,clientSecret,expressPayments,locale},stripeConfig))]}):publishableKey&&!loading&&paymentSourceId?(0,jsx_runtime_1.jsx)(StripePayment_1.default,Object.assign({show,publishableKey,clientSecret,locale,expressPayments},stripeConfig)):loaderComponent}exports.StripeGateway=StripeGateway,exports.default=StripeGateway;
|
|
@@ -1,14 +1,39 @@
|
|
|
1
1
|
import { type PaymentResource } from '../../reducers/PaymentMethodReducer';
|
|
2
|
-
import PaymentSourceContext from '../../context/PaymentSourceContext';
|
|
2
|
+
import PaymentSourceContext, { type IconBrand } from '../../context/PaymentSourceContext';
|
|
3
3
|
import { type ChildrenFunction } from '../../typings/index';
|
|
4
4
|
import { type CustomerPaymentSource } from '@commercelayer/sdk';
|
|
5
5
|
interface ChildrenProps extends Pick<Props, 'customerPayments'> {
|
|
6
6
|
PaymentSourceProvider: typeof PaymentSourceContext.Provider;
|
|
7
7
|
}
|
|
8
|
+
interface CustomerPayment extends CustomerPaymentSource {
|
|
9
|
+
/**
|
|
10
|
+
* Card details
|
|
11
|
+
*/
|
|
12
|
+
card?: {
|
|
13
|
+
/**
|
|
14
|
+
* Card brand
|
|
15
|
+
*/
|
|
16
|
+
brand: IconBrand;
|
|
17
|
+
/**
|
|
18
|
+
* Card last 4 digits
|
|
19
|
+
*/
|
|
20
|
+
last4: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Handle click event
|
|
24
|
+
*/
|
|
25
|
+
handleClick?: () => void;
|
|
26
|
+
}
|
|
8
27
|
export type CustomerCardsTemplateChildren = ChildrenFunction<ChildrenProps>;
|
|
9
28
|
interface Props {
|
|
10
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Customer payments
|
|
31
|
+
*/
|
|
32
|
+
customerPayments: CustomerPayment[];
|
|
11
33
|
children: CustomerCardsTemplateChildren;
|
|
34
|
+
/**
|
|
35
|
+
* Payment resource
|
|
36
|
+
*/
|
|
12
37
|
paymentResource: PaymentResource;
|
|
13
38
|
}
|
|
14
39
|
export default function PaymentCardsTemplate({ customerPayments, children, paymentResource }: Props): JSX.Element;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
type TEvent = 'open-cart';
|
|
2
|
+
declare function subscribe(eventName: TEvent, listener: EventListenerOrEventListenerObject): void;
|
|
3
|
+
declare function unsubscribe(eventName: TEvent, listener: EventListenerOrEventListenerObject): void;
|
|
4
|
+
declare function publish(eventName: TEvent, data?: any): void;
|
|
5
|
+
export { publish, subscribe, unsubscribe };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.unsubscribe=exports.subscribe=exports.publish=void 0;function subscribe(eventName,listener){document.addEventListener(eventName,listener)}exports.subscribe=subscribe;function unsubscribe(eventName,listener){document.removeEventListener(eventName,listener)}exports.unsubscribe=unsubscribe;function publish(eventName,data){const event=new CustomEvent(eventName,{detail:data});document.dispatchEvent(event)}exports.publish=publish;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type ApplicationType = 'checkout' | 'cart' | 'my-account';
|
|
2
|
+
type ApplicationTypeProps = {
|
|
3
|
+
applicationType: 'my-account';
|
|
4
|
+
orderId?: string;
|
|
5
|
+
} | {
|
|
6
|
+
applicationType: Omit<ApplicationType, 'my-account'>;
|
|
7
|
+
orderId: string;
|
|
8
|
+
};
|
|
9
|
+
interface TArgs {
|
|
10
|
+
accessToken: string;
|
|
11
|
+
slug: string;
|
|
12
|
+
domain: string;
|
|
13
|
+
}
|
|
14
|
+
type Props = TArgs & ApplicationTypeProps;
|
|
15
|
+
export declare function getApplicationLink({ orderId, accessToken, slug, domain, applicationType }: Props): string;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getApplicationLink=void 0;function getApplicationLink({orderId,accessToken,slug,domain,applicationType}){return`https://${slug}.${domain==="commercelayer.io"?"":"stg."}commercelayer.app/${applicationType.toString()}/${orderId??""}?accessToken=${accessToken}`}exports.getApplicationLink=getApplicationLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});function getCardDetails({paymentType,customerPayment}){var _a,_b,_c,_d,_e,_f,_g,_h,_j;switch(paymentType){case"checkout_com_payments":{const ps=customerPayment.payment_source,source=(_a=ps?.payment_response)===null||_a===void 0?void 0:_a.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=(_c=(_b=ps?.options)===null||_b===void 0?void 0:_b.card)!==null&&_c!==void 0?_c:(_d=ps?.payment_method)===null||_d===void 0?void 0:_d.card;if(source)return Object.assign({},source);break}case"braintree_payments":{const ps=customerPayment.payment_source,source=(_e=ps?.options)===null||_e===void 0?void 0:_e.card;if(source)return Object.assign({},source);break}case"adyen_payments":{const ps=customerPayment.payment_source,source=(_f=ps?.payment_request_data)===null||_f===void 0?void 0:_f.payment_method,authorized=((_g=ps?.payment_response)===null||_g===void 0?void 0:_g.resultCode)==="Authorised";if(source&&authorized){const brand=source.type==="scheme"?(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});function getCardDetails({paymentType,customerPayment}){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p;switch(paymentType){case"checkout_com_payments":{const ps=customerPayment.payment_source,source=(_a=ps?.payment_response)===null||_a===void 0?void 0:_a.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=(_c=(_b=ps?.options)===null||_b===void 0?void 0:_b.card)!==null&&_c!==void 0?_c:(_d=ps?.payment_method)===null||_d===void 0?void 0:_d.card;if(source)return Object.assign({},source);break}case"braintree_payments":{const ps=customerPayment.payment_source,source=(_e=ps?.options)===null||_e===void 0?void 0:_e.card;if(source)return Object.assign({},source);break}case"adyen_payments":{const ps=customerPayment.payment_source,source=(_f=ps?.payment_request_data)===null||_f===void 0?void 0:_f.payment_method,authorized=((_g=ps?.payment_response)===null||_g===void 0?void 0:_g.resultCode)==="Authorised",last4=(_m=(_k=(_j=(_h=ps?.payment_response)===null||_h===void 0?void 0:_h.additionalData)===null||_j===void 0?void 0:_j.cardSummary)!==null&&_k!==void 0?_k:(_l=ps?.payment_instrument)===null||_l===void 0?void 0:_l.card_last_digits)!==null&&_m!==void 0?_m:"****";if(source&&authorized){const brand=source.type==="scheme"?(_o=source.brand)!==null&&_o!==void 0?_o:"credit-card":source.type.replace("_account","");return Object.assign(Object.assign({},source),{last4,brand})}break}default:{const ps=customerPayment.payment_source,source=(_p=ps?.metadata)===null||_p===void 0?void 0:_p.card;if(source)return Object.assign({},source);break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****"}}exports.default=getCardDetails;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ChildrenFunction } from '../../typings/index';
|
|
2
|
+
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
3
|
+
/**
|
|
4
|
+
* The link href
|
|
5
|
+
*/
|
|
6
|
+
href: string;
|
|
7
|
+
/**
|
|
8
|
+
* The link status
|
|
9
|
+
*/
|
|
10
|
+
disabled: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
|
|
13
|
+
/**
|
|
14
|
+
* A render function to render your own custom component
|
|
15
|
+
*/
|
|
16
|
+
children?: ChildrenFunction<ChildrenProps>;
|
|
17
|
+
/**
|
|
18
|
+
* The label of the link
|
|
19
|
+
*/
|
|
20
|
+
label?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function MyAccountLink(props: Props): JSX.Element;
|
|
23
|
+
export default MyAccountLink;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";import jwt from"../../utils/jwt";export function MyAccountLink(props){const{label="Go to my account",children,...p}=props,{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null||endpoint==null)throw new Error("Cannot use `MyAccountLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint),disabled=!("owner"in jwt(accessToken)),href=getApplicationLink({slug,accessToken,applicationType:"my-account",domain}),parentProps={disabled,label,href,...p};function handleClick(e){disabled&&e.preventDefault()}return children?_jsx(Parent,{...parentProps,children}):_jsx("a",{"aria-disabled":disabled,onClick:handleClick,href,...p,children:label})}export default MyAccountLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import SkuListsContext from"../../context/SkuListsContext";import ExternalFunctionContext from"../../context/ExternalFunctionContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import SkuListsContext from"../../context/SkuListsContext";import ExternalFunctionContext from"../../context/ExternalFunctionContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import{getApplicationLink}from"../../utils/getApplicationLink";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{getDomain}from"../../utils/getDomain";import{publish}from"../../utils/events";export function AddToCartButton(props){const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,...p}=props,{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=useContext(ExternalFunctionContext),{skuLists}=useContext(SkuListsContext),{sku}=useContext(SkuChildrenContext),sCode=sku?.code??skuCode,handleClick=async()=>{const qty=quantity!=null?parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=skuLists?.[skuListId]?.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return await callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=await addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=getDomain(endpoint),orderId2=res?.orderId;hostedCartUrl&&orderId2?location.href=`https://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`:orderId2&&slug&&(location.href=getApplicationLink({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"}))}return publish("open-cart"),res}else if(url)return await callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))},parentProps={handleClick,label,...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{...p,onClick:()=>{handleClick()},children:label})}export default AddToCartButton;
|
|
@@ -1,12 +1,27 @@
|
|
|
1
1
|
import { type MouseEvent, type ReactNode } from 'react';
|
|
2
2
|
import { type ChildrenFunction } from '../../typings/index';
|
|
3
3
|
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
4
|
+
/**
|
|
5
|
+
* The url of the cart
|
|
6
|
+
*/
|
|
4
7
|
href: string;
|
|
8
|
+
/**
|
|
9
|
+
* Callback to dispatch the click event
|
|
10
|
+
* @param e: MouseEvent<HTMLAnchorElement>
|
|
11
|
+
* @returns Promise<void>
|
|
12
|
+
*/
|
|
5
13
|
handleClick?: (e: MouseEvent<HTMLAnchorElement>) => Promise<void>;
|
|
6
14
|
}
|
|
7
15
|
interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
|
|
8
16
|
children?: ChildrenFunction<ChildrenProps>;
|
|
17
|
+
/**
|
|
18
|
+
* Label to display
|
|
19
|
+
*/
|
|
9
20
|
label?: string | ReactNode;
|
|
21
|
+
/**
|
|
22
|
+
* The type of the cart. Defaults to undefined. If set to 'mini', the cart will open in a modal.
|
|
23
|
+
*/
|
|
24
|
+
type?: 'mini';
|
|
10
25
|
}
|
|
11
26
|
export declare function CartLink(props: Props): JSX.Element | null;
|
|
12
27
|
export default CartLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";import{publish}from"../../utils/events";export function CartLink(props){const{label,children,type,...p}=props,{order,createOrder}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null)throw new Error("Cannot use `CartLink` outside of `CommerceLayer`");if(endpoint==null)throw new Error("Cannot use `CartLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint),href=slug&&order?.id?getApplicationLink({slug,orderId:order?.id,accessToken,domain,applicationType:"cart"}):"",handleClick=async event=>{if(event.preventDefault(),type!=="mini")if(order?.id)location.href=href;else{const orderId=await createOrder();slug&&(location.href=getApplicationLink({slug,orderId,accessToken,domain,applicationType:"cart"}))}else publish("open-cart")},parentProps={handleClick,label,href,...p};return accessToken?children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,...p,onClick:e=>{handleClick(e)},children:label}):null}export default CartLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";export function CheckoutLink(props){const{label,hostedCheckout=!0,children,...p}=props,{order}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null||endpoint==null)throw new Error("Cannot use `CheckoutLink` outside of `CommerceLayer`");const
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";export function CheckoutLink(props){const{label,hostedCheckout=!0,children,...p}=props,{order}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null||endpoint==null)throw new Error("Cannot use `CheckoutLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint),href=hostedCheckout&&order?.id?getApplicationLink({slug,orderId:order?.id,accessToken,applicationType:"checkout",domain}):order?.checkout_url??"",parentProps={checkoutUrl:order?.checkout_url,hostedCheckout,label,href,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,...p,children:label})}export default CheckoutLink;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type CSSProperties } from 'react';
|
|
2
|
+
interface Styles {
|
|
3
|
+
cart?: CSSProperties;
|
|
4
|
+
container?: CSSProperties;
|
|
5
|
+
background?: CSSProperties;
|
|
6
|
+
}
|
|
7
|
+
interface Props extends Omit<JSX.IntrinsicElements['div'], 'children' | 'style'> {
|
|
8
|
+
/**
|
|
9
|
+
* The type of the cart. Defaults to undefined.
|
|
10
|
+
*/
|
|
11
|
+
type?: 'mini';
|
|
12
|
+
/**
|
|
13
|
+
* If true, the cart will open when a line item is added to the order clicking the add to cart button. Defaults to false.
|
|
14
|
+
*/
|
|
15
|
+
openAdd?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* The style of the cart.
|
|
18
|
+
*/
|
|
19
|
+
style?: Styles;
|
|
20
|
+
/**
|
|
21
|
+
* If true, the cart will be open. Defaults to false.
|
|
22
|
+
*/
|
|
23
|
+
open?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* A function that will be called when the cart is open and the background is clicked.
|
|
26
|
+
*/
|
|
27
|
+
handleOpen?: () => void;
|
|
28
|
+
}
|
|
29
|
+
export declare function HostedCart({ type, openAdd, style, open, handleOpen, ...props }: Props): JSX.Element | null;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";import useCustomContext from"../../utils/hooks/useCustomContext";import{useContext,useEffect,useState,useRef}from"react";import{iframeResizer}from"iframe-resizer";import{subscribe,unsubscribe}from"../../utils/events";const defaultIframeStyle={width:"1px",minWidth:"100%",minHeight:"100%",border:"none"},defaultContainerStyle={position:"fixed",top:"0",right:"-25rem",height:"100%",width:"23rem",transition:"right 0.5s ease-in-out",zIndex:"0"},defaultBackgroundStyle={opacity:"0",position:"fixed",top:"0",left:"0",height:"100%",width:"100vw",transition:"opacity 0.5s ease-in-out",zIndex:"-10",backgroundColor:"black"},defaultStyle={cart:defaultIframeStyle,container:defaultContainerStyle,background:defaultBackgroundStyle};export function HostedCart({type,openAdd=!1,style=defaultStyle,open=!1,handleOpen,...props}){const[isOpen,setOpen]=useState(!1),ref=useRef(null),{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"HostedCart",key:"accessToken"}),[src,setSrc]=useState();if(accessToken==null||endpoint==null)return null;const{order,createOrder}=useContext(OrderContext),{persistKey}=useContext(OrderStorageContext),{domain,slug}=getDomain(endpoint);async function setOrder(openCart){const orderId=localStorage.getItem(persistKey)??await createOrder();orderId!=null&&accessToken!=null&&(setSrc(getApplicationLink({slug,orderId,accessToken,domain,applicationType:"cart"})),openCart&&setTimeout(()=>{handleOpen!=null?handleOpen():setOpen(!0)},300))}function onMessage(data){switch(data.message.type){case"update":break;case"close":type==="mini"&&(handleOpen!=null?handleOpen():setOpen(!1));break;case"blur":type==="mini"&&isOpen&&ref.current?.focus();break}}return useEffect(()=>{const orderId=localStorage.getItem(persistKey);let ignore=!1;return open!=null&&open!==isOpen&&setOpen(open),openAdd&&type==="mini"&&subscribe("open-cart",()=>{console.log("open-cart by event",src,order?.id,orderId),src==null&&order?.id==null&&orderId==null?setOrder(!0):(src!=null&&ref.current!=null&&(ref.current.src=src),setTimeout(()=>{handleOpen!=null?handleOpen():setOpen(!0)},300))}),src==null&&order?.id==null&&orderId==null&&accessToken!=null&&!ignore&&isOpen?setOrder():src==null&&(order?.id!=null||orderId!=null)&&setSrc(getApplicationLink({slug,orderId:order?.id??orderId,accessToken,domain,applicationType:"cart"})),src!=null&&ref.current!=null&&(ref.current.src=src),()=>{ignore=!0,openAdd&&type==="mini"&&unsubscribe("open-cart",()=>{})}},[src,open,order?.id]),useEffect(()=>{ref.current!=null&&iframeResizer({checkOrigin:!1,bodyPadding:"20px",onMessage},ref.current)},[ref.current!=null]),src==null?null:type==="mini"?_jsxs(_Fragment,{children:[_jsx("div",{style:{...style.background,opacity:isOpen?"0.5":style.background?.opacity,zIndex:isOpen?"1":style.background?.zIndex},onClick:()=>{handleOpen!=null?handleOpen():setOpen(!1)}}),_jsx("div",{style:{...style.container,right:isOpen?"0":style.container?.right,zIndex:isOpen?"10":style.container?.zIndex},...props,children:_jsx("iframe",{title:"Cart",ref,style:style.cart,src,width:"100%",height:"100%"})})]}):_jsx("iframe",{title:"Cart",ref,style:style.cart,src,width:"100%",height:"100%"})}
|
|
@@ -3,11 +3,24 @@ import { type ChildrenFunction } from '../../typings/index';
|
|
|
3
3
|
import type { BaseError } from '../../typings/errors';
|
|
4
4
|
import type { Order } from '@commercelayer/sdk';
|
|
5
5
|
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
6
|
+
/**
|
|
7
|
+
* Callback function to place the order
|
|
8
|
+
*/
|
|
6
9
|
handleClick: () => Promise<void>;
|
|
7
10
|
}
|
|
8
11
|
interface Props extends Omit<JSX.IntrinsicElements['button'], 'children' | 'onClick'> {
|
|
9
12
|
children?: ChildrenFunction<ChildrenProps>;
|
|
13
|
+
/**
|
|
14
|
+
* The label of the button
|
|
15
|
+
*/
|
|
10
16
|
label?: string | ReactNode;
|
|
17
|
+
/**
|
|
18
|
+
* If false, the button doesn't place the order automatically. Default: true
|
|
19
|
+
*/
|
|
20
|
+
autoPlaceOrder?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Callback function that is fired when the button is clicked
|
|
23
|
+
*/
|
|
11
24
|
onClick?: (response: {
|
|
12
25
|
placed: boolean;
|
|
13
26
|
order?: Order;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&handleClick()},[options?.paypalPayerId,paymentType]),useEffect(()=>{paymentType==="stripe_payments"&&options?.stripe?.redirectStatus==="succeeded"&&order?.status&&["draft","pending"].includes(order?.status)&&handleClick()},[options?.stripe?.redirectStatus,paymentType]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status))if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&paymentSource!=null){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes||paymentType==="adyen_payments"&&order?.payment_source?.payment_response?.resultCode==="Authorised"&&ref?.current?.disabled===!1)&&handleClick()},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&handleClick()},[options?.checkoutCom,paymentType]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();let isValid=!0;setForceDisable(!0);const checkPaymentSource=await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}),card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit(checkPaymentSource),!isValid&&checkPaymentSource.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0);const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource});setForceDisable(!1),onClick&&placed&&onClick(placed)},disabledButton=disabled!==void 0?disabled:notPermitted,parentProps={...p,label,disabled:disabledButton,handleClick,ref};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:isFunction(label)?label():label})}export default PlaceOrderButton;
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),useEffect(()=>{paymentType==="stripe_payments"&&options?.stripe?.redirectStatus==="succeeded"&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.stripe?.redirectStatus,paymentType]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status))if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&paymentSource!=null){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder||paymentType==="adyen_payments"&&order?.payment_source?.payment_response?.resultCode==="Authorised"&&ref?.current?.disabled===!1&&autoPlaceOrder)&&handleClick()},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();let isValid=!0;setForceDisable(!0);const checkPaymentSource=await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}),card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit(checkPaymentSource),!isValid&&checkPaymentSource.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0);const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource});setForceDisable(!1),onClick&&placed&&onClick(placed)},disabledButton=disabled!==void 0?disabled:notPermitted,parentProps={...p,label,disabled:disabledButton,handleClick,ref};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:isFunction(label)?label():label})}export default PlaceOrderButton;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";import StripePayment from"../payment_source/StripePayment";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentSourceContext from"../../context/PaymentSourceContext";import{getPaymentConfig}from"../../reducers/PaymentMethodReducer";import getCardDetails from"../../utils/getCardDetails";import isEmpty from"lodash/isEmpty";import React from"react";import PaymentCardsTemplate from"../utils/PaymentCardsTemplate";export function StripeGateway(props){const{readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,loaderComponent,templateCustomerSaveToWallet,...p}=props,{order}=React.useContext(OrderContext),{payment,expressPayments}=React.useContext(PaymentMethodChildrenContext),{payments,isGuest}=React.useContext(CustomerContext),{currentPaymentMethodId,config,paymentSource}=React.useContext(PaymentMethodContext),paymentResource="stripe_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const publishableKey=paymentSource?.publishable_key,clientSecret=paymentSource?.client_secret,paymentSourceId=order?.payment_source?.id||paymentSource?.id,stripeConfig=config?getPaymentConfig(paymentResource,config):{},customerPayments=!isEmpty(payments)&&payments?payments.filter(customerPayment=>customerPayment.payment_source?.type===paymentResource):[];if(readonly||showCard){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value={...card,showCard,handleEditClick,readonly};return isEmpty(card)?null:_jsx(PaymentSourceContext.Provider,{value,children})}return!isGuest&&templateCustomerCards?_jsxs(_Fragment,{children:[isEmpty(customerPayments)?null:_jsx("div",{className:p.className,children:_jsx(PaymentCardsTemplate,{paymentResource,customerPayments,children:templateCustomerCards})}),_jsx(StripePayment,{show,templateCustomerSaveToWallet,publishableKey,clientSecret,expressPayments,locale,...stripeConfig})]}):publishableKey&&!loading&&paymentSourceId?_jsx(StripePayment,{show,publishableKey,clientSecret,locale,expressPayments,...stripeConfig}):loaderComponent}export default StripeGateway;
|
|
1
|
+
import{jsx as _jsx,Fragment as _Fragment,jsxs as _jsxs}from"react/jsx-runtime";import StripePayment from"../payment_source/StripePayment";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentSourceContext from"../../context/PaymentSourceContext";import{getPaymentConfig}from"../../reducers/PaymentMethodReducer";import getCardDetails from"../../utils/getCardDetails";import isEmpty from"lodash/isEmpty";import React from"react";import PaymentCardsTemplate from"../utils/PaymentCardsTemplate";export function StripeGateway(props){const{readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,loaderComponent,templateCustomerSaveToWallet,...p}=props,{order}=React.useContext(OrderContext),{payment,expressPayments}=React.useContext(PaymentMethodChildrenContext),{payments,isGuest}=React.useContext(CustomerContext),{currentPaymentMethodId,config,paymentSource}=React.useContext(PaymentMethodContext),paymentResource="stripe_payments",locale=order?.language_code;if(!readonly&&payment?.id!==currentPaymentMethodId)return null;const publishableKey=paymentSource?.publishable_key,clientSecret=paymentSource?.client_secret,paymentSourceId=order?.payment_source?.id||paymentSource?.id,stripeConfig=config?getPaymentConfig(paymentResource,config).stripePayment:{};console.log("stripeConfig",stripeConfig);const customerPayments=!isEmpty(payments)&&payments?payments.filter(customerPayment=>customerPayment.payment_source?.type===paymentResource):[];if(readonly||showCard){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType:paymentResource}),value={...card,showCard,handleEditClick,readonly};return isEmpty(card)?null:_jsx(PaymentSourceContext.Provider,{value,children})}return!isGuest&&templateCustomerCards?_jsxs(_Fragment,{children:[isEmpty(customerPayments)?null:_jsx("div",{className:p.className,children:_jsx(PaymentCardsTemplate,{paymentResource,customerPayments,children:templateCustomerCards})}),_jsx(StripePayment,{show,templateCustomerSaveToWallet,publishableKey,clientSecret,expressPayments,locale,...stripeConfig})]}):publishableKey&&!loading&&paymentSourceId?_jsx(StripePayment,{show,publishableKey,clientSecret,locale,expressPayments,...stripeConfig}):loaderComponent}export default StripeGateway;
|
|
@@ -1,14 +1,39 @@
|
|
|
1
1
|
import { type PaymentResource } from '../../reducers/PaymentMethodReducer';
|
|
2
|
-
import PaymentSourceContext from '../../context/PaymentSourceContext';
|
|
2
|
+
import PaymentSourceContext, { type IconBrand } from '../../context/PaymentSourceContext';
|
|
3
3
|
import { type ChildrenFunction } from '../../typings/index';
|
|
4
4
|
import { type CustomerPaymentSource } from '@commercelayer/sdk';
|
|
5
5
|
interface ChildrenProps extends Pick<Props, 'customerPayments'> {
|
|
6
6
|
PaymentSourceProvider: typeof PaymentSourceContext.Provider;
|
|
7
7
|
}
|
|
8
|
+
interface CustomerPayment extends CustomerPaymentSource {
|
|
9
|
+
/**
|
|
10
|
+
* Card details
|
|
11
|
+
*/
|
|
12
|
+
card?: {
|
|
13
|
+
/**
|
|
14
|
+
* Card brand
|
|
15
|
+
*/
|
|
16
|
+
brand: IconBrand;
|
|
17
|
+
/**
|
|
18
|
+
* Card last 4 digits
|
|
19
|
+
*/
|
|
20
|
+
last4: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Handle click event
|
|
24
|
+
*/
|
|
25
|
+
handleClick?: () => void;
|
|
26
|
+
}
|
|
8
27
|
export type CustomerCardsTemplateChildren = ChildrenFunction<ChildrenProps>;
|
|
9
28
|
interface Props {
|
|
10
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Customer payments
|
|
31
|
+
*/
|
|
32
|
+
customerPayments: CustomerPayment[];
|
|
11
33
|
children: CustomerCardsTemplateChildren;
|
|
34
|
+
/**
|
|
35
|
+
* Payment resource
|
|
36
|
+
*/
|
|
12
37
|
paymentResource: PaymentResource;
|
|
13
38
|
}
|
|
14
39
|
export default function PaymentCardsTemplate({ customerPayments, children, paymentResource }: Props): JSX.Element;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
type TEvent = 'open-cart';
|
|
2
|
+
declare function subscribe(eventName: TEvent, listener: EventListenerOrEventListenerObject): void;
|
|
3
|
+
declare function unsubscribe(eventName: TEvent, listener: EventListenerOrEventListenerObject): void;
|
|
4
|
+
declare function publish(eventName: TEvent, data?: any): void;
|
|
5
|
+
export { publish, subscribe, unsubscribe };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function subscribe(eventName,listener){document.addEventListener(eventName,listener)}function unsubscribe(eventName,listener){document.removeEventListener(eventName,listener)}function publish(eventName,data){const event=new CustomEvent(eventName,{detail:data});document.dispatchEvent(event)}export{publish,subscribe,unsubscribe};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type ApplicationType = 'checkout' | 'cart' | 'my-account';
|
|
2
|
+
type ApplicationTypeProps = {
|
|
3
|
+
applicationType: 'my-account';
|
|
4
|
+
orderId?: string;
|
|
5
|
+
} | {
|
|
6
|
+
applicationType: Omit<ApplicationType, 'my-account'>;
|
|
7
|
+
orderId: string;
|
|
8
|
+
};
|
|
9
|
+
interface TArgs {
|
|
10
|
+
accessToken: string;
|
|
11
|
+
slug: string;
|
|
12
|
+
domain: string;
|
|
13
|
+
}
|
|
14
|
+
type Props = TArgs & ApplicationTypeProps;
|
|
15
|
+
export declare function getApplicationLink({ orderId, accessToken, slug, domain, applicationType }: Props): string;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function getApplicationLink({orderId,accessToken,slug,domain,applicationType}){return`https://${slug}.${domain==="commercelayer.io"?"":"stg."}commercelayer.app/${applicationType.toString()}/${orderId??""}?accessToken=${accessToken}`}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export default function getCardDetails({paymentType,customerPayment}){switch(paymentType){case"checkout_com_payments":{const source=customerPayment.payment_source?.payment_response?.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=ps?.options?.card??ps?.payment_method?.card;if(source)return{...source};break}case"braintree_payments":{const source=customerPayment.payment_source?.options?.card;if(source)return{...source};break}case"adyen_payments":{const ps=customerPayment.payment_source,source=ps?.payment_request_data?.payment_method,authorized=ps?.payment_response?.resultCode==="Authorised";if(source&&authorized){const brand=source.type==="scheme"?source.brand??"credit-card":source.type.replace("_account","");return{...source,brand}}break}default:{const source=customerPayment.payment_source?.metadata?.card;if(source)return{...source};break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****"}}
|
|
1
|
+
export default function getCardDetails({paymentType,customerPayment}){switch(paymentType){case"checkout_com_payments":{const source=customerPayment.payment_source?.payment_response?.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=ps?.options?.card??ps?.payment_method?.card;if(source)return{...source};break}case"braintree_payments":{const source=customerPayment.payment_source?.options?.card;if(source)return{...source};break}case"adyen_payments":{const ps=customerPayment.payment_source,source=ps?.payment_request_data?.payment_method,authorized=ps?.payment_response?.resultCode==="Authorised",last4=ps?.payment_response?.additionalData?.cardSummary??ps?.payment_instrument?.card_last_digits??"****";if(source&&authorized){const brand=source.type==="scheme"?source.brand??"credit-card":source.type.replace("_account","");return{...source,last4,brand}}break}default:{const source=customerPayment.payment_source?.metadata?.card;if(source)return{...source};break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****"}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commercelayer/react-components",
|
|
3
|
-
"version": "4.5.0-beta.
|
|
3
|
+
"version": "4.5.0-beta.3",
|
|
4
4
|
"description": "The Official Commerce Layer React Components",
|
|
5
5
|
"main": "lib/cjs/index.js",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -172,9 +172,11 @@
|
|
|
172
172
|
"@stripe/react-stripe-js": "^2.1.0",
|
|
173
173
|
"@stripe/stripe-js": "^1.54.0",
|
|
174
174
|
"@tanstack/react-table": "^8.9.2",
|
|
175
|
+
"@types/iframe-resizer": "^3.5.9",
|
|
175
176
|
"axios": "^1.4.0",
|
|
176
177
|
"braintree-web": "^3.94.0",
|
|
177
178
|
"frames-react": "^1.1.0",
|
|
179
|
+
"iframe-resizer": "^4.3.6",
|
|
178
180
|
"jwt-decode": "^3.1.2",
|
|
179
181
|
"lodash": "^4.17.21",
|
|
180
182
|
"rapid-form": "^2.1.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});function getCartLink({orderId,accessToken,slug,domain}){return`https://${slug}.${domain==="commercelayer.io"?"":"stg."}commercelayer.app/cart/${orderId}?accessToken=${accessToken}`}exports.default=getCartLink;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export default function getCartLink({orderId,accessToken,slug,domain}){return`https://${slug}.${domain==="commercelayer.io"?"":"stg."}commercelayer.app/cart/${orderId}?accessToken=${accessToken}`}
|