@commercelayer/react-components 4.28.8 → 4.29.0-beta.1
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/errors/Errors.d.ts +6 -6
- package/lib/cjs/components/errors/Errors.js +1 -1
- package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
- package/lib/cjs/components/payment_gateways/PaymentGateway.js +1 -1
- package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
- package/lib/cjs/components/utils/getAllErrors.d.ts +4 -4
- package/lib/cjs/reducers/OrderReducer.d.ts +3 -1
- package/lib/cjs/reducers/OrderReducer.js +1 -1
- package/lib/cjs/reducers/PaymentMethodReducer.d.ts +7 -4
- package/lib/cjs/reducers/PaymentMethodReducer.js +1 -1
- package/lib/cjs/typings/errors.d.ts +5 -2
- package/lib/esm/components/errors/Errors.d.ts +6 -6
- package/lib/esm/components/errors/Errors.js +1 -1
- package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
- package/lib/esm/components/payment_gateways/PaymentGateway.js +1 -1
- package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
- package/lib/esm/components/utils/getAllErrors.d.ts +4 -4
- package/lib/esm/reducers/OrderReducer.d.ts +3 -1
- package/lib/esm/reducers/OrderReducer.js +1 -1
- package/lib/esm/reducers/PaymentMethodReducer.d.ts +7 -4
- package/lib/esm/reducers/PaymentMethodReducer.js +1 -1
- package/lib/esm/typings/errors.d.ts +5 -2
- package/package.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type JSX } from
|
|
2
|
-
import type { CodeErrorType } from
|
|
3
|
-
import type { ChildrenFunction } from
|
|
4
|
-
export type TResourceError =
|
|
5
|
-
type ErrorChildrenComponentProps = ChildrenFunction<Omit<TErrorComponent,
|
|
1
|
+
import { type JSX } from "react";
|
|
2
|
+
import type { CodeErrorType } from "../../typings/errors";
|
|
3
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
4
|
+
export type TResourceError = "addresses" | "billing_address" | "gift_cards" | "gift_card_or_coupon_code" | "line_items" | "orders" | "payment_methods" | "prices" | "shipments" | "shipping_address" | "customer_address" | "sku_options" | "variant" | "in_stock_subscriptions";
|
|
5
|
+
type ErrorChildrenComponentProps = ChildrenFunction<Omit<TErrorComponent, "children"> & {
|
|
6
6
|
errors: string[];
|
|
7
7
|
}>;
|
|
8
|
-
export interface TErrorComponent extends Omit<JSX.IntrinsicElements[
|
|
8
|
+
export interface TErrorComponent extends Omit<JSX.IntrinsicElements["span"], "children"> {
|
|
9
9
|
/**
|
|
10
10
|
* Resource which get the error
|
|
11
11
|
*/
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Errors=Errors;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Errors=Errors;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),getAllErrors_1=tslib_1.__importDefault(require("../utils/getAllErrors")),AddressContext_1=tslib_1.__importDefault(require("../../context/AddressContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),GiftCardContext_1=tslib_1.__importDefault(require("../../context/GiftCardContext")),InStockSubscriptionContext_1=tslib_1.__importDefault(require("../../context/InStockSubscriptionContext")),LineItemChildrenContext_1=tslib_1.__importDefault(require("../../context/LineItemChildrenContext")),LineItemContext_1=tslib_1.__importDefault(require("../../context/LineItemContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),ShipmentContext_1=tslib_1.__importDefault(require("../../context/ShipmentContext"));function Errors(props){const{children,messages=[],resource,field,...p}=props,{payment}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{errors:orderErrors}=(0,react_1.useContext)(OrderContext_1.default),{errors:giftCardErrors}=(0,react_1.useContext)(GiftCardContext_1.default),{errors:lineItemErrors}=(0,react_1.useContext)(LineItemContext_1.default),{errors:addressErrors}=(0,react_1.useContext)(AddressContext_1.default),{errors:customerErrors}=(0,react_1.useContext)(CustomerContext_1.default),{errors:shipmentErrors}=(0,react_1.useContext)(ShipmentContext_1.default),{errors:inStockSubscriptionErrors}=(0,react_1.useContext)(InStockSubscriptionContext_1.default),{errors:paymentMethodErrors,currentPaymentMethodType,currentPaymentMethodId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{lineItem}=(0,react_1.useContext)(LineItemChildrenContext_1.default),allErrors=(0,react_1.useMemo)(()=>[...giftCardErrors||[],...orderErrors||[],...lineItemErrors||[],...customerErrors||[],...shipmentErrors||[],...inStockSubscriptionErrors||[],...paymentMethodErrors?.filter(v=>v.field===currentPaymentMethodType&&payment?.id===currentPaymentMethodId)||[]],[giftCardErrors,orderErrors,lineItemErrors,customerErrors,shipmentErrors,inStockSubscriptionErrors,paymentMethodErrors]).filter((v,k,a)=>v?.code!==a[k-1]?.code),addressesErrors=(0,react_1.useMemo)(()=>[...addressErrors||[]],[addressErrors]),msgErrors=(0,getAllErrors_1.default)({allErrors:[...allErrors,...addressesErrors],field,messages,props:p,lineItem,resource,returnHtml:!children}),parentProps={messages,resource,field,errors:msgErrors,...p};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:msgErrors})}exports.default=Errors;
|
|
@@ -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"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{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),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase(),card=(0,getCardDetails_1.default)({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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),(0,react_1.useEffect)(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.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(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()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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 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"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase(),card=paymentType&&(0,getCardDetails_1.default)({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&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("button",{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"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{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),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId,errors:paymentMethodErrors}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase(),card=(0,getCardDetails_1.default)({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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),(0,react_1.useEffect)(()=>{(errors&&errors.length>0||paymentMethodErrors&&paymentMethodErrors.length>0)&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors?.length,paymentMethodErrors?.length]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.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(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()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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 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"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase(),card=paymentType&&(0,getCardDetails_1.default)({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&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("button",{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.PaymentGateway=PaymentGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),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")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),AdyenGateway_1=tslib_1.__importDefault(require("./AdyenGateway")),BraintreeGateway_1=tslib_1.__importDefault(require("./BraintreeGateway")),CheckoutComGateway_1=tslib_1.__importDefault(require("./CheckoutComGateway")),ExternalGateway_1=tslib_1.__importDefault(require("./ExternalGateway")),KlarnaGateway_1=tslib_1.__importDefault(require("./KlarnaGateway")),PaypalGateway_1=tslib_1.__importDefault(require("./PaypalGateway")),StripeGateway_1=tslib_1.__importDefault(require("./StripeGateway")),WireTransferGateway_1=tslib_1.__importDefault(require("./WireTransferGateway"));function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=(0,getLoaderComponent_1.default)(loader),[loading,setLoading]=(0,react_1.useState)(!0),{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;(0,react_1.useEffect)(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=(0,getPaymentAttributes_1.getStripeAttributes)(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource]),(0,react_1.useEffect)(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return(0,jsx_runtime_1.jsx)(AdyenGateway_1.default,{...gatewayConfig,children});case"braintree_payments":return(0,jsx_runtime_1.jsx)(BraintreeGateway_1.default,{...gatewayConfig,children});case"checkout_com_payments":return(0,jsx_runtime_1.jsx)(CheckoutComGateway_1.default,{...gatewayConfig,children});case"external_payments":return(0,jsx_runtime_1.jsx)(ExternalGateway_1.default,{...gatewayConfig,children});case"klarna_payments":return(0,jsx_runtime_1.jsx)(KlarnaGateway_1.default,{...gatewayConfig,children});case"stripe_payments":return(0,jsx_runtime_1.jsx)(StripeGateway_1.default,{...gatewayConfig,children});case"wire_transfers":return(0,jsx_runtime_1.jsx)(WireTransferGateway_1.default,{...gatewayConfig,children});case"paypal_payments":return(0,jsx_runtime_1.jsx)(PaypalGateway_1.default,{...gatewayConfig,children});default:return null}}exports.default=PaymentGateway;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentGateway=PaymentGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),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")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),AdyenGateway_1=tslib_1.__importDefault(require("./AdyenGateway")),BraintreeGateway_1=tslib_1.__importDefault(require("./BraintreeGateway")),CheckoutComGateway_1=tslib_1.__importDefault(require("./CheckoutComGateway")),ExternalGateway_1=tslib_1.__importDefault(require("./ExternalGateway")),KlarnaGateway_1=tslib_1.__importDefault(require("./KlarnaGateway")),PaypalGateway_1=tslib_1.__importDefault(require("./PaypalGateway")),StripeGateway_1=tslib_1.__importDefault(require("./StripeGateway")),WireTransferGateway_1=tslib_1.__importDefault(require("./WireTransferGateway"));function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=(0,getLoaderComponent_1.default)(loader),[loading,setLoading]=(0,react_1.useState)(!0),{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;(0,react_1.useEffect)(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=(0,getPaymentAttributes_1.getStripeAttributes)(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1),paymentSource||setLoading(!0)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource?.id]),(0,react_1.useEffect)(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return(0,jsx_runtime_1.jsx)(AdyenGateway_1.default,{...gatewayConfig,children});case"braintree_payments":return(0,jsx_runtime_1.jsx)(BraintreeGateway_1.default,{...gatewayConfig,children});case"checkout_com_payments":return(0,jsx_runtime_1.jsx)(CheckoutComGateway_1.default,{...gatewayConfig,children});case"external_payments":return(0,jsx_runtime_1.jsx)(ExternalGateway_1.default,{...gatewayConfig,children});case"klarna_payments":return(0,jsx_runtime_1.jsx)(KlarnaGateway_1.default,{...gatewayConfig,children});case"stripe_payments":return(0,jsx_runtime_1.jsx)(StripeGateway_1.default,{...gatewayConfig,children});case"wire_transfers":return(0,jsx_runtime_1.jsx)(WireTransferGateway_1.default,{...gatewayConfig,children});case"paypal_payments":return(0,jsx_runtime_1.jsx)(PaypalGateway_1.default,{...gatewayConfig,children});default:return null}}exports.default=PaymentGateway;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),auto_1=require("@adyen/adyen-web/auto"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),getPublicIp_1=require("../../utils/getPublicIp"),hasSubscriptions_1=require("../../utils/hasSubscriptions"),localStorage_1=require("../../utils/localStorage"),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),[giftcardError,setGiftcardError]=(0,react_1.useState)(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder,getOrderByFields}=(0,react_1.useContext)(OrderContext_1.default),authConfig=(0,react_1.useContext)(CommerceLayerContext_1.default),{placeOrderButtonRef,setPlaceOrder,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await(0,getPublicIp_1.getPublicIP)(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...(0,browserInfo_1.default)()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return(0,react_1.useEffect)(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),auto_1=require("@adyen/adyen-web/auto"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),getPublicIp_1=require("../../utils/getPublicIp"),hasSubscriptions_1=require("../../utils/hasSubscriptions"),localStorage_1=require("../../utils/localStorage"),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),[giftcardError,setGiftcardError]=(0,react_1.useState)(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder,getOrderByFields}=(0,react_1.useContext)(OrderContext_1.default),authConfig=(0,react_1.useContext)(CommerceLayerContext_1.default),{placeOrderButtonRef,setPlaceOrder,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await(0,getPublicIp_1.getPublicIP)(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...(0,browserInfo_1.default)()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return(0,react_1.useEffect)(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1&&id.search("giftcard")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type { LineItem } from
|
|
2
|
-
import type { BaseError } from '../../typings/errors';
|
|
3
|
-
import type { TResourceError } from '../errors/Errors';
|
|
1
|
+
import type { LineItem } from "@commercelayer/sdk";
|
|
4
2
|
import type { JSX } from "react";
|
|
3
|
+
import type { TResourceError } from "../errors/Errors";
|
|
4
|
+
import type { BaseError } from "../../typings/errors";
|
|
5
5
|
export interface AllErrorsParams {
|
|
6
6
|
allErrors: BaseError[];
|
|
7
7
|
messages: BaseError[];
|
|
8
8
|
field?: string;
|
|
9
|
-
props: Omit<JSX.IntrinsicElements[
|
|
9
|
+
props: Omit<JSX.IntrinsicElements["span"], "ref">;
|
|
10
10
|
lineItem?: LineItem | null;
|
|
11
11
|
resource?: TResourceError;
|
|
12
12
|
returnHtml?: boolean;
|
|
@@ -64,7 +64,9 @@ export declare function getOrderByFields(params: {
|
|
|
64
64
|
}): Promise<Order>;
|
|
65
65
|
export declare function updateOrder({ id, attributes, dispatch, config, include, state, }: UpdateOrderArgs): Promise<{
|
|
66
66
|
success: boolean;
|
|
67
|
-
error?:
|
|
67
|
+
error?: {
|
|
68
|
+
errors: BaseError[];
|
|
69
|
+
};
|
|
68
70
|
order?: Order;
|
|
69
71
|
}>;
|
|
70
72
|
interface TResourceRequest {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.saveAddressToCustomerAddressBook=exports.unsetOrderState=exports.setOrder=exports.getApiOrder=void 0,exports.createOrder=createOrder,exports.getOrderByFields=getOrderByFields,exports.updateOrder=updateOrder,exports.paymentSourceRequest=paymentSourceRequest,exports.addResourceToInclude=addResourceToInclude,exports.addToCart=addToCart,exports.setOrderErrors=setOrderErrors,exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode,exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),events_1=require("../utils/events"),getApplicationLink_1=require("../utils/getApplicationLink"),getDomain_1=require("../utils/getDomain"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),localStorage_1=require("../utils/localStorage"),organization_1=require("../utils/organization"),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}};exports.getApiOrder=getApiOrder;async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await(0,exports.getApiOrder)({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await(0,exports.getApiOrder)({id,...params})}else await(0,exports.getApiOrder)({id,...params,state});if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.orderInitialState=exports.saveAddressToCustomerAddressBook=exports.unsetOrderState=exports.setOrder=exports.getApiOrder=void 0,exports.createOrder=createOrder,exports.getOrderByFields=getOrderByFields,exports.updateOrder=updateOrder,exports.paymentSourceRequest=paymentSourceRequest,exports.addResourceToInclude=addResourceToInclude,exports.addToCart=addToCart,exports.setOrderErrors=setOrderErrors,exports.setGiftCardOrCouponCode=setGiftCardOrCouponCode,exports.removeGiftCardOrCouponCode=removeGiftCardOrCouponCode;const tslib_1=require("tslib"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),events_1=require("../utils/events"),getApplicationLink_1=require("../utils/getApplicationLink"),getDomain_1=require("../utils/getDomain"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),localStorage_1=require("../utils/localStorage"),organization_1=require("../utils/organization"),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Create order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors,dispatch});return}};exports.getApiOrder=getApiOrder;async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?(0,getSdk_1.default)(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id},currentTotalAmountWithTaxesCents=state?.order?.total_amount_with_taxes_cents;await sdk.orders.update(resource,{include});let order=await(0,exports.getApiOrder)({id,config,dispatch,state});const newTotalAmountWithTaxesCents=order?.total_amount_with_taxes_cents;return currentTotalAmountWithTaxesCents!==newTotalAmountWithTaxesCents&&order?.payment_source?.id&&(await sdk.orders.update({id,payment_source:null}),order=await(0,exports.getApiOrder)({id,config,dispatch,state})),dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Update order",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1,error}}}async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?(0,getSdk_1.default)(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};exports.setOrder=setOrder;function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=(0,getSdk_1.default)(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await(0,exports.getApiOrder)({id,...params})}else await(0,exports.getApiOrder)({id,...params,state});if(!(0,isEmpty_1.default)(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=(0,getDomain_1.getDomain)(config.endpoint),href=(0,getApplicationLink_1.getApplicationLink)({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await(0,organization_1.getOrganizationConfig)({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&(0,events_1.publish)("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=(0,getErrors_1.default)({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&(0,getErrors_1.setErrors)({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};exports.unsetOrderState=unsetOrderState;function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;(0,localStorage_1.setCustomerOrderParam)(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};exports.saveAddressToCustomerAddressBook=saveAddressToCustomerAddressBook;async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}exports.orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,actionType);exports.default=orderReducer;
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
+
import type { AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, KlarnaPayment, Order, PaymentMethod, PaypalPayment, StripePayment, WireTransfer } from "@commercelayer/sdk";
|
|
2
|
+
import type { Dispatch, MutableRefObject } from "react";
|
|
1
3
|
import type { AdyenPaymentConfig } from "../components/payment_source/AdyenPayment";
|
|
2
4
|
import type { BraintreeConfig } from "../components/payment_source/BraintreePayment";
|
|
5
|
+
import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
|
|
6
|
+
import type { ExternalPaymentConfig } from "../components/payment_source/ExternalPayment";
|
|
3
7
|
import type { PaypalConfig } from "../components/payment_source/PaypalPayment";
|
|
4
8
|
import type { StripeConfig } from "../components/payment_source/StripePayment";
|
|
5
9
|
import type { WireTransferConfig } from "../components/payment_source/WireTransferPayment";
|
|
6
10
|
import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
|
|
7
11
|
import type { getOrderContext, updateOrder } from "./OrderReducer";
|
|
8
12
|
import type { BaseError } from "../typings/errors";
|
|
9
|
-
import type { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from "@commercelayer/sdk";
|
|
10
|
-
import type { Dispatch, MutableRefObject } from "react";
|
|
11
|
-
import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
|
|
12
|
-
import type { ExternalPaymentConfig } from "../components/payment_source/ExternalPayment";
|
|
13
13
|
import type { ResourceKeys } from "../utils/getPaymentAttributes";
|
|
14
14
|
export type PaymentSourceType = Order["payment_source"];
|
|
15
15
|
interface Card {
|
|
@@ -110,6 +110,9 @@ interface TSetPaymentMethodParams {
|
|
|
110
110
|
export declare function setPaymentMethod({ config, dispatch, order, paymentMethodId, updateOrder, setOrderErrors, paymentResource, }: TSetPaymentMethodParams): Promise<{
|
|
111
111
|
success: boolean;
|
|
112
112
|
order?: Order;
|
|
113
|
+
error?: {
|
|
114
|
+
errors: BaseError[];
|
|
115
|
+
};
|
|
113
116
|
}>;
|
|
114
117
|
type PaymentSourceTypes = (StripePayment & WireTransfer) | (StripePayment | WireTransfer);
|
|
115
118
|
export type SetPaymentSourceResponse = {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=void 0,exports.setLoading=setLoading,exports.setPaymentMethod=setPaymentMethod,exports.setPaymentSource=setPaymentSource,exports.getPaymentConfig=getPaymentConfig;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=void 0,exports.setLoading=setLoading,exports.setPaymentMethod=setPaymentMethod,exports.setPaymentSource=setPaymentSource,exports.getPaymentConfig=getPaymentConfig;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),pick_1=require("../utils/pick"),replace_1=require("../utils/replace"),snakeToCamelCase_1=require("../utils/snakeToCamelCase");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};exports.getPaymentMethods=getPaymentMethods;async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};if(updateOrder!=null){const currentOrder=await updateOrder({id:order.id,attributes});if(!currentOrder.success&¤tOrder.error){const errors=(0,getErrors_1.default)({error:currentOrder.error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),setOrderErrors?.(errors),response}response=currentOrder}dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource}),expiredErrors=errors.filter(v=>v?.meta?.error==="expired");if(expiredErrors.length>0&&order&&config&&(console.error("Set payment source - expired:",expiredErrors),(0,exports.destroyPaymentSource)({paymentSourceId:order.payment_source?.id||"",paymentResource,dispatch})),errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}}const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await(0,getSdk_1.default)(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}};exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch?.({type:"setPaymentSource",payload:{paymentSource:void 0}})};exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { TResourceError } from
|
|
2
|
-
export type CodeErrorType =
|
|
1
|
+
import type { TResourceError } from "../components/errors/Errors";
|
|
2
|
+
export type CodeErrorType = "EMPTY_ERROR" | "FILTER_NOT_ALLOWED" | "FORBIDDEN" | "INTERNAL_SERVER_ERROR" | "INVALID_DATA_FORMAT" | "INVALID_FIELD" | "INVALID_FIELD_FORMAT" | "INVALID_FIELD_VALUE" | "INVALID_FILTERS_SYNTAX" | "INVALID_FILTER_VALUE" | "INVALID_INCLUDE" | "INVALID_LINKS_OBJECT" | "INVALID_PAGE_OBJECT" | "INVALID_PAGE_VALUE" | "INVALID_RESOURCE" | "INVALID_RESOURCE_ID" | "INVALID_SORT_CRITERIA" | "INVALID_TOKEN" | "KEY_NOT_INCLUDED_IN_URL" | "KEY_ORDER_MISMATCH" | "LOCKED" | "NOT_ACCEPTABLE" | "OUT_OF_STOCK" | "PARAM_MISSING" | "PARAM_NOT_ALLOWED" | "PAYMENT_NOT_APPROVED_FOR_EXECUTION" | "PAYMENT_INTENT_AUTHENTICATION_FAILURE" | "RECORD_NOT_FOUND" | "RECORD_NOT_FOUND" | "RELATION_EXISTS" | "NO_SHIPPING_METHODS" | "SAVE_FAILED" | "TYPE_MISMATCH" | "UNAUTHORIZED" | "UNSUPPORTED_MEDIA_TYPE" | "VALIDATION_ERROR";
|
|
3
3
|
export interface BaseError {
|
|
4
4
|
code: CodeErrorType;
|
|
5
5
|
message: string;
|
|
@@ -9,6 +9,9 @@ export interface BaseError {
|
|
|
9
9
|
title?: string;
|
|
10
10
|
detail?: string;
|
|
11
11
|
status?: string;
|
|
12
|
+
meta?: {
|
|
13
|
+
error: string;
|
|
14
|
+
};
|
|
12
15
|
}
|
|
13
16
|
export interface TAPIError {
|
|
14
17
|
errors: BaseError[];
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type JSX } from
|
|
2
|
-
import type { CodeErrorType } from
|
|
3
|
-
import type { ChildrenFunction } from
|
|
4
|
-
export type TResourceError =
|
|
5
|
-
type ErrorChildrenComponentProps = ChildrenFunction<Omit<TErrorComponent,
|
|
1
|
+
import { type JSX } from "react";
|
|
2
|
+
import type { CodeErrorType } from "../../typings/errors";
|
|
3
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
4
|
+
export type TResourceError = "addresses" | "billing_address" | "gift_cards" | "gift_card_or_coupon_code" | "line_items" | "orders" | "payment_methods" | "prices" | "shipments" | "shipping_address" | "customer_address" | "sku_options" | "variant" | "in_stock_subscriptions";
|
|
5
|
+
type ErrorChildrenComponentProps = ChildrenFunction<Omit<TErrorComponent, "children"> & {
|
|
6
6
|
errors: string[];
|
|
7
7
|
}>;
|
|
8
|
-
export interface TErrorComponent extends Omit<JSX.IntrinsicElements[
|
|
8
|
+
export interface TErrorComponent extends Omit<JSX.IntrinsicElements["span"], "children"> {
|
|
9
9
|
/**
|
|
10
10
|
* Resource which get the error
|
|
11
11
|
*/
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo}from"react";import Parent from"../utils/Parent";import
|
|
2
|
+
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useMemo}from"react";import Parent from"../utils/Parent";import getAllErrors from"../utils/getAllErrors";import AddressContext from"../../context/AddressContext";import CustomerContext from"../../context/CustomerContext";import GiftCardContext from"../../context/GiftCardContext";import InStockSubscriptionContext from"../../context/InStockSubscriptionContext";import LineItemChildrenContext from"../../context/LineItemChildrenContext";import LineItemContext from"../../context/LineItemContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import ShipmentContext from"../../context/ShipmentContext";export function Errors(props){const{children,messages=[],resource,field,...p}=props,{payment}=useContext(PaymentMethodChildrenContext),{errors:orderErrors}=useContext(OrderContext),{errors:giftCardErrors}=useContext(GiftCardContext),{errors:lineItemErrors}=useContext(LineItemContext),{errors:addressErrors}=useContext(AddressContext),{errors:customerErrors}=useContext(CustomerContext),{errors:shipmentErrors}=useContext(ShipmentContext),{errors:inStockSubscriptionErrors}=useContext(InStockSubscriptionContext),{errors:paymentMethodErrors,currentPaymentMethodType,currentPaymentMethodId}=useContext(PaymentMethodContext),{lineItem}=useContext(LineItemChildrenContext),allErrors=useMemo(()=>[...giftCardErrors||[],...orderErrors||[],...lineItemErrors||[],...customerErrors||[],...shipmentErrors||[],...inStockSubscriptionErrors||[],...paymentMethodErrors?.filter(v=>v.field===currentPaymentMethodType&&payment?.id===currentPaymentMethodId)||[]],[giftCardErrors,orderErrors,lineItemErrors,customerErrors,shipmentErrors,inStockSubscriptionErrors,paymentMethodErrors]).filter((v,k,a)=>v?.code!==a[k-1]?.code),addressesErrors=useMemo(()=>[...addressErrors||[]],[addressErrors]),msgErrors=getAllErrors({allErrors:[...allErrors,...addressesErrors],field,messages,props:p,lineItem,resource,returnHtml:!children}),parentProps={messages,resource,field,errors:msgErrors,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx(_Fragment,{children:msgErrors})}export default Errors;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";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),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase(),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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),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 isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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 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"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase(),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&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},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 isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";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),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId,errors:paymentMethodErrors}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(isFree&&!isPermitted&&setNotPermitted(!1),loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const paymentSourceStatus=order?.payment_source?.payment_response?.status?.toLowerCase(),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),!currentPaymentMethodRef?.current?.onsubmit&&paymentSourceStatus==="declined"&&setNotPermitted(!0)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,!currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order?.id,paymentSource?.id,order?.total_amount_with_taxes_cents]),useEffect(()=>{(errors&&errors.length>0||paymentMethodErrors&&paymentMethodErrors.length>0)&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors?.length,paymentMethodErrors?.length]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),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 isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status,paymentMethodType=order?.payment_source?.payment_response?.paymentMethod?.type;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 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"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&paymentMethodType==="giftcard"&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status","payment_source"],include:["payment_source"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",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"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,checkPaymentSourceStatus=checkPaymentSource?.payment_response?.status?.toLowerCase(),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&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&checkPaymentSourceStatus!=="declined"&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})):(setIsLoading(!1),setPlaceOrderStatus?.({status:"standby"}))},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}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes,getStripeAttributes}from"../../utils/getPaymentAttributes";import AdyenGateway from"./AdyenGateway";import BraintreeGateway from"./BraintreeGateway";import CheckoutComGateway from"./CheckoutComGateway";import ExternalGateway from"./ExternalGateway";import KlarnaGateway from"./KlarnaGateway";import PaypalGateway from"./PaypalGateway";import StripeGateway from"./StripeGateway";import WireTransferGateway from"./WireTransferGateway";export function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=getLoaderComponent(loader),[loading,setLoading]=useState(!0),{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=useContext(PaymentMethodContext),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;useEffect(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=getStripeAttributes(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource]),useEffect(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return _jsx(AdyenGateway,{...gatewayConfig,children});case"braintree_payments":return _jsx(BraintreeGateway,{...gatewayConfig,children});case"checkout_com_payments":return _jsx(CheckoutComGateway,{...gatewayConfig,children});case"external_payments":return _jsx(ExternalGateway,{...gatewayConfig,children});case"klarna_payments":return _jsx(KlarnaGateway,{...gatewayConfig,children});case"stripe_payments":return _jsx(StripeGateway,{...gatewayConfig,children});case"wire_transfers":return _jsx(WireTransferGateway,{...gatewayConfig,children});case"paypal_payments":return _jsx(PaypalGateway,{...gatewayConfig,children});default:return null}}export default PaymentGateway;
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useState}from"react";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import getLoaderComponent from"../../utils/getLoaderComponent";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes,getStripeAttributes}from"../../utils/getPaymentAttributes";import AdyenGateway from"./AdyenGateway";import BraintreeGateway from"./BraintreeGateway";import CheckoutComGateway from"./CheckoutComGateway";import ExternalGateway from"./ExternalGateway";import KlarnaGateway from"./KlarnaGateway";import PaypalGateway from"./PaypalGateway";import StripeGateway from"./StripeGateway";import WireTransferGateway from"./WireTransferGateway";export function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=getLoaderComponent(loader),[loading,setLoading]=useState(!0),{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=useContext(PaymentMethodContext),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;useEffect(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=getStripeAttributes(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1),paymentSource||setLoading(!0)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource?.id]),useEffect(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),order&&order.status==="placed"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status,order?.status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return _jsx(AdyenGateway,{...gatewayConfig,children});case"braintree_payments":return _jsx(BraintreeGateway,{...gatewayConfig,children});case"checkout_com_payments":return _jsx(CheckoutComGateway,{...gatewayConfig,children});case"external_payments":return _jsx(ExternalGateway,{...gatewayConfig,children});case"klarna_payments":return _jsx(KlarnaGateway,{...gatewayConfig,children});case"stripe_payments":return _jsx(StripeGateway,{...gatewayConfig,children});case"wire_transfers":return _jsx(WireTransferGateway,{...gatewayConfig,children});case"paypal_payments":return _jsx(PaypalGateway,{...gatewayConfig,children});default:return null}}export default PaymentGateway;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import{getPublicIP}from"../../utils/getPublicIp";import{hasSubscriptions}from"../../utils/hasSubscriptions";import{setCustomerOrderParam}from"../../utils/localStorage";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),[giftcardError,setGiftcardError]=useState(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder,getOrderByFields}=useContext(OrderContext),authConfig=useContext(CommerceLayerContext),{placeOrderButtonRef,setPlaceOrder,status}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&hasSubscriptions(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
|
|
2
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import{getPublicIP}from"../../utils/getPublicIp";import{hasSubscriptions}from"../../utils/hasSubscriptions";import{setCustomerOrderParam}from"../../utils/localStorage";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),[giftcardError,setGiftcardError]=useState(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder,getOrderByFields}=useContext(OrderContext),authConfig=useContext(CommerceLayerContext),{placeOrderButtonRef,setPlaceOrder,status}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0;if(currentBalance===0){const message="The gift card has no balance. Please use a different one.";return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),{resultCode:"Refused",message}}const attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&hasSubscriptions(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1&&id.search("giftcard")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type { LineItem } from
|
|
2
|
-
import type { BaseError } from '../../typings/errors';
|
|
3
|
-
import type { TResourceError } from '../errors/Errors';
|
|
1
|
+
import type { LineItem } from "@commercelayer/sdk";
|
|
4
2
|
import type { JSX } from "react";
|
|
3
|
+
import type { TResourceError } from "../errors/Errors";
|
|
4
|
+
import type { BaseError } from "../../typings/errors";
|
|
5
5
|
export interface AllErrorsParams {
|
|
6
6
|
allErrors: BaseError[];
|
|
7
7
|
messages: BaseError[];
|
|
8
8
|
field?: string;
|
|
9
|
-
props: Omit<JSX.IntrinsicElements[
|
|
9
|
+
props: Omit<JSX.IntrinsicElements["span"], "ref">;
|
|
10
10
|
lineItem?: LineItem | null;
|
|
11
11
|
resource?: TResourceError;
|
|
12
12
|
returnHtml?: boolean;
|
|
@@ -64,7 +64,9 @@ export declare function getOrderByFields(params: {
|
|
|
64
64
|
}): Promise<Order>;
|
|
65
65
|
export declare function updateOrder({ id, attributes, dispatch, config, include, state, }: UpdateOrderArgs): Promise<{
|
|
66
66
|
success: boolean;
|
|
67
|
-
error?:
|
|
67
|
+
error?: {
|
|
68
|
+
errors: BaseError[];
|
|
69
|
+
};
|
|
68
70
|
order?: Order;
|
|
69
71
|
}>;
|
|
70
72
|
interface TResourceRequest {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{publish}from"../utils/events";import{getApplicationLink}from"../utils/getApplicationLink";import{getDomain}from"../utils/getDomain";import getSdk from"../utils/getSdk";import{setCustomerOrderParam}from"../utils/localStorage";import{getOrganizationConfig}from"../utils/organization";import getErrors,{setErrors}from"../utils/getErrors";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?getSdk(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id};await sdk.orders.update(resource,{include});
|
|
2
|
+
import isEmpty from"lodash/isEmpty";import baseReducer from"../utils/baseReducer";import{publish}from"../utils/events";import{getApplicationLink}from"../utils/getApplicationLink";import{getDomain}from"../utils/getDomain";import getSdk from"../utils/getSdk";import{setCustomerOrderParam}from"../utils/localStorage";import{getOrganizationConfig}from"../utils/organization";import getErrors,{setErrors}from"../utils/getErrors";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state,options={}}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function getOrderByFields(params){const{orderId,fields,config}=params,sdk=config!=null?getSdk(config):void 0;if(sdk==null)throw new Error("SDK not initialized");return await sdk.orders.retrieve(orderId,{fields})}export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id},currentTotalAmountWithTaxesCents=state?.order?.total_amount_with_taxes_cents;await sdk.orders.update(resource,{include});let order=await getApiOrder({id,config,dispatch,state});const newTotalAmountWithTaxesCents=order?.total_amount_with_taxes_cents;return currentTotalAmountWithTaxesCents!==newTotalAmountWithTaxesCents&&order?.payment_source?.id&&(await sdk.orders.update({id,payment_source:null}),order=await getApiOrder({id,config,dispatch,state})),dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return console.error("Update order",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1,error}}}export async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?getSdk(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=getErrors({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
+
import type { AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, KlarnaPayment, Order, PaymentMethod, PaypalPayment, StripePayment, WireTransfer } from "@commercelayer/sdk";
|
|
2
|
+
import type { Dispatch, MutableRefObject } from "react";
|
|
1
3
|
import type { AdyenPaymentConfig } from "../components/payment_source/AdyenPayment";
|
|
2
4
|
import type { BraintreeConfig } from "../components/payment_source/BraintreePayment";
|
|
5
|
+
import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
|
|
6
|
+
import type { ExternalPaymentConfig } from "../components/payment_source/ExternalPayment";
|
|
3
7
|
import type { PaypalConfig } from "../components/payment_source/PaypalPayment";
|
|
4
8
|
import type { StripeConfig } from "../components/payment_source/StripePayment";
|
|
5
9
|
import type { WireTransferConfig } from "../components/payment_source/WireTransferPayment";
|
|
6
10
|
import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
|
|
7
11
|
import type { getOrderContext, updateOrder } from "./OrderReducer";
|
|
8
12
|
import type { BaseError } from "../typings/errors";
|
|
9
|
-
import type { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from "@commercelayer/sdk";
|
|
10
|
-
import type { Dispatch, MutableRefObject } from "react";
|
|
11
|
-
import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
|
|
12
|
-
import type { ExternalPaymentConfig } from "../components/payment_source/ExternalPayment";
|
|
13
13
|
import type { ResourceKeys } from "../utils/getPaymentAttributes";
|
|
14
14
|
export type PaymentSourceType = Order["payment_source"];
|
|
15
15
|
interface Card {
|
|
@@ -110,6 +110,9 @@ interface TSetPaymentMethodParams {
|
|
|
110
110
|
export declare function setPaymentMethod({ config, dispatch, order, paymentMethodId, updateOrder, setOrderErrors, paymentResource, }: TSetPaymentMethodParams): Promise<{
|
|
111
111
|
success: boolean;
|
|
112
112
|
order?: Order;
|
|
113
|
+
error?: {
|
|
114
|
+
errors: BaseError[];
|
|
115
|
+
};
|
|
113
116
|
}>;
|
|
114
117
|
type PaymentSourceTypes = (StripePayment & WireTransfer) | (StripePayment | WireTransfer);
|
|
115
118
|
export type SetPaymentSourceResponse = {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{
|
|
2
|
+
import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{pick}from"../utils/pick";import{replace}from"../utils/replace";import{snakeToCamelCase}from"../utils/snakeToCamelCase";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};if(updateOrder!=null){const currentOrder=await updateOrder({id:order.id,attributes});if(!currentOrder.success&¤tOrder.error){const errors=getErrors({error:currentOrder.error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),setOrderErrors?.(errors),response}response=currentOrder}dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=getSdk(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource}),expiredErrors=errors.filter(v=>v?.meta?.error==="expired");if(expiredErrors.length>0&&order&&config&&(console.error("Set payment source - expired:",expiredErrors),destroyPaymentSource({paymentSourceId:order.payment_source?.id||"",paymentResource,dispatch})),errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}else setErrors({currentErrors,newErrors:errors,dispatch})}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch?.({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { TResourceError } from
|
|
2
|
-
export type CodeErrorType =
|
|
1
|
+
import type { TResourceError } from "../components/errors/Errors";
|
|
2
|
+
export type CodeErrorType = "EMPTY_ERROR" | "FILTER_NOT_ALLOWED" | "FORBIDDEN" | "INTERNAL_SERVER_ERROR" | "INVALID_DATA_FORMAT" | "INVALID_FIELD" | "INVALID_FIELD_FORMAT" | "INVALID_FIELD_VALUE" | "INVALID_FILTERS_SYNTAX" | "INVALID_FILTER_VALUE" | "INVALID_INCLUDE" | "INVALID_LINKS_OBJECT" | "INVALID_PAGE_OBJECT" | "INVALID_PAGE_VALUE" | "INVALID_RESOURCE" | "INVALID_RESOURCE_ID" | "INVALID_SORT_CRITERIA" | "INVALID_TOKEN" | "KEY_NOT_INCLUDED_IN_URL" | "KEY_ORDER_MISMATCH" | "LOCKED" | "NOT_ACCEPTABLE" | "OUT_OF_STOCK" | "PARAM_MISSING" | "PARAM_NOT_ALLOWED" | "PAYMENT_NOT_APPROVED_FOR_EXECUTION" | "PAYMENT_INTENT_AUTHENTICATION_FAILURE" | "RECORD_NOT_FOUND" | "RECORD_NOT_FOUND" | "RELATION_EXISTS" | "NO_SHIPPING_METHODS" | "SAVE_FAILED" | "TYPE_MISMATCH" | "UNAUTHORIZED" | "UNSUPPORTED_MEDIA_TYPE" | "VALIDATION_ERROR";
|
|
3
3
|
export interface BaseError {
|
|
4
4
|
code: CodeErrorType;
|
|
5
5
|
message: string;
|
|
@@ -9,6 +9,9 @@ export interface BaseError {
|
|
|
9
9
|
title?: string;
|
|
10
10
|
detail?: string;
|
|
11
11
|
status?: string;
|
|
12
|
+
meta?: {
|
|
13
|
+
error: string;
|
|
14
|
+
};
|
|
12
15
|
}
|
|
13
16
|
export interface TAPIError {
|
|
14
17
|
errors: BaseError[];
|