@rechargeapps/storefront-client 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/api/auth.js +26 -44
- package/dist/cjs/api/auth.js.map +1 -1
- package/dist/cjs/api/bundle.js +1 -3
- package/dist/cjs/api/bundle.js.map +1 -1
- package/dist/cjs/api/customer.js +2 -2
- package/dist/cjs/api/customer.js.map +1 -1
- package/dist/cjs/utils/init.js +2 -0
- package/dist/cjs/utils/init.js.map +1 -1
- package/dist/cjs/utils/request.js +5 -2
- package/dist/cjs/utils/request.js.map +1 -1
- package/dist/esm/api/auth.js +26 -44
- package/dist/esm/api/auth.js.map +1 -1
- package/dist/esm/api/bundle.js +1 -3
- package/dist/esm/api/bundle.js.map +1 -1
- package/dist/esm/api/customer.js +2 -2
- package/dist/esm/api/customer.js.map +1 -1
- package/dist/esm/utils/init.js +2 -0
- package/dist/esm/utils/init.js.map +1 -1
- package/dist/esm/utils/request.js +5 -2
- package/dist/esm/utils/request.js.map +1 -1
- package/dist/index.d.ts +13 -2
- package/dist/umd/recharge-client.min.js +13 -13
- package/package.json +2 -1
package/dist/esm/api/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_customer_account_api_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const token = urlParams.get('token');\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/customers/${customerHash}/access`, {\n headers,\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n"],"names":["baseRequest"],"mappings":";;;;AAYA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAI,UAAW,EAAA,CAAA;AAC7C,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAA,MAAM,WAAW,MAAM,sBAAA,CAAsC,OAAO,SAAW,EAAA,EAAE,SAAS,CAAA,CAAA;AAE1F,EAAO,OAAA,EAAE,UAAU,QAAS,CAAA,SAAA,EAAW,YAAY,QAAS,CAAA,WAAA,EAAa,OAAS,EAAA,QAAA,CAAS,OAAQ,EAAA,CAAA;AACrG,CAAA;AAGsB,eAAA,e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EAAA,UAAA,EAAY,SAAS,WAAY,EAAA,CAAA;AAC1E;;;;"}
|
|
1
|
+
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...options,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const token = urlParams.get('token');\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>('post', `/customers/${customerHash}/access`, {\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });\n}\n"],"names":["baseRequest"],"mappings":";;;;AAcA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAI,UAAW,EAAA,CAAA;AAC7C,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAA,MAAM,WAAW,MAAM,sBAAA,CAAsC,OAAO,SAAW,EAAA,EAAE,SAAS,CAAA,C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AEA,eAAe,oBAAA,CACb,MACA,EAAA,GAAA,EACA,EAAE,EAAA,EAAI,OAAO,IAAM,EAAA,OAAA,EAA4B,GAAA,EACnC,EAAA;AACZ,EAAA,MAAM,EAAE,WAAa,EAAA,cAAA,EAAgB,uBAAuB,OAAS,EAAA,UAAA,KAAe,UAAW,EAAA,CAAA;AAC/F,EAAM,MAAA,eAAA,GAAkB,kBAAmB,CAAA,WAAA,EAAa,cAAc,CAAA,CAAA;AACtE,EAAA,MAAM,UAA6B,GAAA;AAAA,IACjC,GAAI,qBAAwB,GAAA,EAAE,oCAAsC,EAAA,qBAAA,KAA0B,EAAC;AAAA,IAC/F,GAAI,OAAU,GAAA,EAAE,yBAA2B,EAAA,OAAA,KAAY,EAAC;AAAA,IACxD,GAAI,UAAa,GAAA,EAAE,4BAA8B,EAAA,UAAA,KAAe,EAAC;AAAA,IACjE,wBAA0B,EAAA,QAAA;AAAA,IAC1B,GAAI,OAAU,GAAA,OAAA,GAAU,EAAC;AAAA,GAC3B,CAAA;AAEA,EAAA,OAAOA,OAAe,CAAA,MAAA,EAAQ,CAAG,EAAA,eAAe,CAAG,EAAA,GAAG,CAAI,CAAA,EAAA,EAAE,EAAI,EAAA,KAAA,EAAO,IAAM,EAAA,OAAA,EAAS,YAAY,CAAA,CAAA;AACpG;;;;"}
|
package/dist/esm/api/bundle.js
CHANGED
|
@@ -9,9 +9,7 @@ function getTimestampSecondsFromClient() {
|
|
|
9
9
|
}
|
|
10
10
|
async function getTimestampSecondsFromServer() {
|
|
11
11
|
try {
|
|
12
|
-
const { timestamp } = await shopifyAppProxyRequest("get", `${STORE_FRONT_MANAGER_URL}/t
|
|
13
|
-
headers: { "X-Recharge-App": "storefront-client" }
|
|
14
|
-
});
|
|
12
|
+
const { timestamp } = await shopifyAppProxyRequest("get", `${STORE_FRONT_MANAGER_URL}/t`);
|
|
15
13
|
return timestamp;
|
|
16
14
|
} catch (ex) {
|
|
17
15
|
console.error(`Fetch failed: ${ex}. Using client-side date.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid/non-secure';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { toLineItemProperty } from '../utils/bundle';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n}\n\nexport function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n if (!bundle) {\n return 'Bundle is not defined';\n }\n // Don't make bundle settings call due to merchant issues\n // const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n // if (!bundleSettings) {\n // return 'Bundle settings do not exist for the given product';\n // }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'getBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>(\n 'get',\n `/bundle_selections`,\n { query },\n getInternalSession(session, 'listBundleSelections')\n );\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n getInternalSession(session, 'createBundleSelection')\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n getInternalSession(session, 'updateBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'deleteBundleSelection')\n );\n}\n\nexport async function updateBundle(\n session: Session,\n purchase_item_id: string | number,\n updateRequest: UpdateBundlePurchaseItem,\n query?: BundlePurchaseItemParams\n): Promise<BundlePurchaseItem> {\n const { subscription } = await rechargeApiRequest<{ subscription: BundlePurchaseItem }>(\n 'put',\n '/bundles',\n {\n id: purchase_item_id,\n data: updateRequest,\n query,\n },\n getInternalSession(session, 'updateBundle')\n );\n\n return subscription;\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,uBAA0B,GAAA,8BAAA,CAAA;AAEhC,SAAS,6BAAwC,GAAA;AAI/C,EAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAK,CAAA,GAAA,KAAQ,GAAI,CAAA,CAAA;AACpC,CAAA;AAEA,eAAe,6BAAiD,GAAA;AAK9D,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,WAAc,GAAA,MAAM,uBAA8C,KAAO,EAAA,CAAA,EAAG,uBAAuB,CAAM,EAAA,CAAA,EAAA;AAAA,MAC/G,OAAA,EAAS,EAAE,gBAAA,EAAkB,mBAAoB,EAAA;AAAA,KAClD,CAAA,CAAA;AACD,IAAO,OAAA,SAAA,CAAA;AAAA,WACA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OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC7B,KAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,MACE,EAAI,EAAA,gBAAA;AAAA,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid/non-secure';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { toLineItemProperty } from '../utils/bundle';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`);\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n}\n\nexport function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n if (!bundle) {\n return 'Bundle is not defined';\n }\n // Don't make bundle settings call due to merchant issues\n // const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n // if (!bundleSettings) {\n // return 'Bundle settings do not exist for the given product';\n // }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'getBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>(\n 'get',\n `/bundle_selections`,\n { query },\n getInternalSession(session, 'listBundleSelections')\n );\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n getInternalSession(session, 'createBundleSelection')\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n getInternalSession(session, 'updateBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'deleteBundleSelection')\n );\n}\n\nexport async function updateBundle(\n session: Session,\n purchase_item_id: string | number,\n updateRequest: UpdateBundlePurchaseItem,\n query?: BundlePurchaseItemParams\n): Promise<BundlePurchaseItem> {\n const { subscription } = await rechargeApiRequest<{ subscription: BundlePurchaseItem }>(\n 'put',\n '/bundles',\n {\n id: purchase_item_id,\n data: updateRequest,\n query,\n },\n getInternalSession(session, 'updateBundle')\n );\n\n return subscription;\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,uBAA0B,GAAA,8BAAA,CAAA;AAEhC,SAAS,6BAAwC,GAAA;AAI/C,EAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAK,CAAA,GAAA,KAAQ,GAAI,CAAA,CAAA;AACpC,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EAAO,OAAA,kBAAA;AAAA,IACL,QAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC7B,KAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,MACE,EAAI,EAAA,gBAAA;AAAA,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
|
package/dist/esm/api/customer.js
CHANGED
|
@@ -42,11 +42,11 @@ async function getDeliverySchedule(session, query) {
|
|
|
42
42
|
);
|
|
43
43
|
return deliveries;
|
|
44
44
|
}
|
|
45
|
-
async function getCustomerPortalAccess(session) {
|
|
45
|
+
async function getCustomerPortalAccess(session, query) {
|
|
46
46
|
return rechargeApiRequest(
|
|
47
47
|
"get",
|
|
48
48
|
"/portal_access",
|
|
49
|
-
{},
|
|
49
|
+
{ query },
|
|
50
50
|
getInternalSession(session, "getCustomerPortalAccess")
|
|
51
51
|
);
|
|
52
52
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n UpdateCustomerRequest,\n Session,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${id}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(session: Session): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n {},\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${redirectURL}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${redirectURL}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n const data = customerNotificationMap[notification];\n if (!data) {\n throw new Error('Notification not supported.');\n }\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${customerId}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${id}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n UpdateCustomerRequest,\n Session,\n CustomerPortalAccessOptions,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${id}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(\n session: Session,\n query?: CustomerPortalAccessOptions\n): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n { query },\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${redirectURL}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${redirectURL}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n const data = customerNotificationMap[notification];\n if (!data) {\n throw new Error('Notification not supported.');\n }\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${customerId}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${id}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":[],"mappings":";;AAmBsB,eAAA,WAAA,CAAY,SAAkB,OAAiD,EAAA;AACnG,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EAAA,GAAI,MAAM,kBAAA;AAAA,IACzB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,KA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wB,YAAY,CAAA,CAAA;AACjD,EAAA,IAAI,CAAC,IAAM,EAAA;AACT,IAAM,MAAA,IAAI,MAAM,6BAA6B,CAAA,CAAA;AAAA,GAC/C;AACA,EAAO,OAAA,kBAAA;AAAA,IACL,MAAA;AAAA,IACA,cAAc,UAAU,CAAA,cAAA,CAAA;AAAA,IACxB;AAAA,MACE,IAAM,EAAA;AAAA,QACJ,GAAG,IAAA;AAAA,QACH,aAAe,EAAA,OAAA;AAAA,OACjB;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,0BAA0B,CAAA;AAAA,GACxD,CAAA;AACF;;;;"}
|
package/dist/esm/utils/init.js
CHANGED
|
@@ -47,6 +47,8 @@ function initRecharge(opt = {}) {
|
|
|
47
47
|
storeIdentifier: getStoreIdentifier(opt.storeIdentifier),
|
|
48
48
|
loginRetryFn: opt.loginRetryFn,
|
|
49
49
|
storefrontAccessToken,
|
|
50
|
+
appName: opt.appName,
|
|
51
|
+
appVersion: opt.appVersion,
|
|
50
52
|
environment: hiddenOpts.environment ? hiddenOpts.environment : "prod",
|
|
51
53
|
environmentUri: hiddenOpts.environmentUri,
|
|
52
54
|
customerHash: hiddenOpts.customerHash
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","sources":["../../../src/utils/init.ts"],"sourcesContent":["import { resetCDNCache } from '../api/cdn';\nimport { StorefrontOptions, CRUDRequestOptions, GetRequestOptions, InitOptions } from '../types';\nimport { setOptions } from './options';\nimport { request } from './request';\n\n/**\n * @internal\n * @deprecated will be removed in next version\n */\nexport const api = {\n get<T>(url: string, requestOptions?: GetRequestOptions): Promise<T> {\n return request<T>('get', url, requestOptions);\n },\n post<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('post', url, requestOptions);\n },\n put<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('put', url, requestOptions);\n },\n delete<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('delete', url, requestOptions);\n },\n};\n\n/**\n * Uses passed in storeIdentifier, but if it's not passed in will try to infer it.\n * Currently it will only infer if we are in the context of a Shopify store. This will not infer headless or hosted yet.\n */\nfunction getStoreIdentifier(storeIdentifier?: string): string {\n if (storeIdentifier) {\n return storeIdentifier;\n }\n\n // Infer's when on Shopify store (non headless)\n if (window?.Shopify?.shop) {\n return window.Shopify.shop;\n }\n\n // Domain exists on hosted themes. If it doesn't for some reason, get the subdomain and create the identifier\n let domain = window?.domain;\n if (!domain) {\n const subdomain = location?.href\n .match(/(?:http[s]*:\\/\\/)*(.*?)\\.(?=admin\\.rechargeapps\\.com)/i)?.[1]\n .replace(/-sp$/, '');\n if (subdomain) {\n domain = `${subdomain}.myshopify.com`;\n }\n }\n\n // Infer's when on Recharge hosted\n if (domain) {\n return domain;\n }\n\n throw new Error(`No storeIdentifier was passed into init.`);\n}\n\nexport function initRecharge(opt: InitOptions = {}) {\n const hiddenOpts = opt as StorefrontOptions;\n const { storefrontAccessToken } = opt;\n if (storefrontAccessToken && !storefrontAccessToken.startsWith('strfnt')) {\n throw new Error(\n 'Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.'\n );\n }\n setOptions({\n storeIdentifier: getStoreIdentifier(opt.storeIdentifier),\n loginRetryFn: opt.loginRetryFn,\n storefrontAccessToken,\n environment: hiddenOpts.environment ? hiddenOpts.environment : 'prod',\n environmentUri: hiddenOpts.environmentUri,\n customerHash: hiddenOpts.customerHash,\n });\n\n // When init is called again, reset the cache to make sure we don't have the old cache around\n resetCDNCache();\n}\n"],"names":[],"mappings":";;;;AASO,MAAM,GAAM,GAAA;AAAA,EACjB,GAAA,CAAO,KAAa,cAAgD,EAAA;AAClE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,IAAA,CAAQ,KAAa,cAAiD,EAAA;AACpE,IAAO,OAAA,OAAA,C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,CAAW,QAAQ,CAAG,EAAA;AACxE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uKAAA;AAAA,KACF,CAAA;AAAA,GACF;AACA,EAAW,UAAA,CAAA;AAAA,IACT,eAAA,EAAiB,kBAAmB,CAAA,GAAA,CAAI,eAAe,CAAA;AAAA,IACvD,cAAc,GAAI,CAAA,YAAA;AAAA,IAClB,qBAAA;AAAA,IACA,WAAa,EAAA,UAAA,CAAW,WAAc,GAAA,UAAA,CAAW,WAAc,GAAA,MAAA;AAAA,IAC/D,gBAAgB,UAAW,CAAA,cAAA;AAAA,IAC3B,cAAc,UAAW,CAAA,YAAA;AAAA,GAC1B,CAAA,CAAA;AAGD,EAAc,aAAA,EAAA,CAAA;AAChB;;;;"}
|
|
1
|
+
{"version":3,"file":"init.js","sources":["../../../src/utils/init.ts"],"sourcesContent":["import { resetCDNCache } from '../api/cdn';\nimport { StorefrontOptions, CRUDRequestOptions, GetRequestOptions, InitOptions } from '../types';\nimport { setOptions } from './options';\nimport { request } from './request';\n\n/**\n * @internal\n * @deprecated will be removed in next version\n */\nexport const api = {\n get<T>(url: string, requestOptions?: GetRequestOptions): Promise<T> {\n return request<T>('get', url, requestOptions);\n },\n post<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('post', url, requestOptions);\n },\n put<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('put', url, requestOptions);\n },\n delete<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('delete', url, requestOptions);\n },\n};\n\n/**\n * Uses passed in storeIdentifier, but if it's not passed in will try to infer it.\n * Currently it will only infer if we are in the context of a Shopify store. This will not infer headless or hosted yet.\n */\nfunction getStoreIdentifier(storeIdentifier?: string): string {\n if (storeIdentifier) {\n return storeIdentifier;\n }\n\n // Infer's when on Shopify store (non headless)\n if (window?.Shopify?.shop) {\n return window.Shopify.shop;\n }\n\n // Domain exists on hosted themes. If it doesn't for some reason, get the subdomain and create the identifier\n let domain = window?.domain;\n if (!domain) {\n const subdomain = location?.href\n .match(/(?:http[s]*:\\/\\/)*(.*?)\\.(?=admin\\.rechargeapps\\.com)/i)?.[1]\n .replace(/-sp$/, '');\n if (subdomain) {\n domain = `${subdomain}.myshopify.com`;\n }\n }\n\n // Infer's when on Recharge hosted\n if (domain) {\n return domain;\n }\n\n throw new Error(`No storeIdentifier was passed into init.`);\n}\n\nexport function initRecharge(opt: InitOptions = {}) {\n const hiddenOpts = opt as StorefrontOptions;\n const { storefrontAccessToken } = opt;\n if (storefrontAccessToken && !storefrontAccessToken.startsWith('strfnt')) {\n throw new Error(\n 'Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.'\n );\n }\n setOptions({\n storeIdentifier: getStoreIdentifier(opt.storeIdentifier),\n loginRetryFn: opt.loginRetryFn,\n storefrontAccessToken,\n appName: opt.appName,\n appVersion: opt.appVersion,\n environment: hiddenOpts.environment ? hiddenOpts.environment : 'prod',\n environmentUri: hiddenOpts.environmentUri,\n customerHash: hiddenOpts.customerHash,\n });\n\n // When init is called again, reset the cache to make sure we don't have the old cache around\n resetCDNCache();\n}\n"],"names":[],"mappings":";;;;AASO,MAAM,GAAM,GAAA;AAAA,EACjB,GAAA,CAAO,KAAa,cAAgD,EAAA;AAClE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,IAAA,CAAQ,KAAa,cAAiD,EAAA;AACpE,IAAO,OAAA,OAAA,CAAW,MAAQ,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC/C;AAAA,EACA,GAAA,CAAO,KAAa,cAAiD,EAAA;AACnE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,MAAA,CAAU,KAAa,cAAiD,EAAA;AACtE,IAAO,OAAA,OAAA,CAAW,QAAU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CAAA,OAAA;AAAA,IACb,YAAY,GAAI,CAAA,UAAA;AAAA,IAChB,WAAa,EAAA,UAAA,CAAW,WAAc,GAAA,UAAA,CAAW,WAAc,GAAA,MAAA;AAAA,IAC/D,gBAAgB,UAAW,CAAA,cAAA;AAAA,IAC3B,cAAc,UAAW,CAAA,YAAA;AAAA,GAC1B,CAAA,CAAA;AAGD,EAAc,aAAA,EAAA,CAAA;AAChB;;;;"}
|
|
@@ -24,13 +24,16 @@ async function cdnRequest(method, url, requestOptions = {}) {
|
|
|
24
24
|
return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);
|
|
25
25
|
}
|
|
26
26
|
async function rechargeApiRequest(method, url, { id, query, data, headers } = {}, session) {
|
|
27
|
-
const { environment, environmentUri, storeIdentifier, loginRetryFn } = getOptions();
|
|
27
|
+
const { environment, environmentUri, storeIdentifier, loginRetryFn, appName, appVersion } = getOptions();
|
|
28
28
|
const token = session.apiToken;
|
|
29
29
|
const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);
|
|
30
30
|
const reqHeaders = {
|
|
31
31
|
"X-Recharge-Access-Token": token,
|
|
32
32
|
"X-Recharge-Version": "2021-11",
|
|
33
|
-
"X-Recharge-Fn": session.internalFnCall,
|
|
33
|
+
"X-Recharge-Sdk-Fn": session.internalFnCall,
|
|
34
|
+
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
35
|
+
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
36
|
+
"X-Recharge-Sdk-Version": "1.20.0",
|
|
34
37
|
"X-Request-Id": session.internalRequestId,
|
|
35
38
|
...headers ? headers : {}
|
|
36
39
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport { nanoid } from 'nanoid/non-secure';\nimport stringify from 'qs/lib/stringify';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\n });\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const { environment, environmentUri, storeIdentifier, loginRetryFn } = getOptions();\n const token = session.apiToken;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Fn': session.internalFnCall,\n 'X-Request-Id': session.internalRequestId,\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: storeIdentifier,\n ...(query as any),\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n reqUrl = [reqUrl, `${id}`.trim()].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["session"],"mappings":";;;;;;;AAUA,SAAS,eAAe,GAAsB,EAAA;AAC5C,EAAA,OAAO,UAAU,GAAK,EAAA;AAAA,IACpB,MAAQ,EAAA,KAAA;AAAA,IACR,OAAS,EAAA,KAAA;AAAA,IACT,WAAa,EAAA,OAAA;AAAA,GACd,CAAA,CAAA;AACH,CAAA;AAGgB,SAAA,kBAAA,CAAmB,SAAoC,MAAiC,EAAA;AACtG,EAAO,OAAA;AAAA,IACL,GAAG,OAAA;AAAA,IACH,cAAA,EAAiB,QAA4B,cAAkB,IAAA,MAAA;AAAA,IAC/D,iBAAA,EAAoB,OAA4B,CAAA,iBAAA,IAAqB,MAAO,EAAA;AAAA,GAC9E,CAAA;AACF,CAAA;AAEA,eAAsB,UAAc,CAAA,MAAA,EAAgB,GAAa,EAAA,cAAA,GAAiC,EAAgB,EAAA;AAChH,EAAA,MAAM,OAAO,UAAW,EAAA,CAAA;AACxB,EAAA,OAAO,OAAQ,CAAA,MAAA,EAAQ,CAAG,EAAA,gBAAA,CAAiB,IAAK,CAAA,WAAW,CAAC,CAAA,OAAA,EAAU,IAAK,CAAA,eAAe,CAAG,EAAA,GAAG,IAAI,cAAc,CAAA,CAAA;AACpH,CAAA;AAEsB,eAAA,kBAAA,CACpB,MACA,EAAA,GAAA,EACA,EAAE,EAAA,EAAI,KAAO,EAAA,IAAA,EAAM,OAAQ,EAAA,GAAoB,EAAC,EAChD,OACY,EAAA;AACZ,
|
|
1
|
+
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport { nanoid } from 'nanoid/non-secure';\nimport stringify from 'qs/lib/stringify';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\n });\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const { environment, environmentUri, storeIdentifier, loginRetryFn, appName, appVersion } = getOptions();\n const token = session.apiToken;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: storeIdentifier,\n ...(query as any),\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n reqUrl = [reqUrl, `${id}`.trim()].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["session"],"mappings":";;;;;;;AAUA,SAAS,eAAe,GAAsB,EAAA;AAC5C,EAAA,OAAO,UAAU,GAAK,EAAA;AAAA,IACpB,MAAQ,EAAA,KAAA;AAAA,IACR,OAAS,EAAA,KAAA;AAAA,IACT,WAAa,EAAA,OAAA;AAAA,GACd,CAAA,CAAA;AACH,CAAA;AAGgB,SAAA,kBAAA,CAAmB,SAAoC,MAAiC,EAAA;AACtG,EAAO,OAAA;AAAA,IACL,GAAG,OAAA;AAAA,IACH,cAAA,EAAiB,QAA4B,cAAkB,IAAA,MAAA;AAAA,IAC/D,iBAAA,EAAoB,OAA4B,CAAA,iBAAA,IAAqB,MAAO,EAAA;AAAA,GAC9E,CAAA;AACF,CAAA;AAEA,eAAsB,UAAc,CAAA,MAAA,EAAgB,GAAa,EAAA,cAAA,GAAiC,EAAgB,EAAA;AAChH,EAAA,MAAM,OAAO,UAAW,EAAA,CAAA;AACxB,EAAA,OAAO,OAAQ,CAAA,MAAA,EAAQ,CAAG,EAAA,gBAAA,CAAiB,IAAK,CAAA,WAAW,CAAC,CAAA,OAAA,EAAU,IAAK,CAAA,eAAe,CAAG,EAAA,GAAG,IAAI,cAAc,CAAA,CAAA;AACpH,CAAA;AAEsB,eAAA,kBAAA,CACpB,MACA,EAAA,GAAA,EACA,EAAE,E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;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -875,6 +875,9 @@ interface CustomerDeliveryScheduleResponse {
|
|
|
875
875
|
};
|
|
876
876
|
deliveries: Delivery[];
|
|
877
877
|
}
|
|
878
|
+
interface CustomerPortalAccessOptions {
|
|
879
|
+
page_destination?: 'subscriptions' | 'delivery_schedule' | 'orders' | 'shipping' | 'payment_methods' | 'overview';
|
|
880
|
+
}
|
|
878
881
|
interface CustomerPortalAccessResponse {
|
|
879
882
|
/** base URL for customer portal */
|
|
880
883
|
base_url: string;
|
|
@@ -2431,6 +2434,10 @@ interface StorefrontOptions {
|
|
|
2431
2434
|
storeIdentifier: string;
|
|
2432
2435
|
/** Recharge storefront access token used for Recharge Storefront API access */
|
|
2433
2436
|
storefrontAccessToken?: string;
|
|
2437
|
+
/** Merchant application name, optional, but helpful for debugging */
|
|
2438
|
+
appName?: string;
|
|
2439
|
+
/** Merchant application version, optional, but helpful for debugging */
|
|
2440
|
+
appVersion?: string;
|
|
2434
2441
|
/**
|
|
2435
2442
|
* Middleware function that should return a Session, called when API functions return a 401.
|
|
2436
2443
|
* This function allows your app to refetch a session, store it by whatever means your app uses for future calls,
|
|
@@ -2451,6 +2458,10 @@ interface InitOptions {
|
|
|
2451
2458
|
storeIdentifier?: string;
|
|
2452
2459
|
/** Recharge storefront access token used for Recharge Storefront API access */
|
|
2453
2460
|
storefrontAccessToken?: string;
|
|
2461
|
+
/** Merchant application name, optional, but helpful for debugging */
|
|
2462
|
+
appName?: string;
|
|
2463
|
+
/** Merchant application version, optional, but helpful for debugging */
|
|
2464
|
+
appVersion?: string;
|
|
2454
2465
|
/**
|
|
2455
2466
|
* Middleware function that should return a Session, called when API functions return a 401.
|
|
2456
2467
|
* This function allows your app to refetch a session, store it by whatever means your app uses for future calls,
|
|
@@ -2596,7 +2607,7 @@ declare function listCreditAccounts(session: Session, query?: CreditAccountListP
|
|
|
2596
2607
|
declare function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer>;
|
|
2597
2608
|
declare function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer>;
|
|
2598
2609
|
declare function getDeliverySchedule(session: Session, query?: CustomerDeliveryScheduleParams): Promise<Delivery[]>;
|
|
2599
|
-
declare function getCustomerPortalAccess(session: Session): Promise<CustomerPortalAccessResponse>;
|
|
2610
|
+
declare function getCustomerPortalAccess(session: Session, query?: CustomerPortalAccessOptions): Promise<CustomerPortalAccessResponse>;
|
|
2600
2611
|
declare function getActiveChurnLandingPageURL(session: Session, subscriptionId: string | number, redirectURL: string): Promise<string>;
|
|
2601
2612
|
declare function getGiftRedemptionLandingPageURL(session: Session, giftId: string | number, redirectURL: string): Promise<string>;
|
|
2602
2613
|
declare function sendCustomerNotification<T extends CustomerNotification>(session: Session, notification: CustomerNotification, options?: CustomerNotificationOptions<T>): Promise<void>;
|
|
@@ -2724,4 +2735,4 @@ declare const api: {
|
|
|
2724
2735
|
};
|
|
2725
2736
|
declare function initRecharge(opt?: InitOptions): void;
|
|
2726
2737
|
|
|
2727
|
-
export { type ActivateMembershipRequest, type AddToCartCallbackSettings, type AddonSettings, type Address, type AddressIncludes, type AddressListParams, type AddressListResponse, type AddressResponse, type AddressSortBy, type AnalyticsData, type ApplyCreditOptions, type AssociatedAddress, type BasicSubscriptionParams, type BooleanLike, type BooleanNumbers, type BooleanString, type BooleanStringNumbers, type BundleAppProxy, type BundlePriceRule, type BundleProduct, type BundleProductLayoutSettings, type BundlePurchaseItem, type BundlePurchaseItemParams, type BundleSelection, type BundleSelectionAppProxy, type BundleSelectionItem, type BundleSelectionItemRequiredCreateProps, type BundleSelectionListParams, type BundleSelectionsResponse, type BundleSelectionsSortBy, type BundleTemplateSettings, type BundleTemplateType, type BundleTranslations, type BundleVariant, type BundleVariantOptionSource, type BundleVariantRange, type BundleVariantSelectionDefault, type CDNBaseWidgetSettings, type CDNBundleSettings, type CDNBundleVariant, type CDNBundleVariantOptionSource, type CDNPlan, type CDNProduct, type CDNProductAndSettings, type CDNProductKeyObject, type CDNProductQuery_2020_12, type CDNProductQuery_2022_06, type CDNProductRaw, type CDNProductResource, type CDNProductResponseType, type CDNProductType, type CDNProductVariant_2022_06, type CDNProduct_2022_06, type CDNProductsAndSettings, type CDNProductsAndSettingsResource, type CDNStoreSettings, type CDNSubscriptionOption, type CDNVariant, type CDNVersion, type CDNWidgetSettings, type CDNWidgetSettingsRaw, type CDNWidgetSettingsResource, type CRUDRequestOptions, type CancelMembershipRequest, type CancelSubscriptionRequest, type ChangeMembershipRequest, type ChannelSettings, type Charge, type ChargeIncludes, type ChargeListParams, type ChargeListResponse, type ChargeResponse, type ChargeSortBy, type ChargeStatus, type Collection, type CollectionListParams, type CollectionTypes, type CollectionsResponse, type CollectionsSortBy, type ColorString, type CreateAddressRequest, type CreateBundleSelectionRequest, type CreateMetafieldRequest, type CreateOnetimeRequest, type CreatePaymentMethodRequest, type CreateRecipientAddress, type CreateSubscriptionRequest, type CreditAccount, type CreditAccountIncludes, type CreditAccountListParams, type CreditAccountType, type CreditAccountsResponse, type CreditAccountsSortBy, type CreditSummaryIncludes, type CrossSellsSettings, type Customer, type CustomerCreditSummary, type CustomerDeliveryScheduleParams, type CustomerDeliveryScheduleResponse, type CustomerIncludes, type CustomerNotification, type CustomerNotificationOptions, type CustomerNotificationTemplate, type CustomerNotificationType, type CustomerPortalAccessResponse, type Delivery, type DeliveryLineItem, type DeliveryOrder, type DeliveryPaymentMethod, type Discount, type DiscountType, type DynamicBundleItemAppProxy, type DynamicBundlePropertiesAppProxy, type ExternalAttributeSchema, type ExternalId, type ExternalTransactionId, type FirstOption, type GetAddressOptions, type GetChargeOptions, type GetCreditSummaryOptions, type GetCustomerOptions, type GetMembershipProgramOptions, type GetPaymentMethodOptions, type GetRequestOptions, type GetSubscriptionOptions, type GiftPurchase, type GiftPurchasesParams, type GiftPurchasesResponse, type HTMLString, type InitOptions, type InternalSession, type IntervalUnit, type IsoDateString, type LineItem, type ListParams, type LoginResponse, type Membership, type MembershipBenefit, type MembershipIncludes, type MembershipListParams, type MembershipListResponse, type MembershipProgram, type MembershipProgramIncludes, type MembershipProgramListParams, type MembershipProgramListResponse, type MembershipProgramResponse, type MembershipProgramSortBy, type MembershipProgramStatus, type MembershipResponse, type MembershipStatus, type MembershipsSortBy, type MergeAddressesRequest, type Metafield, type MetafieldOptionalCreateProps, type MetafieldOwnerResource, type MetafieldRequiredCreateProps, type Method, type Modifier, type MultiStepSettings, type OnePageSettings, type Onetime, type OnetimeListParams, type OnetimeOptionalCreateProps, type OnetimeRequiredCreateProps, type OnetimesResponse, type OnetimesSortBy, type Order, type OrderIncludes, type OrderListParams, type OrderSortBy, type OrderStatus, type OrderType, type OrdersResponse, type PasswordlessCodeResponse, type PasswordlessOptions, type PasswordlessValidateResponse, type PaymentDetails, type PaymentMethod, type PaymentMethodIncludes, type PaymentMethodListParams, type PaymentMethodOptionalCreateProps, type PaymentMethodRequiredCreateProps, type PaymentMethodSortBy, type PaymentMethodStatus, type PaymentMethodsResponse, type PaymentType, type Plan, type PlanListParams, type PlanSortBy, type PlanType, type PlansResponse, type ProcessorName, type ProductImage, type ProductInclude, type ProductListResponse, type ProductOption, type ProductSearchParams_2020_12, type ProductSearchParams_2022_06, type ProductSearchResponse_2020_12, type ProductSearchResponse_2022_06, type ProductSearchType, type ProductSource, type ProductValueOption, type ProductVariant_2020_12, type ProductVariant_2022_06, type Product_2020_12, type Product_2022_06, type Property, type PublishStatus, type Request, type RequestHeaders, type RequestOptions, type SellingPlan, type SellingPlanGroup, type Session, type ShippingCountriesOptions, type ShippingCountriesResponse, type ShippingCountry, type ShippingLine, type ShippingProvince, type ShopifyUpdatePaymentInfoOptions, type SkipChargeParams, type SkipFutureChargeAddressRequest, type SkipFutureChargeAddressResponse, type SortBy, type SortField, type SortKeys, type StepSettings, type StepSettingsCommon, type StepSettingsTypes, type StorefrontEnvironment, type StorefrontOptions, type StorefrontPurchaseOption, type SubType, type Subscription, type SubscriptionIncludes, type SubscriptionListParams, type SubscriptionOption, type SubscriptionOptionalCreateProps, type SubscriptionPreferences, type SubscriptionRequiredCreateProps, type SubscriptionSortBy, type SubscriptionStatus, type Subscription_2021_01, type SubscriptionsResponse, type TaxLine, type Translations, type UpdateAddressRequest, type UpdateBundlePurchaseItem, type UpdateBundleSelectionRequest, type UpdateCustomerRequest, type UpdateMetafieldRequest, type UpdateOnetimeRequest, type UpdatePaymentMethodRequest, type UpdateSubscriptionParams, type UpdateSubscriptionRequest, type UpdateSubscriptionsParams, type UpdateSubscriptionsRequest, type VariantSelector, type VariantSelectorStepSetting, type WidgetIconColor, type WidgetTemplateType, type WidgetVisibility, activateMembership, activateSubscription, api, applyDiscountToAddress, applyDiscountToCharge, cancelMembership, cancelSubscription, changeMembership, createAddress, createBundleSelection, createMetafield, createOnetime, createPaymentMethod, createSubscription, createSubscriptions, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCollection, getCreditSummary, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getDynamicBundleItems, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getSubscription, initRecharge, type intervalUnit, listAddresses, listBundleSelections, listCharges, listCollectionProducts, listCollections, listCreditAccounts, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptions, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, type membershipIncludes, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, setApplyCreditsToNextCharge, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
|
|
2738
|
+
export { type ActivateMembershipRequest, type AddToCartCallbackSettings, type AddonSettings, type Address, type AddressIncludes, type AddressListParams, type AddressListResponse, type AddressResponse, type AddressSortBy, type AnalyticsData, type ApplyCreditOptions, type AssociatedAddress, type BasicSubscriptionParams, type BooleanLike, type BooleanNumbers, type BooleanString, type BooleanStringNumbers, type BundleAppProxy, type BundlePriceRule, type BundleProduct, type BundleProductLayoutSettings, type BundlePurchaseItem, type BundlePurchaseItemParams, type BundleSelection, type BundleSelectionAppProxy, type BundleSelectionItem, type BundleSelectionItemRequiredCreateProps, type BundleSelectionListParams, type BundleSelectionsResponse, type BundleSelectionsSortBy, type BundleTemplateSettings, type BundleTemplateType, type BundleTranslations, type BundleVariant, type BundleVariantOptionSource, type BundleVariantRange, type BundleVariantSelectionDefault, type CDNBaseWidgetSettings, type CDNBundleSettings, type CDNBundleVariant, type CDNBundleVariantOptionSource, type CDNPlan, type CDNProduct, type CDNProductAndSettings, type CDNProductKeyObject, type CDNProductQuery_2020_12, type CDNProductQuery_2022_06, type CDNProductRaw, type CDNProductResource, type CDNProductResponseType, type CDNProductType, type CDNProductVariant_2022_06, type CDNProduct_2022_06, type CDNProductsAndSettings, type CDNProductsAndSettingsResource, type CDNStoreSettings, type CDNSubscriptionOption, type CDNVariant, type CDNVersion, type CDNWidgetSettings, type CDNWidgetSettingsRaw, type CDNWidgetSettingsResource, type CRUDRequestOptions, type CancelMembershipRequest, type CancelSubscriptionRequest, type ChangeMembershipRequest, type ChannelSettings, type Charge, type ChargeIncludes, type ChargeListParams, type ChargeListResponse, type ChargeResponse, type ChargeSortBy, type ChargeStatus, type Collection, type CollectionListParams, type CollectionTypes, type CollectionsResponse, type CollectionsSortBy, type ColorString, type CreateAddressRequest, type CreateBundleSelectionRequest, type CreateMetafieldRequest, type CreateOnetimeRequest, type CreatePaymentMethodRequest, type CreateRecipientAddress, type CreateSubscriptionRequest, type CreditAccount, type CreditAccountIncludes, type CreditAccountListParams, type CreditAccountType, type CreditAccountsResponse, type CreditAccountsSortBy, type CreditSummaryIncludes, type CrossSellsSettings, type Customer, type CustomerCreditSummary, type CustomerDeliveryScheduleParams, type CustomerDeliveryScheduleResponse, type CustomerIncludes, type CustomerNotification, type CustomerNotificationOptions, type CustomerNotificationTemplate, type CustomerNotificationType, type CustomerPortalAccessOptions, type CustomerPortalAccessResponse, type Delivery, type DeliveryLineItem, type DeliveryOrder, type DeliveryPaymentMethod, type Discount, type DiscountType, type DynamicBundleItemAppProxy, type DynamicBundlePropertiesAppProxy, type ExternalAttributeSchema, type ExternalId, type ExternalTransactionId, type FirstOption, type GetAddressOptions, type GetChargeOptions, type GetCreditSummaryOptions, type GetCustomerOptions, type GetMembershipProgramOptions, type GetPaymentMethodOptions, type GetRequestOptions, type GetSubscriptionOptions, type GiftPurchase, type GiftPurchasesParams, type GiftPurchasesResponse, type HTMLString, type InitOptions, type InternalSession, type IntervalUnit, type IsoDateString, type LineItem, type ListParams, type LoginResponse, type Membership, type MembershipBenefit, type MembershipIncludes, type MembershipListParams, type MembershipListResponse, type MembershipProgram, type MembershipProgramIncludes, type MembershipProgramListParams, type MembershipProgramListResponse, type MembershipProgramResponse, type MembershipProgramSortBy, type MembershipProgramStatus, type MembershipResponse, type MembershipStatus, type MembershipsSortBy, type MergeAddressesRequest, type Metafield, type MetafieldOptionalCreateProps, type MetafieldOwnerResource, type MetafieldRequiredCreateProps, type Method, type Modifier, type MultiStepSettings, type OnePageSettings, type Onetime, type OnetimeListParams, type OnetimeOptionalCreateProps, type OnetimeRequiredCreateProps, type OnetimesResponse, type OnetimesSortBy, type Order, type OrderIncludes, type OrderListParams, type OrderSortBy, type OrderStatus, type OrderType, type OrdersResponse, type PasswordlessCodeResponse, type PasswordlessOptions, type PasswordlessValidateResponse, type PaymentDetails, type PaymentMethod, type PaymentMethodIncludes, type PaymentMethodListParams, type PaymentMethodOptionalCreateProps, type PaymentMethodRequiredCreateProps, type PaymentMethodSortBy, type PaymentMethodStatus, type PaymentMethodsResponse, type PaymentType, type Plan, type PlanListParams, type PlanSortBy, type PlanType, type PlansResponse, type ProcessorName, type ProductImage, type ProductInclude, type ProductListResponse, type ProductOption, type ProductSearchParams_2020_12, type ProductSearchParams_2022_06, type ProductSearchResponse_2020_12, type ProductSearchResponse_2022_06, type ProductSearchType, type ProductSource, type ProductValueOption, type ProductVariant_2020_12, type ProductVariant_2022_06, type Product_2020_12, type Product_2022_06, type Property, type PublishStatus, type Request, type RequestHeaders, type RequestOptions, type SellingPlan, type SellingPlanGroup, type Session, type ShippingCountriesOptions, type ShippingCountriesResponse, type ShippingCountry, type ShippingLine, type ShippingProvince, type ShopifyUpdatePaymentInfoOptions, type SkipChargeParams, type SkipFutureChargeAddressRequest, type SkipFutureChargeAddressResponse, type SortBy, type SortField, type SortKeys, type StepSettings, type StepSettingsCommon, type StepSettingsTypes, type StorefrontEnvironment, type StorefrontOptions, type StorefrontPurchaseOption, type SubType, type Subscription, type SubscriptionIncludes, type SubscriptionListParams, type SubscriptionOption, type SubscriptionOptionalCreateProps, type SubscriptionPreferences, type SubscriptionRequiredCreateProps, type SubscriptionSortBy, type SubscriptionStatus, type Subscription_2021_01, type SubscriptionsResponse, type TaxLine, type Translations, type UpdateAddressRequest, type UpdateBundlePurchaseItem, type UpdateBundleSelectionRequest, type UpdateCustomerRequest, type UpdateMetafieldRequest, type UpdateOnetimeRequest, type UpdatePaymentMethodRequest, type UpdateSubscriptionParams, type UpdateSubscriptionRequest, type UpdateSubscriptionsParams, type UpdateSubscriptionsRequest, type VariantSelector, type VariantSelectorStepSetting, type WidgetIconColor, type WidgetTemplateType, type WidgetVisibility, activateMembership, activateSubscription, api, applyDiscountToAddress, applyDiscountToCharge, cancelMembership, cancelSubscription, changeMembership, createAddress, createBundleSelection, createMetafield, createOnetime, createPaymentMethod, createSubscription, createSubscriptions, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCollection, getCreditSummary, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getDynamicBundleItems, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getSubscription, initRecharge, type intervalUnit, listAddresses, listBundleSelections, listCharges, listCollectionProducts, listCollections, listCreditAccounts, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptions, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, type membershipIncludes, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, setApplyCreditsToNextCharge, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
|