Skip to content

Commit

Permalink
feat: dynamic tax calculation in paypal (#739)
Browse files Browse the repository at this point in the history
  • Loading branch information
ImSagnik007 authored Oct 16, 2024
1 parent 85bc6df commit 9a5b87d
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 17 deletions.
10 changes: 7 additions & 3 deletions src/Payments/PaypalSDK.res
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ open PaypalSDKTypes

@react.component
let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) => {
let {iframeId, publishableKey, sdkHandleOneClickConfirmPayment} = Recoil.useRecoilValueFromAtom(
RecoilAtoms.keys,
)
let {
iframeId,
publishableKey,
sdkHandleOneClickConfirmPayment,
clientSecret,
} = Recoil.useRecoilValueFromAtom(RecoilAtoms.keys)
let sdkHandleIsThere = Recoil.useRecoilValueFromAtom(
RecoilAtoms.isPaymentButtonHandlerProvidedAtom,
)
Expand Down Expand Up @@ -100,6 +103,7 @@ let make = (~sessionObj: SessionsType.token, ~paymentType: CardThemeType.mode) =
~isCallbackUsedVal,
~sdkHandleIsThere,
~sessions,
~clientSecret,
)
})
Window.body->Window.appendChild(paypalScript)
Expand Down
34 changes: 32 additions & 2 deletions src/Payments/PaypalSDKHelpers.res
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
open PaypalSDKTypes
open Promise
open Utils
open TaxCalculation

