Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions packages/commerce-sdk-react/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/commerce-sdk-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"version": "node ./scripts/version.js"
},
"dependencies": {
"commerce-sdk-isomorphic": "4.0.1-preview-shopper-configurations.0",
"commerce-sdk-isomorphic": "4.0.0-nightly-20251016080758",
"js-cookie": "^3.0.1",
"jwt-decode": "^4.0.0"
},
Expand Down
44 changes: 36 additions & 8 deletions packages/commerce-sdk-react/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import {
isOriginTrusted,
onClient,
getDefaultCookieAttributes,
isAbsoluteUrl,
stringToBase64,
extractCustomParameters
} from '../utils'
Expand Down Expand Up @@ -96,10 +95,19 @@ type AuthorizePasswordlessParams = {
callbackURI?: string
userid: string
mode?: string
/** When true, SLAS will register the customer as part of the passwordless flow */
register_customer?: boolean | string
/** Optional registration details forwarded to SLAS when register_customer=true */
first_name?: string
last_name?: string
email?: string
phone_number?: string
}

type GetPasswordLessAccessTokenParams = {
pwdlessLoginToken: string
/** When true, SLAS will register the customer if not already registered */
register_customer?: boolean | string
}

/**
Expand Down Expand Up @@ -1262,21 +1270,33 @@ class Auth {
async authorizePasswordless(parameters: AuthorizePasswordlessParams) {
const usid = this.get('usid')
const callbackURI = parameters.callbackURI || this.passwordlessLoginCallbackURI
const finalMode = callbackURI ? 'callback' : parameters.mode || 'sms'
const finalMode = parameters.mode || (callbackURI ? 'callback' : 'sms')

const res = await helpers.authorizePasswordless({
const res = await (helpers as unknown as Helpers).authorizePasswordless({
slasClient: this.client,
credentials: {
clientSecret: this.clientSecret
},
parameters: {
...(callbackURI && {callbackURI: callbackURI}),
...(callbackURI && {callbackURI}),
...(usid && {usid}),
userid: parameters.userid,
mode: finalMode
mode: finalMode,
...(parameters.register_customer !== undefined && {
// Helper expects camelCase 'registerCustomer'
registerCustomer:
typeof parameters.register_customer === 'boolean'
? Boolean(parameters.register_customer)
: parameters.register_customer
}),
// Helper expects camelCase registration fields in parameters; it maps to body internally
...(parameters.last_name && {lastName: parameters.last_name}),
...(parameters.email && {email: parameters.email}),
...(parameters.first_name && {firstName: parameters.first_name}),
...(parameters.phone_number && {phoneNumber: parameters.phone_number})
}
})
if (res && res.status !== 200) {
} as any)
if (res && res.status && res.status !== 200) {
const errorData = await res.json()
throw new Error(`${res.status} ${String(errorData.message)}`)
}
Expand All @@ -1289,14 +1309,22 @@ class Auth {
async getPasswordLessAccessToken(parameters: GetPasswordLessAccessTokenParams) {
const pwdlessLoginToken = parameters.pwdlessLoginToken || ''
const dntPref = this.getDnt({includeDefaults: true})
const usid = this.get('usid')
const token = await helpers.getPasswordLessAccessToken({
slasClient: this.client,
credentials: {
clientSecret: this.clientSecret
},
parameters: {
pwdlessLoginToken,
dnt: dntPref !== undefined ? String(dntPref) : undefined
dnt: dntPref !== undefined ? String(dntPref) : undefined,
...(usid && {usid}),
...(parameters.register_customer !== undefined && {
register_customer:
typeof parameters.register_customer === 'boolean'
? String(parameters.register_customer)
: parameters.register_customer
})
}
})
const isGuest = false
Expand Down
178 changes: 178 additions & 0 deletions packages/template-retail-react-app/app/hooks/use-basket-recovery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Copyright (c) 2025, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {useCommerceApi} from '@salesforce/commerce-sdk-react'
import useAuthContext from '@salesforce/commerce-sdk-react/hooks/useAuthContext'
import {useShopperBasketsMutation} from '@salesforce/commerce-sdk-react'

/**
* Reusable basket recovery hook to stabilize basket after OTP/auth swap.
* - Attempts merge (if caller already merged, pass skipMerge=true)
* - Hydrates destination basket by id with retry
* - Fallbacks to create/copy items and re-apply shipping
*/
const useBasketRecovery = () => {
const api = useCommerceApi()
const auth = useAuthContext()
// const currentBasketQuery = useCurrentBasket()

const mergeBasket = useShopperBasketsMutation('mergeBasket')
const createBasket = useShopperBasketsMutation('createBasket')
const addItemToBasket = useShopperBasketsMutation('addItemToBasket')
const updateShippingAddressForShipment = useShopperBasketsMutation(
'updateShippingAddressForShipment'
)
const updateShippingMethodForShipment = useShopperBasketsMutation(
'updateShippingMethodForShipment'
)

const copyItemsAndShipping = async (
destBasketId,
items = [],
shipmentSnapshot = null,
shipmentId = 'me'
) => {
if (items?.length) {
const payload = items.map((item) => {
const productId = item.productId || item.product_id || item.id || item.product?.id

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where do all these variations come from?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does it somehow stem from ocapi vs scapi response? Wonder if we should 'normalize' the object prior tothis

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

list products vs get product API response differences. would be nice to have a centralized normalization function

const quantity = item.quantity || item.amount || 1
const variationAttributes =
item.variationAttributes || item.variation_attributes || []
const optionItems = item.optionItems || item.option_items || []
const mappedVariations = Array.isArray(variationAttributes)
? variationAttributes.map((v) => ({
attributeId: v.attributeId || v.attribute_id || v.id,
valueId: v.valueId || v.value_id || v.value
}))
: []
const mappedOptions = Array.isArray(optionItems)
? optionItems.map((o) => ({
optionId: o.optionId || o.option_id || o.id,
optionValueId:
o.optionValueId || o.optionValue || o.option_value || o.value
}))
: []
const obj = {productId, quantity}
if (mappedVariations.length) obj.variationAttributes = mappedVariations
if (mappedOptions.length) obj.optionItems = mappedOptions
return obj
})
await addItemToBasket.mutateAsync({parameters: {basketId: destBasketId}, body: payload})
}

if (shipmentSnapshot) {
const shippingAddress = shipmentSnapshot.shippingAddress
if (shippingAddress) {
await updateShippingAddressForShipment.mutateAsync({
parameters: {basketId: destBasketId, shipmentId},
body: {
address1: shippingAddress.address1,
address2: shippingAddress.address2,
city: shippingAddress.city,
countryCode: shippingAddress.countryCode,
firstName: shippingAddress.firstName,
lastName: shippingAddress.lastName,
phone: shippingAddress.phone,
postalCode: shippingAddress.postalCode,
stateCode: shippingAddress.stateCode
}
})
}
const methodId = shipmentSnapshot?.shippingMethod?.id
if (methodId) {
await updateShippingMethodForShipment.mutateAsync({
parameters: {basketId: destBasketId, shipmentId},
body: {id: methodId}
})
}
}
}

const recoverBasketAfterAuth = async ({
preLoginItems = [],
shipmentSnapshot = null,
doMerge = true
} = {}) => {
// Ensure fresh token in provider
await auth.refreshAccessToken()
// Defer invalidation to the end to avoid duplicate basket/shipping-method refetches

let destId
if (doMerge) {
try {
const merged = await mergeBasket.mutateAsync({
parameters: {createDestinationBasket: true}
})
destId = merged?.basketId || merged?.basket_id || merged?.id
} catch (_e) {
/* noop */
}
}

if (!destId) {
try {
const list = await api.shopperCustomers.getCustomerBaskets({
parameters: {customerId: 'me'}
})
destId = list?.baskets?.[0]?.basketId
} catch (_e) {
/* noop */
}
}

if (destId) {
// Avoid triggering a hook-level refetch that can cause UI remounts.
// Instead, probe the destination basket directly for shipment id.
let hydrated = null
try {
hydrated = await api.shopperBaskets.getBasket({
headers: {authorization: `Bearer ${auth.get('access_token')}`},

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this sort of thing the responsibility of the SDK? I haven't seen any other API requests have inline token management. Why exactly is this required?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Somehow the user context isn't refreshed when a guest becomes a registered user and we get stale basket or we lose the merged basket. This is an attempt to get the registered user's basket by explicitly specifying the access token. We will be re-visiting the logic in this file in another ticket. I will leave this as-is for now.

parameters: {basketId: destId}
})
} catch (_e) {
hydrated = null
}
if (!hydrated) {
try {
const created = await createBasket.mutateAsync({})
destId = created?.basketId || created?.basket_id || created?.id || destId
await copyItemsAndShipping(destId, preLoginItems, shipmentSnapshot)
} catch (_e) {
/* noop */
}
} else if (shipmentSnapshot) {
// PII (shipping address/method) is not merged by API; re-apply from snapshot
try {
const effectiveDestId = hydrated?.basketId || destId
const destShipmentId =
hydrated?.shipments?.[0]?.shipmentId || hydrated?.shipments?.[0]?.id || 'me'
await copyItemsAndShipping(
effectiveDestId,
[],
shipmentSnapshot,
destShipmentId
)
} catch (_e) {
/* noop */
}
}
} else {
try {
const created = await createBasket.mutateAsync({})
destId = created?.basketId || created?.basket_id || created?.id
await copyItemsAndShipping(destId, preLoginItems, shipmentSnapshot)
} catch (_e) {
/* noop */
}
}

return destId
}

return {recoverBasketAfterAuth}
}

export default useBasketRecovery
Loading
Loading