@commercelayer/react-components 4.23.2 → 4.23.3-beta.0

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.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;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")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent");function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(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});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(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,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e=options?.adyen)===null||_e===void 0)&&_e.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_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(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&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)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),(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 _a2,_b2,_c2,_d2,_e;if(e?.preventDefault(),e?.stopPropagation(),order?.status==="placed"){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e=checkPaymentSource?.payment_response)===null||_e===void 0?void 0:_e.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});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:labelButton}))}exports.default=PlaceOrderButton;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;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")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent");function PlaceOrderButton(props){var _a,_b,_c,_d,_e;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(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});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(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,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.checkPaymentIntent)({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}});getPaymentIntent()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e2,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e2=options?.adyen)===null||_e2===void 0)&&_e2.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_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(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&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)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2;if(paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentResponse=(_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.payment_response;((_c2=paymentResponse?.status)===null||_c2===void 0?void 0:_c2.toLowerCase())==="pending"&&setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}).then(res=>{var _a3;const paymentStatus2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.status;paymentStatus2.toLowerCase()==="authorized"?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})}},[options?.checkoutCom,paymentType,(_e=order?.payment_source)===null||_e===void 0?void 0:_e.id]),(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 _a2,_b2,_c2,_d2,_e2,_f,_g,_h,_j,_k;e?.preventDefault(),e?.stopPropagation();const isAlreadyPlaced=order?.status==="placed",isDraftOrder=order?.status==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]});return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e2=checkPaymentSource?.payment_response)===null||_e2===void 0?void 0:_e2.resultCode)==="Authorised"&&(isValid=!0)):!((_f=currentPaymentMethodRef?.current)===null||_f===void 0)&&_f.onsubmit&&(!((_g=options?.checkoutCom)===null||_g===void 0)&&_g.session_id)&&((_j=(_h=checkPaymentSource?.payment_response)===null||_h===void 0?void 0:_h.status)===null||_j===void 0?void 0:_j.toLowerCase())==="declined"?isValid=yield(_k=currentPaymentMethodRef.current)===null||_k===void 0?void 0:_k.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId}));placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))}),disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});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:labelButton}))}exports.default=PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=(0,jwt_1.jwt)(accessToken).test?"sandbox":"production",locale=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){(yield window.CheckoutWebComponents({appearance:Object.assign({},options?.appearance),showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3,_b2;const element=(_a3=ref.current)===null||_a3===void 0?void 0:_a3.elements,savePaymentSourceToCustomerWallet=(_b2=element?.save_payment_source_to_customer_wallet)===null||_b2===void 0?void 0:_b2.checked;savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=yield component.tokenize(),token=data?.token,paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1}),setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",error,"Component",component.type)}})).create("flow").mount(document.getElementById("flow-container"))}))()}}},[loaded,(_b=order?.payment_source)===null||_b===void 0?void 0:_b.id,accessToken]),loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})})),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=(0,jwt_1.jwt)(accessToken).test?"sandbox":"production",locale=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){(yield window.CheckoutWebComponents({appearance:Object.assign({},options?.appearance),showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3,_b2;const element=(_a3=ref.current)===null||_a3===void 0?void 0:_a3.elements,savePaymentSourceToCustomerWallet=(_b2=element?.save_payment_source_to_customer_wallet)===null||_b2===void 0?void 0:_b2.checked;savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=yield component.tokenize(),token=data?.token,paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1}),setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:(component,paymentResponse)=>tslib_1.__awaiter(this,void 0,void 0,function*(){console.log("onPaymentCompleted -----",{paymentResponse,component,ps});const paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}});console.log("paymentSource",{paymentSource})})})).create("flow").mount(document.getElementById("flow-container"))}))()}}},[loaded,(_b=order?.payment_source)===null||_b===void 0?void 0:_b.id,accessToken]),loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})})),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
@@ -12,7 +12,7 @@ export interface PlaceOrderOptions {
12
12
  redirectResult?: string;
13
13
  };
14
14
  checkoutCom?: {
15
- session_id: string;
15
+ session_id: string | undefined;
16
16
  };
17
17
  stripe?: {
18
18
  /**
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d,_e,_f,_g;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_b=options?.checkoutCom)===null||_b===void 0)&&_b.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0});if(((_c=payment?.payment_response)===null||_c===void 0?void 0:_c.status)!=="Authorized"){const[action]=((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_e=ps?.options)===null||_e===void 0?void 0:_e.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_f=order?.total_amount_cents)!==null&&_f!==void 0?_f:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_g=orderUpdated?.total_amount_cents)!==null&&_g!==void 0?_g:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_b=ps?.options)===null||_b===void 0?void 0:_b.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_c=order?.total_amount_cents)!==null&&_c!==void 0?_c:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_d=orderUpdated?.total_amount_cents)!==null&&_d!==void 0?_d:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- 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";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=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});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(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(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&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"&&resultCode&&ref?.current?.disabled===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),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=>{if(e?.preventDefault(),e?.stopPropagation(),order?.status==="placed"){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,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({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ 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";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=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});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(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(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&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"&&resultCode&&ref?.current?.disabled===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&order?.payment_source?.payment_response?.status?.toLowerCase()==="pending"&&setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}).then(res=>{const paymentStatus2=res?.payment_response?.status;paymentStatus2.toLowerCase()==="authorized"?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))})},[options?.checkoutCom,paymentType,order?.payment_source?.id]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const isAlreadyPlaced=order?.status==="placed",isDraftOrder=order?.status==="draft";if(isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]});return}setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,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({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",error,"Component",component.type)}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",{error},"Component",component.type)},onPaymentCompleted:async(component,paymentResponse)=>{console.log("onPaymentCompleted -----",{paymentResponse,component,ps});const paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token:paymentResponse.id,_authorize:!0}});console.log("paymentSource",{paymentSource})}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
@@ -12,7 +12,7 @@ export interface PlaceOrderOptions {
12
12
  redirectResult?: string;
13
13
  };
14
14
  checkoutCom?: {
15
- session_id: string;
15
+ session_id: string | undefined;
16
16
  };
17
17
  stripe?: {
18
18
  /**
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
2
+ import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.23.2",
3
+ "version": "4.23.3-beta.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",