let loadPaypalSDK = (
~loggerState: OrcaLogger.loggerMake,
Expand All @@ -25,6 +26,7 @@ let loadPaypalSDK = (
~isCallbackUsedVal as _: bool,
~sdkHandleIsThere: bool,
~sessions: PaymentType.loadType,
~clientSecret,
) => {
loggerState.setLogInfo(
~value="Paypal SDK Button Clicked",
Expand Down Expand Up @@ -113,6 +115,35 @@ let loadPaypalSDK = (
}
})
},
onShippingAddressChange: data => {
let isTaxCalculationEnabled = paymentMethodListValue.is_tax_calculation_enabled
if isTaxCalculationEnabled {
let newShippingAddressObj =
data
->getDictFromJson
->getDictFromObj("shippingAddress")
->shippingAddressItemToObjMapper
let newShippingAddress =
[
("state", newShippingAddressObj.state->Option.getOr("")->JSON.Encode.string),
("country", newShippingAddressObj.countryCode->Option.getOr("")->JSON.Encode.string),
("zip", newShippingAddressObj.postalCode->Option.getOr("")->JSON.Encode.string),
]->getJsonFromArrayOfJson

let paymentMethodType = "paypal"->JSON.Encode.string

calculateTax(
~shippingAddress=[("address", newShippingAddress)]->getJsonFromArrayOfJson,
~logger=loggerState,
~publishableKey,
~clientSecret=clientSecret->Option.getOr(""),
~paymentMethodType,
~sessionId=data->getDictFromJson->Dict.get("orderID"),
)
} else {
Js.Json.null->Js.Promise.resolve
}
},
onApprove: (_data, actions) => {
if !options.readOnly {
actions.order.get()
Expand Down Expand Up @@ -141,8 +172,7 @@ let loadPaypalSDK = (

let (connectors, _) =
paymentMethodListValue->PaymentUtils.getConnectors(Wallets(Paypal(SDK)))

let orderId = val->Utils.getDictFromJson->Utils.getString("id", "")
let orderId = val->getDictFromJson->Utils.getString("id", "")
let body = PaymentBody.paypalSdkBody(~token=orderId, ~connectors)
let modifiedPaymentBody = PaymentUtils.appendedCustomerAcceptance(
~isGuestCustomer,
Expand Down
6 changes: 3 additions & 3 deletions src/Types/ApplePayTypes.res
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type lineItem = {
\"type": string,
}
type shippingAddressChangeEvent = {shippingContact: JSON.t}
type updatedOrderDetails = {newTotal: lineItem, newLineItems: array<lineItem>}
type orderDetails = {newTotal: lineItem, newLineItems: array<lineItem>}
type innerSession
type session = {
begin: unit => unit,
Expand All @@ -41,8 +41,8 @@ type session = {
mutable onvalidatemerchant: event => unit,
completeMerchantValidation: JSON.t => unit,
mutable onpaymentauthorized: event => unit,
mutable onshippingcontactselected: shippingAddressChangeEvent => unit,
completeShippingContactSelection: updatedOrderDetails => unit,
mutable onshippingcontactselected: shippingAddressChangeEvent => promise<unit>,
completeShippingContactSelection: orderDetails => unit,
completePayment: JSON.t => unit,
\"STATUS_SUCCESS": string,
\"STATUS_FAILURE": string,
Expand Down
12 changes: 12 additions & 0 deletions src/Types/PaypalSDKTypes.res
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type buttons = {
onApprove: (data, actions) => unit,
onCancel: data => unit,
onError?: err => unit,
onShippingAddressChange?: JSON.t => promise<JSON.t>,
}
let getLabel = (var: PaymentType.paypalStyleType) => {
switch var {
Expand Down Expand Up @@ -177,3 +178,14 @@ let getOrderDetails = (orderDetails, paymentType) => {
shippingAddressOverride,
}
}

let shippingAddressItemToObjMapper=dict=>{
recipientName: dict->Utils.getOptionString("recipientName"),
line1: dict->Utils.getOptionString("line1"),
line2: dict->Utils.getOptionString("line2"),
city: dict->Utils.getOptionString("city"),
countryCode: dict->Utils.getOptionString("countryCode"),
postalCode: dict->Utils.getOptionString("postalCode"),
state: dict->Utils.getOptionString("state"),
phone: dict->Utils.getOptionString("phone"),
}
33 changes: 24 additions & 9 deletions src/Utilities/ApplePayHelpers.res
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,28 @@ let startApplePaySession = (
}

ssn.onshippingcontactselected = shippingAddressChangeEvent => {
let currentTotal = paymentRequest->getDictFromJson->getDictFromDict("total")
let label = currentTotal->getString("label", "apple")
let currentAmount = currentTotal->getString("amount", "0.00")
let \"type" = currentTotal->getString("type", "final")

let oldTotal: lineItem = {
label,
amount: currentAmount,
\"type",
}
let currentOrderDetails: orderDetails = {
newTotal: oldTotal,
newLineItems: [oldTotal],
}
if isTaxCalculationEnabled {
let newShippingContact =
shippingAddressChangeEvent.shippingContact
->getDictFromJson
->shippingContactItemToObjMapper
let newShippingAddress =
[
("state", newShippingContact.locality->JSON.Encode.string),
("state", newShippingContact.administrativeArea->JSON.Encode.string),
("country", newShippingContact.countryCode->JSON.Encode.string),
("zip", newShippingContact.postalCode->JSON.Encode.string),
]->getJsonFromArrayOfJson
Expand All @@ -126,8 +140,7 @@ let startApplePaySession = (
~publishableKey,
~clientSecret,
~paymentMethodType,
)
->thenResolve(response => {
)->thenResolve(response => {
switch response->taxResponseToObjMapper {
| Some(taxCalculationResponse) => {
let (netAmount, ordertaxAmount, shippingCost) = (
Expand All @@ -136,13 +149,13 @@ let startApplePaySession = (
taxCalculationResponse.shipping_cost,
)
let newTotal: lineItem = {
label: "Net Amount",
label,
amount: netAmount->minorUnitToString,
\"type": "final",
\"type",
}
let newLineItems: array<lineItem> = [
{
label: "Bag Subtotal",
label: "Subtotal",
amount: (netAmount - ordertaxAmount - shippingCost)->minorUnitToString,
\"type": "final",
},
Expand All @@ -157,16 +170,18 @@ let startApplePaySession = (
\"type": "final",
},
]
let updatedOrderDetails: updatedOrderDetails = {
let updatedOrderDetails: orderDetails = {
newTotal,
newLineItems,
}
ssn.completeShippingContactSelection(updatedOrderDetails)
}
| None => ssn.abort()
| None => ssn.completeShippingContactSelection(currentOrderDetails)
}
})
->ignore
} else {
ssn.completeShippingContactSelection(currentOrderDetails)
resolve()
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/Utilities/PaymentHelpers.res
Original file line number Diff line number Diff line change
Expand Up @@ -2017,6 +2017,7 @@ let calculateTax = (
~shippingAddress,
~logger,
~customPodUri,
~sessionId,
) => {
open Promise
let endpoint = ApiEndpoint.getApiEndPoint()
Expand All @@ -2027,6 +2028,8 @@ let calculateTax = (
("shipping", shippingAddress),
("payment_method_type", paymentMethodType),
]
sessionId->Option.mapOr((), id => body->Array.push(("session_id", id))->ignore)

logApi(
~optLogger=Some(logger),
~url=uri,
Expand Down
2 changes: 2 additions & 0 deletions src/Utilities/TaxCalculation.res
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ let calculateTax = (
~clientSecret,
~publishableKey,
~paymentMethodType,
~sessionId=None,
) => {
PaymentHelpers.calculateTax(
~clientSecret=clientSecret->JSON.Encode.string,
Expand All @@ -33,5 +34,6 @@ let calculateTax = (
~shippingAddress,
~logger,
~customPodUri="",
~sessionId,
)
}

0 comments on commit 9a5b87d

Please sign in to comment.