@aglyn/plugins-commerce 1.15.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/cart.js +8 -3
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +4 -2
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/product-detail.js +7 -3
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +26 -39
- package/src/lib/model/commerce-payment-methods.js +11 -118
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/server/billing-webhook.d.ts +23 -0
- package/src/lib/server/billing-webhook.js +162 -30
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +61 -14
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +42 -12
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +37 -12
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +112 -32
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
|
@@ -14,8 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
18
|
-
import { paymentProvider } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
17
|
+
*/ import { firebaseAdmin, getOrgForHost, isServerReleaseFlagOnForOrg } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import { accountChargeModel, DIRECT_CHARGE_ACCOUNT_PARAMS, paymentProvider } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
19
19
|
import { buildRoute, Route } from "@aglyn/aglyn/server";
|
|
20
20
|
async function stripe(path, params) {
|
|
21
21
|
const response = await fetch(`https://api.stripe.com/v1/${path}`, _extends({
|
|
@@ -86,15 +86,31 @@ async function stripe(path, params) {
|
|
|
86
86
|
const profileSnapshot = await profileRef.get();
|
|
87
87
|
let accountId = profileSnapshot.get('stripeAccountId');
|
|
88
88
|
if (!accountId) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
89
|
+
// The seller's OWN Stripe account (direct charges): Stripe bills it,
|
|
90
|
+
// underwrites it and gives it the full Stripe Dashboard, so the seller
|
|
91
|
+
// is the merchant of record on every site sale and can refund, answer
|
|
92
|
+
// a dispute and manage tax registrations there. See
|
|
93
|
+
// `DIRECT_CHARGE_ACCOUNT_PARAMS`. Behind `release_direct_charges` until
|
|
94
|
+
// the Terms say so; off, the platform-managed Express account and its
|
|
95
|
+
// destination charges, exactly as before. The shape cannot be changed
|
|
96
|
+
// once the account exists, so this is the one place it is decided.
|
|
97
|
+
// Any failure to read the flag is OFF: the account it would create is
|
|
98
|
+
// the one every store had before, never a shape nobody chose.
|
|
99
|
+
let ownsAccount = false;
|
|
100
|
+
try {
|
|
101
|
+
var _ref, _ref1;
|
|
102
|
+
var _ownerOrg_org2;
|
|
103
|
+
ownsAccount = await isServerReleaseFlagOnForOrg('release_direct_charges', String((_ref = (_ref1 = ownerOrg == null ? void 0 : (_ownerOrg_org2 = ownerOrg.org) == null ? void 0 : _ownerOrg_org2.id) != null ? _ref1 : ownerOrg == null ? void 0 : ownerOrg.orgId) != null ? _ref : '') || null);
|
|
104
|
+
} catch (unused) {
|
|
105
|
+
ownsAccount = false;
|
|
106
|
+
}
|
|
107
|
+
const account = await stripe('accounts', new URLSearchParams(_extends({}, ownsAccount ? DIRECT_CHARGE_ACCOUNT_PARAMS : {
|
|
108
|
+
type: 'express'
|
|
109
|
+
}, {
|
|
110
|
+
// Explicit capabilities (AGL-1994): `card_payments` for the
|
|
111
|
+
// charges, and `transfers` because a destination charge (every
|
|
112
|
+
// sale on an Express account, and the register and Tap to Pay on
|
|
113
|
+
// either kind) requires the destination to hold it.
|
|
98
114
|
'capabilities[card_payments][requested]': 'true',
|
|
99
115
|
'capabilities[transfers][requested]': 'true',
|
|
100
116
|
'metadata[profileId]': decoded.uid,
|
|
@@ -134,8 +150,13 @@ async function stripe(path, params) {
|
|
|
134
150
|
// BEFORE the first sale strands funds in a Connect account that
|
|
135
151
|
// cannot pay them out.
|
|
136
152
|
const payoutsEnabled = Boolean(account == null ? void 0 : account.payouts_enabled);
|
|
153
|
+
// Which charge shape this account takes, read off the account itself
|
|
154
|
+
// every time, so a re-onboarded seller can never inherit the last
|
|
155
|
+
// account's answer.
|
|
156
|
+
const chargeModel = accountChargeModel(account);
|
|
137
157
|
await profileRef.set({
|
|
138
158
|
stripeChargesEnabled: chargesEnabled,
|
|
159
|
+
stripeChargeModel: chargeModel,
|
|
139
160
|
stripePayoutsEnabled: payoutsEnabled,
|
|
140
161
|
// ALWAYS written, and `null` when Stripe would not say (AGL-2471).
|
|
141
162
|
// Writing unconditionally is what makes re-onboarding safe: a fresh
|
|
@@ -202,6 +223,16 @@ async function stripe(path, params) {
|
|
|
202
223
|
// a login link is a convenience, and failing to mint one must never turn
|
|
203
224
|
// a working status check into an error.
|
|
204
225
|
let dashboardUrl;
|
|
226
|
+
if (chargeModel === 'direct') {
|
|
227
|
+
// A full Stripe account signs in to Stripe itself; login links exist
|
|
228
|
+
// only for Express accounts.
|
|
229
|
+
return res.status(200).json({
|
|
230
|
+
accountId,
|
|
231
|
+
chargesEnabled: true,
|
|
232
|
+
payoutsEnabled,
|
|
233
|
+
dashboardUrl: 'https://dashboard.stripe.com/'
|
|
234
|
+
});
|
|
235
|
+
}
|
|
205
236
|
try {
|
|
206
237
|
const login = await stripe(`accounts/${accountId}/login_links`, new URLSearchParams());
|
|
207
238
|
dashboardUrl = typeof (login == null ? void 0 : login.url) === 'string' ? login.url : undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { paymentProvider } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Merchant payments onboarding (AGL-284): Stripe Connect Express for\n * storefront selling. Same account storage the checkout reads\n * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the\n * marketplace-profile prerequisite — commerce merchants aren't necessarily\n * publishers. Only the owning org's owner may onboard (payouts land on\n * their account). 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = ownerOrg?.org?.ownerUid\n if (!ownerUid) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n if (String(ownerUid) !== decoded.uid) {\n return res\n .status(403)\n .json({ error: 'Only the organization owner can set up payments' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const profileRef = firestore.collection('profiles').doc(decoded.uid)\n const profileSnapshot = await profileRef.get()\n\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n if (!accountId) {\n const account = await stripe(\n 'accounts',\n new URLSearchParams({\n type: 'express',\n // Explicit capabilities (AGL-1994, mirroring the marketplace twin\n // hardened by AGL-1547): without them the account's abilities\n // depend on unverified dashboard platform-profile defaults, and\n // the storefront charge is a DESTINATION charge — checkout.ts\n // sends `payment_intent_data[transfer_data][destination]`, which\n // requires the destination to hold `transfers`. A merchant\n // onboarded without it takes money that can never pay out.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[profileId]': decoded.uid,\n 'metadata[purpose]': 'commerce',\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = account.id\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n\n const account = await stripe(`accounts/${accountId}`)\n const chargesEnabled = Boolean(account?.charges_enabled)\n // WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).\n //\n // Three production linkages named TEST-mode accounts, one of them with\n // `stripeChargesEnabled: true`, so its storefronts read as payments-ready\n // and could not take a payment. Nothing recorded the mode, and nothing\n // could recover it later: the Account object carries no `livemode` field\n // and an `acct_…` id is the same shape in both worlds.\n //\n // The retrieve above IS the proof. Stripe refuses cross-mode account\n // access outright — \"was a test account created with a testmode key\" —\n // so an account this key just fetched is in this key's mode, and the\n // payment provider asks Stripe (`/v1/balance.livemode`) what that mode is\n // rather than reading the key string.\n const platformMode = await paymentProvider().resolvePlatformMode()\n // Payout readiness rides along (AGL-1994): the sale gate stays on\n // charges_enabled — that is what Stripe checks at charge time — but\n // charges-yes/payouts-no was invisible to the storefront, because\n // commerce wrote only `stripeChargesEnabled`. Recording\n // `payouts_enabled` is what lets a console surface warn a merchant\n // BEFORE the first sale strands funds in a Connect account that\n // cannot pay them out.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe bakes these into the onboarding link, so they have to be real\n // console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622\n // shape — so finishing Connect onboarding dropped the seller on a 404\n // (AGL-685). Console products is the plugin route under the org slug and\n // the host SUBDOMAIN, both of which have to be resolved here; the client\n // hook (useConsoleHostRoute) is not available to server code.\n const index = await firebaseAdmin\n .app()\n .firestore()\n .collection('hostIndex')\n .doc(hostId)\n .get()\n const subdomain = index.get('subdomain') as string | undefined\n const orgSlug = ownerOrg?.org?.slug as string | undefined\n // No slug/subdomain means no route to send them to; Stripe requires\n // both URLs, so fall back to the origin root rather than a fabricated\n // path that 404s.\n const productsUrl =\n orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'products',\n })}`\n : origin\n // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.\n //\n // This route used to return here the moment `charges_enabled` was true,\n // with a status and no link of any kind, and both console cards read the\n // `chargesEnabled` flag before they ever looked for a url. So the one\n // state that most needs Stripe — charges on, payouts NOT released, funds\n // accumulating in a Connect account that cannot pay them out — offered a\n // button labelled \"Finish payout setup in Stripe\" that raised a toast and\n // went nowhere. An Express account has no password and no direct login, so\n // a link minted here is the merchant's ONLY way in; without one the money\n // is unreachable and no surface says why.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n // The remediation flow, which is what Stripe points an account with\n // outstanding requirements at. Failures are NOT swallowed: answering\n // 200 with no link is precisely the dead end being closed here, so a\n // mint that fails surfaces as the handler's 502 and the merchant is\n // told to try again rather than left pressing a dead button.\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Payouts are flowing, so this is the VIEW: balance, payout schedule,\n // and the reason a payout failed — none of which Aglyn records and none\n // of which the merchant could otherwise reach. Best-effort on purpose:\n // a login link is a convenience, and failing to mint one must never turn\n // a working status check into an error.\n let dashboardUrl: string | undefined\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","paymentProvider","buildRoute","Route","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","ownerOrg","decoded","app","auth","verifyIdToken","ownerUid","org","uid","firestore","profileRef","collection","doc","profileSnapshot","get","accountId","account","URLSearchParams","type","email","id","set","stripeAccountId","stripeChargesEnabled","merge","chargesEnabled","Boolean","charges_enabled","platformMode","resolvePlatformMode","payoutsEnabled","payouts_enabled","stripePayoutsEnabled","stripeAccountLivemode","origin","host","index","subdomain","orgSlug","slug","productsUrl","HOST_PLUGIN","pluginSlug","fix","refresh_url","return_url","url","dashboardUrl","login","console","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,mDAAkD;AAClF,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAE9E,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEH,MAAM,EAAE;QAChEI,QAAQH,SAAS,SAAS;QAC1BI,SAAS;YACPC,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;WACpDR,UAAU;YACZ,gBAAgB;QAClB;OAEEA,UAAU;QAAES,MAAMT,OAAOU,QAAQ;IAAG;IAE1C,MAAMC,UAAU,MAAMV,SAASW,IAAI;IACnC,IAAI,CAACX,SAASY,EAAE,EAAE;;YACAF;QAAhB,MAAM,IAAIG,cAAMH,4BAAAA,iBAAAA,QAASI,KAAK,qBAAdJ,eAAgBK,OAAO,mBAAI,CAAC,OAAO,EAAEjB,KAAK,OAAO,CAAC;IACpE;IACA,OAAOY;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMM,iBAAmC,OAAOC,KAAKC;QAS7BD,4BAM4BA,WACnCT;IAftB,IAAIS,IAAIf,MAAM,KAAK,QAAQ;QACzB,OAAOgB,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACT,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOW,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEG,OAAO;QAAmD;IACtE;IACA,MAAMM,gBAAgBC,QAAOJ,6BAAAA,IAAId,OAAO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AAMhF,OAClB,CAAC,SAAS,EAAE+C,UAAU,YAAY,CAAC,EACnC,IAAIE;gBAEN8B,eAAe,QAAOC,yBAAAA,MAAOF,GAAG,MAAK,WAAWE,MAAMF,GAAG,GAAGjD;YAC9D,EAAE,OAAOZ,OAAO;gBACdgE,QAAQhE,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;gBAC1BiC;gBACAU,gBAAgB;gBAChBK;eACIiB,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAMG,OAAO,MAAMlF,OACjB,iBACA,IAAIiD,gBAAgB;YAClBD,SAASD;YACTG,MAAM;YACN0B,aAAa,GAAGJ,YAAY,gBAAgB,CAAC;YAC7CK,YAAY,GAAGL,YAAY,aAAa,CAAC;QAC3C;QAEF,OAAOnD,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEiC;YAAWU,gBAAgB;YAAOqB,KAAKI,KAAKJ,GAAG;QAAC;IAC5D,EAAE,OAAO7D,OAAO;QACdgE,QAAQhE,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAuB;IAC9D;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n firebaseAdmin,\n getOrgForHost,\n isServerReleaseFlagOnForOrg,\n} from '@aglyn/tenant-data-admin'\nimport {\n accountChargeModel,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n paymentProvider,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Merchant payments onboarding (AGL-284): Stripe Connect Express for\n * storefront selling. Same account storage the checkout reads\n * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the\n * marketplace-profile prerequisite — commerce merchants aren't necessarily\n * publishers. Only the owning org's owner may onboard (payouts land on\n * their account). 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = ownerOrg?.org?.ownerUid\n if (!ownerUid) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n if (String(ownerUid) !== decoded.uid) {\n return res\n .status(403)\n .json({ error: 'Only the organization owner can set up payments' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const profileRef = firestore.collection('profiles').doc(decoded.uid)\n const profileSnapshot = await profileRef.get()\n\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n if (!accountId) {\n // The seller's OWN Stripe account (direct charges): Stripe bills it,\n // underwrites it and gives it the full Stripe Dashboard, so the seller\n // is the merchant of record on every site sale and can refund, answer\n // a dispute and manage tax registrations there. See\n // `DIRECT_CHARGE_ACCOUNT_PARAMS`. Behind `release_direct_charges` until\n // the Terms say so; off, the platform-managed Express account and its\n // destination charges, exactly as before. The shape cannot be changed\n // once the account exists, so this is the one place it is decided.\n // Any failure to read the flag is OFF: the account it would create is\n // the one every store had before, never a shape nobody chose.\n let ownsAccount = false\n try {\n ownsAccount = await isServerReleaseFlagOnForOrg(\n 'release_direct_charges',\n String(ownerOrg?.org?.id ?? ownerOrg?.orgId ?? '') || null,\n )\n } catch {\n ownsAccount = false\n }\n const account = await stripe(\n 'accounts',\n new URLSearchParams({\n ...(ownsAccount\n ? DIRECT_CHARGE_ACCOUNT_PARAMS\n : { type: 'express' }),\n // Explicit capabilities (AGL-1994): `card_payments` for the\n // charges, and `transfers` because a destination charge (every\n // sale on an Express account, and the register and Tap to Pay on\n // either kind) requires the destination to hold it.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[profileId]': decoded.uid,\n 'metadata[purpose]': 'commerce',\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = account.id\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n\n const account = await stripe(`accounts/${accountId}`)\n const chargesEnabled = Boolean(account?.charges_enabled)\n // WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).\n //\n // Three production linkages named TEST-mode accounts, one of them with\n // `stripeChargesEnabled: true`, so its storefronts read as payments-ready\n // and could not take a payment. Nothing recorded the mode, and nothing\n // could recover it later: the Account object carries no `livemode` field\n // and an `acct_…` id is the same shape in both worlds.\n //\n // The retrieve above IS the proof. Stripe refuses cross-mode account\n // access outright — \"was a test account created with a testmode key\" —\n // so an account this key just fetched is in this key's mode, and the\n // payment provider asks Stripe (`/v1/balance.livemode`) what that mode is\n // rather than reading the key string.\n const platformMode = await paymentProvider().resolvePlatformMode()\n // Payout readiness rides along (AGL-1994): the sale gate stays on\n // charges_enabled — that is what Stripe checks at charge time — but\n // charges-yes/payouts-no was invisible to the storefront, because\n // commerce wrote only `stripeChargesEnabled`. Recording\n // `payouts_enabled` is what lets a console surface warn a merchant\n // BEFORE the first sale strands funds in a Connect account that\n // cannot pay them out.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n // Which charge shape this account takes, read off the account itself\n // every time, so a re-onboarded seller can never inherit the last\n // account's answer.\n const chargeModel = accountChargeModel(account)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripeChargeModel: chargeModel,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe bakes these into the onboarding link, so they have to be real\n // console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622\n // shape — so finishing Connect onboarding dropped the seller on a 404\n // (AGL-685). Console products is the plugin route under the org slug and\n // the host SUBDOMAIN, both of which have to be resolved here; the client\n // hook (useConsoleHostRoute) is not available to server code.\n const index = await firebaseAdmin\n .app()\n .firestore()\n .collection('hostIndex')\n .doc(hostId)\n .get()\n const subdomain = index.get('subdomain') as string | undefined\n const orgSlug = ownerOrg?.org?.slug as string | undefined\n // No slug/subdomain means no route to send them to; Stripe requires\n // both URLs, so fall back to the origin root rather than a fabricated\n // path that 404s.\n const productsUrl =\n orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'products',\n })}`\n : origin\n // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.\n //\n // This route used to return here the moment `charges_enabled` was true,\n // with a status and no link of any kind, and both console cards read the\n // `chargesEnabled` flag before they ever looked for a url. So the one\n // state that most needs Stripe — charges on, payouts NOT released, funds\n // accumulating in a Connect account that cannot pay them out — offered a\n // button labelled \"Finish payout setup in Stripe\" that raised a toast and\n // went nowhere. An Express account has no password and no direct login, so\n // a link minted here is the merchant's ONLY way in; without one the money\n // is unreachable and no surface says why.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n // The remediation flow, which is what Stripe points an account with\n // outstanding requirements at. Failures are NOT swallowed: answering\n // 200 with no link is precisely the dead end being closed here, so a\n // mint that fails surfaces as the handler's 502 and the merchant is\n // told to try again rather than left pressing a dead button.\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Payouts are flowing, so this is the VIEW: balance, payout schedule,\n // and the reason a payout failed — none of which Aglyn records and none\n // of which the merchant could otherwise reach. Best-effort on purpose:\n // a login link is a convenience, and failing to mint one must never turn\n // a working status check into an error.\n let dashboardUrl: string | undefined\n if (chargeModel === 'direct') {\n // A full Stripe account signs in to Stripe itself; login links exist\n // only for Express accounts.\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n dashboardUrl: 'https://dashboard.stripe.com/',\n })\n }\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","accountChargeModel","DIRECT_CHARGE_ACCOUNT_PARAMS","paymentProvider","buildRoute","Route","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","ownerOrg","decoded","app","auth","verifyIdToken","ownerUid","org","uid","firestore","profileRef","collection","doc","profileSnapshot","get","accountId","ownsAccount","id","orgId","account","URLSearchParams","type","email","set","stripeAccountId","stripeChargesEnabled","merge","chargesEnabled","Boolean","charges_enabled","platformMode","resolvePlatformMode","payoutsEnabled","payouts_enabled","chargeModel","stripeChargeModel","stripePayoutsEnabled","stripeAccountLivemode","origin","host","index","subdomain","orgSlug","slug","productsUrl","HOST_PLUGIN","pluginSlug","fix","refresh_url","return_url","url","dashboardUrl","login","console","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,aAAa,EACbC,aAAa,EACbC,2BAA2B,QACtB,2BAA0B;AACjC,SACEC,kBAAkB,EAClBC,4BAA4B,EAC5BC,eAAe,QACV,mDAAkD;AACzD,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAE9E,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC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,wCAAwC;YACxC,IAAIC;YACJ,IAAIjB,gBAAgB,UAAU;gBAC5B,qEAAqE;gBACrE,6BAA6B;gBAC7B,OAAO7C,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;oBAC1BiC;oBACAY,gBAAgB;oBAChBK;oBACAmB,cAAc;gBAChB;YACF;YACA,IAAI;gBACF,MAAMC,QAAQ,MAAMpF,OAClB,CAAC,SAAS,EAAE+C,UAAU,YAAY,CAAC,EACnC,IAAIK;gBAEN+B,eAAe,QAAOC,yBAAAA,MAAOF,GAAG,MAAK,WAAWE,MAAMF,GAAG,GAAGrD;YAC9D,EAAE,OAAOZ,OAAO;gBACdoE,QAAQpE,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;gBAC1BiC;gBACAY,gBAAgB;gBAChBK;eACImB,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAMG,OAAO,MAAMtF,OACjB,iBACA,IAAIoD,gBAAgB;YAClBD,SAASJ;YACTM,MAAM;YACN2B,aAAa,GAAGJ,YAAY,gBAAgB,CAAC;YAC7CK,YAAY,GAAGL,YAAY,aAAa,CAAC;QAC3C;QAEF,OAAOvD,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEiC;YAAWY,gBAAgB;YAAOuB,KAAKI,KAAKJ,GAAG;QAAC;IAC5D,EAAE,OAAOjE,OAAO;QACdoE,QAAQpE,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAuB;IAC9D;AACF,EAAC"}
|
|
@@ -19,10 +19,11 @@ import { commerceSitePermissionRefusal } from "../model/plugin-permissions.js";
|
|
|
19
19
|
import * as Aglyn from "@aglyn/aglyn/server";
|
|
20
20
|
import * as CommerceModel from "../model/index.js";
|
|
21
21
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
22
|
-
import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
22
|
+
import { connectedAccountHeader, directChargeParams, merchantAccountIsReady, saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
23
23
|
import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
|
|
24
24
|
import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
|
|
25
25
|
import { resolveManualTaxRateId } from "./manual-tax-rate.js";
|
|
26
|
+
import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
|
|
26
27
|
import { orderStatusUrl } from "./order-status-token.js";
|
|
27
28
|
import { holdPromotionSlot, promotionHoldKey } from "./promotion-hold.js";
|
|
28
29
|
import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
@@ -159,6 +160,12 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
159
160
|
error: 'Payments are not set up yet'
|
|
160
161
|
});
|
|
161
162
|
}
|
|
163
|
+
// A DIRECT charge opens the link ON the seller's own Stripe account
|
|
164
|
+
// (`Stripe-Account`), with Aglyn's take as the application fee; the
|
|
165
|
+
// destination path below is unchanged for every other seller.
|
|
166
|
+
const chargeModel = saleChargeModel(ownerProfile == null ? void 0 : ownerProfile.get('stripeChargeModel'));
|
|
167
|
+
const direct = chargeModel === 'direct';
|
|
168
|
+
const onAccount = connectedAccountHeader(chargeModel, accountId);
|
|
162
169
|
// Where Stripe returns the BUYER is the business's own site (AGL-4094):
|
|
163
170
|
// the order's status page after paying, the site's home after backing
|
|
164
171
|
// out — see the params below. The console Products page is only the
|
|
@@ -361,6 +368,14 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
361
368
|
});
|
|
362
369
|
}
|
|
363
370
|
const useStripeTax = taxDecision.kind === 'stripe-automatic';
|
|
371
|
+
// Stripe refuses `automatic_tax` on a seller's account whose Stripe Tax is
|
|
372
|
+
// not set up, and a store that chose it must not sell untaxed. Above the
|
|
373
|
+
// claim and the order write with the other tax refusals.
|
|
374
|
+
if (direct && useStripeTax && !await sellerStripeTaxActive(String(accountId))) {
|
|
375
|
+
return res.status(409).json({
|
|
376
|
+
error: SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE
|
|
377
|
+
});
|
|
378
|
+
}
|
|
364
379
|
const manualRate = taxDecision.kind === 'manual' && !taxSettings.pricesIncludeTax ? CommerceModel.resolveTaxRate(taxSettings, (_taxSettings_origin = taxSettings.origin) != null ? _taxSettings_origin : {}) : null;
|
|
365
380
|
// THE DISCOUNTED BASE (AGL-305). `chargedItemsCents` is what the line
|
|
366
381
|
// will actually be worth, and the session applies this same rate to that
|
|
@@ -443,9 +458,9 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
443
458
|
amountCents: 0
|
|
444
459
|
})) : shippingPlan.options;
|
|
445
460
|
// THE PLATFORM FEE (AGL-2152) — the advertised take PLUS Stripe's card
|
|
446
|
-
// cost, passed through at cost, at the CARD rate: the link
|
|
447
|
-
// buy-now-pay-later
|
|
448
|
-
//
|
|
461
|
+
// cost, passed through at cost, at the CARD rate: the link, like every
|
|
462
|
+
// session a site opens, excludes buy-now-pay-later (AGL-4198). A payment
|
|
463
|
+
// link is a destination charge, so
|
|
449
464
|
// Stripe debits 2.9% + 30¢ from the PLATFORM's balance; the old take-only
|
|
450
465
|
// figure meant every tier carrying a 0% rate invoiced a buyer at a loss to
|
|
451
466
|
// Aglyn, and Starter's 2% is below 2.9% so it lost money at every size too.
|
|
@@ -468,7 +483,14 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
468
483
|
// cut of what the merchant actually sells for, and Stripe's card cost is
|
|
469
484
|
// passed through on what the card actually runs for — reading `itemsCents`
|
|
470
485
|
// here would invoice the merchant a fee on money nobody paid.
|
|
471
|
-
|
|
486
|
+
//
|
|
487
|
+
// A direct charge's fee is the take alone: Stripe bills the seller its
|
|
488
|
+
// own card fee and charges the platform nothing for the sale.
|
|
489
|
+
const feeCents = Aglyn.resolveTransactionFeeCents(ownerOrg == null ? void 0 : ownerOrg.org, (_product_type1 = product.type) != null ? _product_type1 : 'physical', chargedItemsCents, chargedItemsCents + taxCents + shippingCeilingCents, direct ? {
|
|
490
|
+
direct: true
|
|
491
|
+
} : {
|
|
492
|
+
stripeTax: useStripeTax
|
|
493
|
+
});
|
|
472
494
|
// Stripe Tax mode leaves the tax 0 at composition time and the webhook
|
|
473
495
|
// folds the computed figure in — the same additive shape AGL-1792 used for
|
|
474
496
|
// shipping, and for the same reason: only Stripe knows it.
|
|
@@ -637,6 +659,8 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
637
659
|
headers: {
|
|
638
660
|
'Idempotency-Key': `${claim.stripeKey}-tax-rate`
|
|
639
661
|
}
|
|
662
|
+
} : {}, onAccount['Stripe-Account'] ? {
|
|
663
|
+
stripeAccount: onAccount['Stripe-Account']
|
|
640
664
|
} : {}))) != null ? _ref2 : '';
|
|
641
665
|
if (!draftTaxRateId) {
|
|
642
666
|
// A VISIBLE refusal rather than an untaxed payment link — the silent
|
|
@@ -666,7 +690,7 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
666
690
|
'line_items[0][price_data][currency]': 'usd',
|
|
667
691
|
'line_items[0][price_data][unit_amount]': String(chargedUnitAmountCents),
|
|
668
692
|
'line_items[0][price_data][product_data][name]': chargedLineName
|
|
669
|
-
}, CommerceModel.destinationChargeParams({
|
|
693
|
+
}, direct ? directChargeParams(feeCents) : CommerceModel.destinationChargeParams({
|
|
670
694
|
accountId: String(accountId),
|
|
671
695
|
feeCents,
|
|
672
696
|
taxOwner: useStripeTax ? 'platform' : 'merchant',
|
|
@@ -688,13 +712,15 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
688
712
|
'metadata[variantId]': variantId
|
|
689
713
|
} : {}, {
|
|
690
714
|
'metadata[feeCents]': String(feeCents)
|
|
691
|
-
},
|
|
715
|
+
}, direct ? {
|
|
716
|
+
'metadata[chargeModel]': 'direct'
|
|
717
|
+
} : {}, shippingPlan.quotedPostalCode ? {
|
|
692
718
|
'metadata[shippingQuotePostalCode]': shippingPlan.quotedPostalCode
|
|
693
719
|
} : {}, appliedDiscountId ? {
|
|
694
720
|
'metadata[discountId]': appliedDiscountId
|
|
695
721
|
} : {}, discountHoldKey ? {
|
|
696
722
|
'metadata[discountHoldKey]': discountHoldKey
|
|
697
|
-
} : {}, useStripeTax ? {
|
|
723
|
+
} : {}, useStripeTax && !direct ? {
|
|
698
724
|
'metadata[transferCents]': String(CommerceModel.platformLiableTransferCents({
|
|
699
725
|
feeCents,
|
|
700
726
|
merchantGoodsCents: chargedItemsCents,
|
|
@@ -714,9 +740,8 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
714
740
|
// The payment methods the merchant switched off reach the payment link
|
|
715
741
|
// too (AGL-3629). A hosted Stripe page shows Apple Pay and Google Pay by
|
|
716
742
|
// device and cannot hide them per merchant; everything else follows.
|
|
717
|
-
//
|
|
718
|
-
|
|
719
|
-
CommerceModel.appendStorefrontPaymentMethodParams(params, CommerceModel.payLinkPaymentMethodControls(CommerceModel.resolveStorefrontPaymentMethodControls(CommerceModel.normalizeStorefrontPaymentMethodSettings(storeSettings.get('paymentMethods')))));
|
|
743
|
+
// Buy-now-pay-later is excluded too, whatever the store chose (AGL-4198).
|
|
744
|
+
CommerceModel.appendStorefrontPaymentMethodParams(params, CommerceModel.resolveStorefrontPaymentMethodControls(CommerceModel.normalizeStorefrontPaymentMethodSettings(storeSettings.get('paymentMethods'))));
|
|
720
745
|
const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {
|
|
721
746
|
method: 'POST',
|
|
722
747
|
headers: _extends({
|
|
@@ -724,7 +749,7 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
|
|
|
724
749
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
725
750
|
}, claim.stripeKey ? {
|
|
726
751
|
'Idempotency-Key': claim.stripeKey
|
|
727
|
-
} : {}),
|
|
752
|
+
} : {}, onAccount),
|
|
728
753
|
body: params.toString()
|
|
729
754
|
});
|
|
730
755
|
const session = await response.json();
|