@stacksjs/payments 0.75.514 → 0.75.518

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.
Files changed (45) hide show
  1. package/dist/billable/charge.js +1 -1
  2. package/dist/billable/checkout.js +1 -1
  3. package/dist/billable/customer.js +1 -1
  4. package/dist/billable/intent.js +1 -1
  5. package/dist/billable/invoice.js +1 -1
  6. package/dist/billable/payment-method.js +1 -1
  7. package/dist/billable/portal.js +1 -1
  8. package/dist/billable/price.js +1 -1
  9. package/dist/billable/product.js +1 -1
  10. package/dist/billable/setup-products.js +1 -1
  11. package/dist/billable/subscription.js +1 -1
  12. package/dist/billable/transaction.js +1 -1
  13. package/dist/billable/webhook-events.js +1 -1
  14. package/dist/billable/webhook.js +1 -1
  15. package/dist/connect/account.js +1 -1
  16. package/dist/connect/charge.js +1 -1
  17. package/dist/connect/destination.js +1 -1
  18. package/dist/connect/direct.js +1 -1
  19. package/dist/connect/financials.js +1 -1
  20. package/dist/connect/invoice-collection.js +1 -1
  21. package/dist/connect/invoice-credit.js +1 -1
  22. package/dist/connect/invoice-fee.js +1 -1
  23. package/dist/connect/invoice-price.js +1 -1
  24. package/dist/connect/invoice-purchase.js +1 -1
  25. package/dist/connect/invoice-tax.js +1 -1
  26. package/dist/connect/pagination.js +1 -1
  27. package/dist/connect/payout.js +1 -1
  28. package/dist/connect/refund.js +1 -1
  29. package/dist/connect/subscription.js +1 -1
  30. package/dist/connect/tax.js +1 -1
  31. package/dist/connect/transfer.js +1 -1
  32. package/dist/direct-debit.js +1 -1
  33. package/dist/driver/adyen.js +1 -1
  34. package/dist/driver/index.js +1 -1
  35. package/dist/driver/lemonsqueezy.js +1 -1
  36. package/dist/driver/paddle-checkout.js +1 -1
  37. package/dist/driver/paddle.js +1 -1
  38. package/dist/driver/stripe.js +1 -1
  39. package/dist/driver/types.js +1 -1
  40. package/dist/drivers/stripe.js +1 -1
  41. package/dist/idempotency.js +1 -1
  42. package/dist/payment.js +1 -1
  43. package/dist/subscription-state.js +1 -1
  44. package/dist/terminal.js +1 -1
  45. package/package.json +8 -8
@@ -1 +1 @@
1
- import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";import{freshIdempotencyKey}from"../idempotency";function defaultCurrency(){const cfg=config||{};return(cfg.payment?.currency||cfg.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}export const manageCharge=(()=>{async function createPayment(user,amount,options){const defaultOptions={currency:defaultCurrency(),amount};if(manageCustomer.hasStripeId(user))defaultOptions.customer=user.stripe_id??void 0;const mergedOptions={...defaultOptions,...options};return await stripe.paymentIntents.create(mergedOptions,{idempotencyKey:freshIdempotencyKey("payment_intent.create",user.id,amount)})}async function findPayment(id){try{return await stripe.paymentIntents.retrieve(id)}catch(error){log.error(error);return null}}async function refund(paymentIntentId,options={}){if(!paymentIntentId||typeof paymentIntentId!=="string")throw Error("[payments/refund] paymentIntentId is required");if(options.amount!=null){if(typeof options.amount!=="number"||!Number.isFinite(options.amount)||options.amount<=0)throw Error("[payments/refund] amount must be a positive finite number");try{const original=await stripe.paymentIntents.retrieve(paymentIntentId),captured=original.amount_received??original.amount;if(captured&&options.amount>captured)throw Error(`[payments/refund] amount ${options.amount} exceeds captured amount ${captured}`)}catch(err){if(err instanceof Error&&err.message.startsWith("[payments/refund]"))throw err}}const{idempotencyKey,...rest}=options,refundParams={payment_intent:paymentIntentId,...rest},requestOptions={idempotencyKey:idempotencyKey||`refund:${paymentIntentId}:${rest.amount??"full"}`};return await stripe.refunds.create(refundParams,requestOptions)}async function charge(user,amount,paymentMethod,options){const mergedOptions={...{confirmation_method:"automatic",confirm:!0,payment_method:paymentMethod,currency:defaultCurrency(),amount},...options};return await createPayment(user,amount,mergedOptions)}return{createPayment,charge,findPayment,refund}})();
1
+ import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";import{freshIdempotencyKey}from"../idempotency";function defaultCurrency(){const cfg=config||{};const fromConfig=cfg.payment?.currency||cfg.billing?.currency;return(fromConfig||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}export const manageCharge=(()=>{async function createPayment(user,amount,options){const defaultOptions={currency:defaultCurrency(),amount};if(manageCustomer.hasStripeId(user)){defaultOptions.customer=user.stripe_id??undefined}const mergedOptions={...defaultOptions,...options};return await stripe.paymentIntents.create(mergedOptions,{idempotencyKey:freshIdempotencyKey("payment_intent.create",user.id,amount)})}async function findPayment(id){try{const stripePaymentIntent=await stripe.paymentIntents.retrieve(id);return stripePaymentIntent}catch(error){log.error(error);return null}}async function refund(paymentIntentId,options={}){if(!paymentIntentId||typeof paymentIntentId!=="string"){throw new Error("[payments/refund] paymentIntentId is required")}if(options.amount!=null){if(typeof options.amount!=="number"||!Number.isFinite(options.amount)||options.amount<=0){throw new Error("[payments/refund] amount must be a positive finite number")}try{const original=await stripe.paymentIntents.retrieve(paymentIntentId);const captured=original.amount_received??original.amount;if(captured&&options.amount>captured){throw new Error(`[payments/refund] amount ${options.amount} exceeds captured amount ${captured}`)}}catch(err){if(err instanceof Error&&err.message.startsWith("[payments/refund]"))throw err}}const{idempotencyKey,...rest}=options;const refundParams={payment_intent:paymentIntentId,...rest};const requestOptions={idempotencyKey:idempotencyKey||`refund:${paymentIntentId}:${rest.amount??"full"}`};return await stripe.refunds.create(refundParams,requestOptions)}async function charge(user,amount,paymentMethod,options){const defaultOptions={confirmation_method:"automatic",confirm:true,payment_method:paymentMethod,currency:defaultCurrency(),amount};const mergedOptions={...defaultOptions,...options};const payment=await createPayment(user,amount,mergedOptions);return payment}return{createPayment,charge,findPayment,refund}})();
@@ -1 +1 @@
1
- import{config}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";export function assertSameOriginUrl(url,label){if(!url)return;let parsed;try{parsed=new URL(url)}catch{throw Error(`[payments/checkout] ${label} is not a valid URL: ${url}`)}const appUrl=config?.app?.url;if(!appUrl)return;let appOrigin;try{appOrigin=new URL(appUrl.startsWith("http")?appUrl:`https://${appUrl}`).origin}catch{return}if(parsed.origin!==appOrigin)throw Error(`[payments/checkout] ${label} origin (${parsed.origin}) does not match app origin (${appOrigin})`)}export const manageCheckout=(()=>{async function create(user,params){const customerId=params.customer||user.stripe_id;if(!customerId)throw Error("User has no Stripe customer");assertSameOriginUrl(params.success_url,"success_url");assertSameOriginUrl(params.cancel_url,"cancel_url");const mergedParams={...{customer:customerId,mode:"payment",success_url:params.success_url,cancel_url:params.cancel_url},...params};return await stripe.checkout.sessions.create(mergedParams,{idempotencyKey:freshIdempotencyKey("checkout.session.create",user.id)})}return{create}})();
1
+ import{config}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";export function assertSameOriginUrl(url,label){if(!url)return;let parsed;try{parsed=new URL(url)}catch{throw new Error(`[payments/checkout] ${label} is not a valid URL: ${url}`)}const appUrl=config?.app?.url;if(!appUrl)return;let appOrigin;try{appOrigin=new URL(appUrl.startsWith("http")?appUrl:`https://${appUrl}`).origin}catch{return}if(parsed.origin!==appOrigin){throw new Error(`[payments/checkout] ${label} origin (${parsed.origin}) does not match app origin (${appOrigin})`)}}export const manageCheckout=(()=>{async function create(user,params){const customerId=params.customer||user.stripe_id;if(!customerId){throw new Error("User has no Stripe customer")}assertSameOriginUrl(params.success_url,"success_url");assertSameOriginUrl(params.cancel_url,"cancel_url");const defaultParams={customer:customerId,mode:"payment",success_url:params.success_url,cancel_url:params.cancel_url};const mergedParams={...defaultParams,...params};return await stripe.checkout.sessions.create(mergedParams,{idempotencyKey:freshIdempotencyKey("checkout.session.create",user.id)})}return{create}})();
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{stacksIdempotencyKey}from"../idempotency";export const manageCustomer=(()=>{function stripeId(user){return user.stripe_id||""}function stripeAddress(options){return{line1:options.address?.line1,city:options.address?.city,state:options.address?.state,postal_code:options.address?.postal_code,country:options.address?.country}}function stripePreferredLocales(){return[]}function stripeMetadata(metadata){return metadata}function hasStripeId(user){return Boolean(user.stripe_id)}async function createStripeCustomer(user,options={}){if(hasStripeId(user))throw Error("Customer already created");if(!options.name&&stripeName(user))options.name=stripeName(user);if(!options.email&&stripeEmail(user))options.email=stripeEmail(user);const customer=await stripe.customers.create(options,{idempotencyKey:stacksIdempotencyKey("customer.create",user.id)});await user.update({stripe_id:customer.id});return customer}async function updateStripeCustomer(user,options={}){if(!user.stripe_id)throw Error("User does not have a Stripe customer ID. Create a customer first.");return await stripe.customers.update(user.stripe_id,options,{idempotencyKey:stacksIdempotencyKey("customer.update",user.id,user.stripe_id)})}async function deleteStripeUser(user){if(!hasStripeId(user))throw Error("User does not have a Stripe ID");try{if(!user.stripe_id)throw Error("User has no Stripe ID");const deletedCustomer=await stripe.customers.del(user.stripe_id);await user.update({stripe_id:""});return deletedCustomer}catch(error){if(error.statusCode===404)throw Error("Customer not found in Stripe");throw error}}async function createOrGetStripeUser(user,options={}){if(!hasStripeId(user))return await createStripeCustomer(user,options);try{const customer=await stripe.customers.retrieve(user.stripe_id);if(customer.deleted)throw Error("Customer was deleted");return customer}catch(error){if(error.statusCode===404)return await createStripeCustomer(user,options);throw error}}async function retrieveStripeUser(user){if(!hasStripeId(user))return;try{const customer=await stripe.customers.retrieve(user.stripe_id);if(customer.deleted)throw Error("Customer was deleted in Stripe");return customer}catch(error){if(error.statusCode===404)throw Error("Customer not found in Stripe");throw error}}async function createOrUpdateStripeUser(user,options){if(!hasStripeId(user))return await createStripeCustomer(user,options);try{if((await stripe.customers.retrieve(user.stripe_id)).deleted)return await createStripeCustomer(user,options);return await updateStripeCustomer(user,options)}catch(error){if(error.statusCode===404)return await createStripeCustomer(user,options);throw error}}async function syncStripeCustomerDetails(user,options){return await updateStripeCustomer(user,{name:stripeName(user),email:stripeEmail(user),address:stripeAddress(options),preferred_locales:stripePreferredLocales(),metadata:options.metadata?stripeMetadata(options.metadata):{}})}function stripeName(user){return user.name||""}function stripeEmail(user){return user.email||""}return{stripeId,hasStripeId,createStripeCustomer,updateStripeCustomer,createOrGetStripeUser,createOrUpdateStripeUser,deleteStripeUser,retrieveStripeUser,syncStripeCustomerDetails}})();
1
+ import{stripe}from"../drivers/stripe";import{stacksIdempotencyKey}from"../idempotency";export const manageCustomer=(()=>{function stripeId(user){return user.stripe_id||""}function stripeAddress(options){return{line1:options.address?.line1,city:options.address?.city,state:options.address?.state,postal_code:options.address?.postal_code,country:options.address?.country}}function stripePreferredLocales(){return[]}function stripeMetadata(metadata){return metadata}function hasStripeId(user){return Boolean(user.stripe_id)}async function createStripeCustomer(user,options={}){if(hasStripeId(user)){throw new Error("Customer already created")}if(!options.name&&stripeName(user)){options.name=stripeName(user)}if(!options.email&&stripeEmail(user)){options.email=stripeEmail(user)}const customer=await stripe.customers.create(options,{idempotencyKey:stacksIdempotencyKey("customer.create",user.id)});await user.update({stripe_id:customer.id});return customer}async function updateStripeCustomer(user,options={}){if(!user.stripe_id){throw new Error("User does not have a Stripe customer ID. Create a customer first.")}const customer=await stripe.customers.update(user.stripe_id,options,{idempotencyKey:stacksIdempotencyKey("customer.update",user.id,user.stripe_id)});return customer}async function deleteStripeUser(user){if(!hasStripeId(user)){throw new Error("User does not have a Stripe ID")}try{if(!user.stripe_id){throw new Error("User has no Stripe ID")}const deletedCustomer=await stripe.customers.del(user.stripe_id);await user.update({stripe_id:""});return deletedCustomer}catch(error){if(error.statusCode===404){throw new Error("Customer not found in Stripe")}throw error}}async function createOrGetStripeUser(user,options={}){if(!hasStripeId(user)){return await createStripeCustomer(user,options)}try{const customer=await stripe.customers.retrieve(user.stripe_id);if(customer.deleted){throw new Error("Customer was deleted")}return customer}catch(error){if(error.statusCode===404){return await createStripeCustomer(user,options)}throw error}}async function retrieveStripeUser(user){if(!hasStripeId(user)){return}try{const customer=await stripe.customers.retrieve(user.stripe_id);if(customer.deleted){throw new Error("Customer was deleted in Stripe")}return customer}catch(error){if(error.statusCode===404){throw new Error("Customer not found in Stripe")}throw error}}async function createOrUpdateStripeUser(user,options){if(!hasStripeId(user)){return await createStripeCustomer(user,options)}try{const customer=await stripe.customers.retrieve(user.stripe_id);if(customer.deleted){return await createStripeCustomer(user,options)}return await updateStripeCustomer(user,options)}catch(error){if(error.statusCode===404){return await createStripeCustomer(user,options)}throw error}}async function syncStripeCustomerDetails(user,options){return await updateStripeCustomer(user,{name:stripeName(user),email:stripeEmail(user),address:stripeAddress(options),preferred_locales:stripePreferredLocales(),metadata:options.metadata?stripeMetadata(options.metadata):{}})}function stripeName(user){return user.name||""}function stripeEmail(user){return user.email||""}return{stripeId,hasStripeId,createStripeCustomer,updateStripeCustomer,createOrGetStripeUser,createOrUpdateStripeUser,deleteStripeUser,retrieveStripeUser,syncStripeCustomerDetails}})();
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";import{freshIdempotencyKey}from"../idempotency";export const manageSetupIntent=(()=>{async function create(user,params){const mergedParams={...{customer:await manageCustomer.createOrGetStripeUser(user,{}).then((customer)=>{if(!customer||!customer.id)throw Error("Customer does not exist in Stripe");return customer.id}),allowed_payment_method_types:["card"]},...params};return await stripe.setupIntents.create(mergedParams,{idempotencyKey:freshIdempotencyKey("setup_intent.create",user.id)})}return{create}})();
1
+ import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";import{freshIdempotencyKey}from"../idempotency";export const manageSetupIntent=(()=>{async function create(user,params){const customerId=await manageCustomer.createOrGetStripeUser(user,{}).then((customer)=>{if(!customer||!customer.id){throw new Error("Customer does not exist in Stripe")}return customer.id});const defaultParams={customer:customerId,allowed_payment_method_types:["card"]};const mergedParams={...defaultParams,...params};return await stripe.setupIntents.create(mergedParams,{idempotencyKey:freshIdempotencyKey("setup_intent.create",user.id)})}return{create}})();
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";export const INVOICE_LIST_EXPAND=["data.payments"],manageInvoice=(()=>{async function list(user){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");if(!user.stripe_id)throw Error("User has no Stripe ID");return await stripe.invoices.list({customer:user.stripe_id,expand:[...INVOICE_LIST_EXPAND]})}return{list}})();
1
+ import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";export const INVOICE_LIST_EXPAND=["data.payments"];export const manageInvoice=(()=>{async function list(user){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}if(!user.stripe_id){throw new Error("User has no Stripe ID")}const invoices=await stripe.invoices.list({customer:user.stripe_id,expand:[...INVOICE_LIST_EXPAND]});return invoices}return{list}})();
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";import{PaymentMethod}from"@stacksjs/orm";import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";export const managePaymentMethod=(()=>{async function addPaymentMethod(user,paymentMethod){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");let stripePaymentMethod;if(typeof paymentMethod==="string")stripePaymentMethod=await stripe.paymentMethods.retrieve(paymentMethod);else stripePaymentMethod=paymentMethod;if(stripePaymentMethod.customer!==user.stripe_id)stripePaymentMethod=await stripe.paymentMethods.attach(stripePaymentMethod.id,{customer:user.stripe_id});await storePaymentMethod(user,stripePaymentMethod);return stripePaymentMethod}async function setUserDefaultPayment(user,paymentMethodId){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");const paymentMethod=await stripe.paymentMethods.retrieve(paymentMethodId),paymentMethodModel=await db.selectFrom("payment_methods").where("provider_id","=",paymentMethodId).selectAll().executeTakeFirst();if(!user.stripe_id)throw Error("User has no Stripe ID");if(paymentMethod.customer!==user.stripe_id)await stripe.paymentMethods.attach(paymentMethod.id,{customer:user.stripe_id});const updatedCustomer=await stripe.customers.update(user.stripe_id,{invoice_settings:{default_payment_method:paymentMethodId}});await db.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",user.id).executeTakeFirst();if(paymentMethodModel)await updateDefault(paymentMethodModel);return updatedCustomer}async function setDefaultPaymentMethod(user,paymentId){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");const pm=await db.selectFrom("payment_methods").where("id","=",paymentId).selectAll().executeTakeFirst();if(!pm?.provider_id)throw Error(`Payment method with id ${paymentId} not found`);const paymentMethod=await stripe.paymentMethods.retrieve(String(pm.provider_id));if(paymentMethod.customer!==user.stripe_id)await stripe.paymentMethods.attach(paymentMethod.id,{customer:user.stripe_id});if(!user.stripe_id)throw Error("User has no Stripe ID");const updatedCustomer=await stripe.customers.update(user.stripe_id,{invoice_settings:{default_payment_method:String(pm.provider_id)}});await db.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",user.id).executeTakeFirst();await db.updateTable("payment_methods").set({is_default:!0}).where("id","=",paymentId).executeTakeFirst();return updatedCustomer}async function storePaymentMethod(user,paymentMethod){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");if(!paymentMethod.card?.brand||!paymentMethod.card?.exp_year||!paymentMethod.card?.exp_month)throw Error("Invalid payment method: missing required card details");const method={type:"card",lastFour:String(paymentMethod.card.last4),brand:paymentMethod.card.brand,expYear:paymentMethod.card.exp_year,expMonth:paymentMethod.card.exp_month,user_id:user.id,providerId:paymentMethod.id};if(paymentMethod.customer!==user.stripe_id)await stripe.paymentMethods.attach(paymentMethod.id,{customer:user.stripe_id});return await PaymentMethod.create(method)}async function updateDefault(paymentMethodModel){return await paymentMethodModel.update({is_default:!0})}async function deletePaymentMethod(user,paymentMethodId){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");const pm=typeof paymentMethodId==="string"?await db.selectFrom("payment_methods").where("provider_id","=",paymentMethodId).selectAll().executeTakeFirst():await PaymentMethod.find(paymentMethodId);if(!pm?.provider_id)throw Error(`Payment method with id ${paymentMethodId} not found`);if((await stripe.paymentMethods.retrieve(String(pm.provider_id))).customer!==user.stripe_id)throw Error("Payment method does not belong to this customer");await pm.delete();return await stripe.paymentMethods.detach(String(pm.provider_id))}async function updatePaymentMethod(user,paymentMethodId,updateParams){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");if((await stripe.paymentMethods.retrieve(paymentMethodId)).customer!==user.stripe_id)throw Error("Payment method does not belong to this customer");return await stripe.paymentMethods.update(paymentMethodId,updateParams)}async function listPaymentMethods(user){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");return await db.selectFrom("payment_methods").selectAll().where("user_id","=",user.id).execute()}async function retrievePaymentMethod(user,paymentMethodId){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");return await db.selectFrom("payment_methods").where("id","=",paymentMethodId).selectAll().executeTakeFirst()}async function retrieveDefaultPaymentMethod(user){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");return await PaymentMethod.where("user_id",user.id).where("is_default",!0).first()}return{addPaymentMethod,deletePaymentMethod,retrieveDefaultPaymentMethod,updatePaymentMethod,listPaymentMethods,setDefaultPaymentMethod,storePaymentMethod,retrievePaymentMethod,setUserDefaultPayment}})();
1
+ import{db}from"@stacksjs/database/runtime";import{PaymentMethod}from"@stacksjs/orm";import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";export const managePaymentMethod=(()=>{async function addPaymentMethod(user,paymentMethod){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}let stripePaymentMethod;if(typeof paymentMethod==="string"){stripePaymentMethod=await stripe.paymentMethods.retrieve(paymentMethod)}else{stripePaymentMethod=paymentMethod}if(stripePaymentMethod.customer!==user.stripe_id){stripePaymentMethod=await stripe.paymentMethods.attach(stripePaymentMethod.id,{customer:user.stripe_id})}await storePaymentMethod(user,stripePaymentMethod);return stripePaymentMethod}async function setUserDefaultPayment(user,paymentMethodId){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const paymentMethod=await stripe.paymentMethods.retrieve(paymentMethodId);const paymentMethodModel=await db.selectFrom("payment_methods").where("provider_id","=",paymentMethodId).selectAll().executeTakeFirst();if(!user.stripe_id){throw new Error("User has no Stripe ID")}if(paymentMethod.customer!==user.stripe_id){await stripe.paymentMethods.attach(paymentMethod.id,{customer:user.stripe_id})}const updatedCustomer=await stripe.customers.update(user.stripe_id,{invoice_settings:{default_payment_method:paymentMethodId}});await db.updateTable("payment_methods").set({is_default:false}).where("user_id","=",user.id).executeTakeFirst();if(paymentMethodModel){await updateDefault(paymentMethodModel)}return updatedCustomer}async function setDefaultPaymentMethod(user,paymentId){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const pm=await db.selectFrom("payment_methods").where("id","=",paymentId).selectAll().executeTakeFirst();if(!pm?.provider_id){throw new Error(`Payment method with id ${paymentId} not found`)}const paymentMethod=await stripe.paymentMethods.retrieve(String(pm.provider_id));if(paymentMethod.customer!==user.stripe_id){await stripe.paymentMethods.attach(paymentMethod.id,{customer:user.stripe_id})}if(!user.stripe_id){throw new Error("User has no Stripe ID")}const updatedCustomer=await stripe.customers.update(user.stripe_id,{invoice_settings:{default_payment_method:String(pm.provider_id)}});await db.updateTable("payment_methods").set({is_default:false}).where("user_id","=",user.id).executeTakeFirst();await db.updateTable("payment_methods").set({is_default:true}).where("id","=",paymentId).executeTakeFirst();return updatedCustomer}async function storePaymentMethod(user,paymentMethod){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}if(!paymentMethod.card?.brand||!paymentMethod.card?.exp_year||!paymentMethod.card?.exp_month){throw new Error("Invalid payment method: missing required card details")}const method={type:"card",lastFour:String(paymentMethod.card.last4),brand:paymentMethod.card.brand,expYear:paymentMethod.card.exp_year,expMonth:paymentMethod.card.exp_month,user_id:user.id,providerId:paymentMethod.id};if(paymentMethod.customer!==user.stripe_id){await stripe.paymentMethods.attach(paymentMethod.id,{customer:user.stripe_id})}const model=await PaymentMethod.create(method);return model}async function updateDefault(paymentMethodModel){const paymentMethod=await paymentMethodModel.update({is_default:true});return paymentMethod}async function deletePaymentMethod(user,paymentMethodId){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const pm=typeof paymentMethodId==="string"?await db.selectFrom("payment_methods").where("provider_id","=",paymentMethodId).selectAll().executeTakeFirst():await PaymentMethod.find(paymentMethodId);if(!pm?.provider_id){throw new Error(`Payment method with id ${paymentMethodId} not found`)}const paymentMethod=await stripe.paymentMethods.retrieve(String(pm.provider_id));if(paymentMethod.customer!==user.stripe_id){throw new Error("Payment method does not belong to this customer")}await pm.delete();return await stripe.paymentMethods.detach(String(pm.provider_id))}async function updatePaymentMethod(user,paymentMethodId,updateParams){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const paymentMethod=await stripe.paymentMethods.retrieve(paymentMethodId);if(paymentMethod.customer!==user.stripe_id){throw new Error("Payment method does not belong to this customer")}return await stripe.paymentMethods.update(paymentMethodId,updateParams)}async function listPaymentMethods(user){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const paymentMethods=await db.selectFrom("payment_methods").selectAll().where("user_id","=",user.id).execute();return paymentMethods}async function retrievePaymentMethod(user,paymentMethodId){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const paymentMethod=await db.selectFrom("payment_methods").where("id","=",paymentMethodId).selectAll().executeTakeFirst();return paymentMethod}async function retrieveDefaultPaymentMethod(user){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const paymentMethod=await PaymentMethod.where("user_id",user.id).where("is_default",true).first();return paymentMethod}return{addPaymentMethod,deletePaymentMethod,retrieveDefaultPaymentMethod,updatePaymentMethod,listPaymentMethods,setDefaultPaymentMethod,storePaymentMethod,retrievePaymentMethod,setUserDefaultPayment}})();
@@ -1 +1 @@
1
- import{app}from"@stacksjs/config";import{stripe}from"../drivers/stripe";export function managedPortalTag(appName=app?.name||"stacks"){return{managed_by:"stacks",stacks_app:appName}}export function portalConfigurationParams(portal,appName){const emailUpdate=portal.emailUpdate!==!1,cancel=portal.cancel??"at_period_end",businessProfile={};if(portal.headline)businessProfile.headline=portal.headline;if(portal.privacyPolicyUrl)businessProfile.privacy_policy_url=portal.privacyPolicyUrl;if(portal.termsOfServiceUrl)businessProfile.terms_of_service_url=portal.termsOfServiceUrl;return{features:{customer_update:emailUpdate?{enabled:!0,allowed_updates:["email"]}:{enabled:!1},invoice_history:{enabled:portal.invoiceHistory!==!1},payment_method_update:{enabled:portal.paymentMethodUpdate!==!1},subscription_cancel:cancel===!1?{enabled:!1}:{enabled:!0,mode:cancel}},...Object.keys(businessProfile).length?{business_profile:businessProfile}:{},...portal.returnUrl?{default_return_url:portal.returnUrl}:{},metadata:managedPortalTag(appName)}}export function portalConfigurationMatches(live,params){const want=params.features,have=live.features,cancelWanted=want.subscription_cancel;return have.invoice_history.enabled===want.invoice_history?.enabled&&have.payment_method_update.enabled===want.payment_method_update?.enabled&&have.customer_update.enabled===want.customer_update?.enabled&&have.subscription_cancel.enabled===cancelWanted?.enabled&&(!cancelWanted?.enabled||have.subscription_cancel.mode===cancelWanted.mode)&&(live.default_return_url??void 0)===(params.default_return_url||void 0)&&(live.business_profile.headline??void 0)===(params.business_profile?.headline||void 0)}export async function findManagedPortalConfiguration(appName,client=stripe){const tag=managedPortalTag(appName);for await(const configuration of client.billingPortal.configurations.list({active:!0,limit:100}))if(configuration.metadata?.managed_by===tag.managed_by&&configuration.metadata?.stacks_app===tag.stacks_app)return configuration;return}export const manageBillingPortal={async createSession(customerId,options={}){const configuration=await findManagedPortalConfiguration();return stripe.billingPortal.sessions.create({customer:customerId,...options.returnUrl?{return_url:options.returnUrl}:{},...configuration?{configuration:configuration.id}:{}})}};
1
+ import{app}from"@stacksjs/config";import{stripe}from"../drivers/stripe";export function managedPortalTag(appName=app?.name||"stacks"){return{managed_by:"stacks",stacks_app:appName}}export function portalConfigurationParams(portal,appName){const emailUpdate=portal.emailUpdate!==false;const cancel=portal.cancel??"at_period_end";const businessProfile={};if(portal.headline)businessProfile.headline=portal.headline;if(portal.privacyPolicyUrl)businessProfile.privacy_policy_url=portal.privacyPolicyUrl;if(portal.termsOfServiceUrl)businessProfile.terms_of_service_url=portal.termsOfServiceUrl;return{features:{customer_update:emailUpdate?{enabled:true,allowed_updates:["email"]}:{enabled:false},invoice_history:{enabled:portal.invoiceHistory!==false},payment_method_update:{enabled:portal.paymentMethodUpdate!==false},subscription_cancel:cancel===false?{enabled:false}:{enabled:true,mode:cancel}},...Object.keys(businessProfile).length?{business_profile:businessProfile}:{},...portal.returnUrl?{default_return_url:portal.returnUrl}:{},metadata:managedPortalTag(appName)}}export function portalConfigurationMatches(live,params){const want=params.features;const have=live.features;const cancelWanted=want.subscription_cancel;return have.invoice_history.enabled===want.invoice_history?.enabled&&have.payment_method_update.enabled===want.payment_method_update?.enabled&&have.customer_update.enabled===want.customer_update?.enabled&&have.subscription_cancel.enabled===cancelWanted?.enabled&&(!cancelWanted?.enabled||have.subscription_cancel.mode===cancelWanted.mode)&&(live.default_return_url??undefined)===(params.default_return_url||undefined)&&(live.business_profile.headline??undefined)===(params.business_profile?.headline||undefined)}export async function findManagedPortalConfiguration(appName,client=stripe){const tag=managedPortalTag(appName);for await(const configuration of client.billingPortal.configurations.list({active:true,limit:100})){if(configuration.metadata?.managed_by===tag.managed_by&&configuration.metadata?.stacks_app===tag.stacks_app)return configuration}return}export const manageBillingPortal={async createSession(customerId,options={}){const configuration=await findManagedPortalConfiguration();return stripe.billingPortal.sessions.create({customer:customerId,...options.returnUrl?{return_url:options.returnUrl}:{},...configuration?{configuration:configuration.id}:{}})}};
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";export const managePrice=(()=>{async function retrieveByLookupKey(lookupKey){const prices=await stripe.prices.list({lookup_keys:[lookupKey]});if(!prices.data.length)return;return prices.data[0]}async function createOrGet(lookupKey,params){const existingPrice=await retrieveByLookupKey(lookupKey);if(existingPrice)return existingPrice;return await stripe.prices.create({...params,lookup_key:lookupKey})}return{retrieveByLookupKey,createOrGet}})();
1
+ import{stripe}from"../drivers/stripe";export const managePrice=(()=>{async function retrieveByLookupKey(lookupKey){const prices=await stripe.prices.list({lookup_keys:[lookupKey]});if(!prices.data.length)return;return prices.data[0]}async function createOrGet(lookupKey,params){const existingPrice=await retrieveByLookupKey(lookupKey);if(existingPrice)return existingPrice;const newPrice=await stripe.prices.create({...params,lookup_key:lookupKey});return newPrice}return{retrieveByLookupKey,createOrGet}})();
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";export const manageProduct=(()=>{async function create(params){return await stripe.products.create(params)}async function retrieve(productId){return await stripe.products.retrieve(productId)}async function update(productId,params){return await stripe.products.update(productId,params)}async function list(params={}){return await stripe.products.list({active:!0,...params})}async function archive(productId){return await stripe.products.update(productId,{active:!1})}async function createWithPrice(productParams,priceParams){const product=await stripe.products.create(productParams),price=await stripe.prices.create({...priceParams,product:product.id});return{product,price}}async function search(query,params={query:""}){return await stripe.products.search({...params,query})}return{create,retrieve,update,list,archive,createWithPrice,search}})(),managePriceExtended=(()=>{async function create(params){return await stripe.prices.create(params)}async function retrieve(priceId){return await stripe.prices.retrieve(priceId)}async function update(priceId,params){return await stripe.prices.update(priceId,params)}async function list(params={}){return await stripe.prices.list({active:!0,...params})}async function listByProduct(productId,params={}){return await stripe.prices.list({product:productId,active:!0,...params})}async function search(query,params={query:""}){return await stripe.prices.search({...params,query})}async function archive(priceId){return await stripe.prices.update(priceId,{active:!1})}return{create,retrieve,update,list,listByProduct,search,archive}})(),manageCoupon=(()=>{async function create(params){return await stripe.coupons.create(params)}async function retrieve(couponId){return await stripe.coupons.retrieve(couponId)}async function update(couponId,params){return await stripe.coupons.update(couponId,params)}async function deleteCoupon(couponId){return await stripe.coupons.del(couponId)}async function list(params={}){return await stripe.coupons.list(params)}async function createPromotionCode(params){return await stripe.promotionCodes.create(params)}async function retrievePromotionCode(code){try{const promotionCodes=await stripe.promotionCodes.list({code,active:!0});if(promotionCodes.data.length>0)return promotionCodes.data[0]??null;return null}catch{return null}}return{create,retrieve,update,delete:deleteCoupon,list,createPromotionCode,retrievePromotionCode}})();
1
+ import{stripe}from"../drivers/stripe";export const manageProduct=(()=>{async function create(params){return await stripe.products.create(params)}async function retrieve(productId){return await stripe.products.retrieve(productId)}async function update(productId,params){return await stripe.products.update(productId,params)}async function list(params={}){return await stripe.products.list({active:true,...params})}async function archive(productId){return await stripe.products.update(productId,{active:false})}async function createWithPrice(productParams,priceParams){const product=await stripe.products.create(productParams);const price=await stripe.prices.create({...priceParams,product:product.id});return{product,price}}async function search(query,params={query:""}){return await stripe.products.search({...params,query})}return{create,retrieve,update,list,archive,createWithPrice,search}})();export const managePriceExtended=(()=>{async function create(params){return await stripe.prices.create(params)}async function retrieve(priceId){return await stripe.prices.retrieve(priceId)}async function update(priceId,params){return await stripe.prices.update(priceId,params)}async function list(params={}){return await stripe.prices.list({active:true,...params})}async function listByProduct(productId,params={}){return await stripe.prices.list({product:productId,active:true,...params})}async function search(query,params={query:""}){return await stripe.prices.search({...params,query})}async function archive(priceId){return await stripe.prices.update(priceId,{active:false})}return{create,retrieve,update,list,listByProduct,search,archive}})();export const manageCoupon=(()=>{async function create(params){return await stripe.coupons.create(params)}async function retrieve(couponId){return await stripe.coupons.retrieve(couponId)}async function update(couponId,params){return await stripe.coupons.update(couponId,params)}async function deleteCoupon(couponId){return await stripe.coupons.del(couponId)}async function list(params={}){return await stripe.coupons.list(params)}async function createPromotionCode(params){return await stripe.promotionCodes.create(params)}async function retrievePromotionCode(code){try{const promotionCodes=await stripe.promotionCodes.list({code,active:true});if(promotionCodes.data.length>0){return promotionCodes.data[0]??null}return null}catch{return null}}return{create,retrieve,update,delete:deleteCoupon,list,createPromotionCode,retrievePromotionCode}})();
@@ -1 +1 @@
1
- import{saas}from"@stacksjs/config";import{err,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{stripe}from"@stacksjs/payments";import{findManagedPortalConfiguration,portalConfigurationMatches,portalConfigurationParams}from"./portal";async function findProductByName(name){for await(const product of stripe.products.list({active:!0,limit:100}))if(product.name===name)return product;return}async function findPriceByLookupKey(lookupKey){return(await stripe.prices.list({lookup_keys:[lookupKey],active:!0,limit:1})).data[0]}function priceMatches(price,params){return price.unit_amount===params.unit_amount&&price.currency===params.currency&&price.product===params.product&&(price.recurring?.interval??void 0)===params.recurring?.interval}export async function createStripeProduct(options={}){const dryRun=options.dryRun??!1,actions=[],plans=saas.plans??[],productIds=new Map;try{if(!plans.length&&!saas.coupons?.length&&!saas.portal)return ok({dryRun,actions});for(const plan of plans){const existingProduct=await findProductByName(plan.productName);let productId=existingProduct?.id;if(existingProduct)actions.push({kind:"product",verb:"reuse",target:plan.productName,detail:existingProduct.id});else{actions.push({kind:"product",verb:"create",target:plan.productName});if(!dryRun)productId=(await stripe.products.create({name:plan.productName,description:plan.description,metadata:plan.metadata})).id}if(productId)productIds.set(plan.productName,productId);for(const pricing of plan.pricing){if(!productId){actions.push({kind:"price",verb:"create",target:pricing.key});continue}const priceParams={unit_amount:pricing.price,currency:pricing.currency,product:productId,lookup_key:pricing.key};if(pricing.interval)priceParams.recurring={interval:pricing.interval};const existingPrice=await findPriceByLookupKey(pricing.key);if(existingPrice&&priceMatches(existingPrice,priceParams)){actions.push({kind:"price",verb:"reuse",target:pricing.key,detail:existingPrice.id});continue}if(existingPrice){actions.push({kind:"price",verb:"replace",target:pricing.key,detail:`${existingPrice.id} -> new price (${pricing.price} ${pricing.currency})`});priceParams.transfer_lookup_key=!0}else actions.push({kind:"price",verb:"create",target:pricing.key});if(!dryRun)await stripe.prices.create(priceParams)}}for(const coupon of saas.coupons??[])await reconcileCoupon(coupon,productIds,dryRun,actions);if(saas.portal)await reconcilePortal(dryRun,actions);return ok({dryRun,actions})}catch(error){const e=error instanceof Error?error:Error(String(error));log.error(e);return err(e)}}async function findCoupon(id){try{const coupon=await stripe.coupons.retrieve(id);return coupon.deleted?void 0:coupon}catch(error){if(error.statusCode===404||error.code==="resource_missing")return;throw error}}function promotionCouponId(promotion){const coupon=promotion.promotion?.coupon;return typeof coupon==="string"?coupon:coupon?.id}function couponMatches(live,want){return(live.percent_off??void 0)===want.percentOff&&(live.amount_off??void 0)===want.amountOff&&live.duration===want.duration&&(live.duration_in_months??void 0)===(want.duration==="repeating"?want.durationInMonths:void 0)}async function reconcileCoupon(coupon,productIds,dryRun,actions){const id=coupon.id??coupon.code;if(!id){actions.push({kind:"coupon",verb:"conflict",target:"(unnamed)",detail:"a coupon needs an id or a code"});return}const live=await findCoupon(id);if(live&&!couponMatches(live,coupon)){actions.push({kind:"coupon",verb:"conflict",target:id,detail:"exists with a different discount; coupons cannot change, so give this one a new id"});return}if(live)actions.push({kind:"coupon",verb:"reuse",target:id});else{const products=(coupon.appliesTo??[]).map((name)=>productIds.get(name)),unresolved=(coupon.appliesTo??[]).filter((_name,index)=>!products[index]);if(unresolved.length&&!dryRun){actions.push({kind:"coupon",verb:"conflict",target:id,detail:`appliesTo names no plan: ${unresolved.join(", ")}`});return}actions.push({kind:"coupon",verb:"create",target:id});if(!dryRun)await stripe.coupons.create({id,...coupon.name?{name:coupon.name}:{},...coupon.percentOff!==void 0?{percent_off:coupon.percentOff}:{},...coupon.amountOff!==void 0?{amount_off:coupon.amountOff,currency:coupon.currency??"usd"}:{},duration:coupon.duration,...coupon.duration==="repeating"&&coupon.durationInMonths?{duration_in_months:coupon.durationInMonths}:{},...coupon.maxRedemptions?{max_redemptions:coupon.maxRedemptions}:{},...products.length?{applies_to:{products}}:{}})}for(const code of coupon.codes??(coupon.code?[coupon.code]:[])){const existing=(await stripe.promotionCodes.list({code,active:!0,limit:1})).data[0];if(existing&&promotionCouponId(existing)===id){actions.push({kind:"promotion-code",verb:"reuse",target:code,detail:existing.id});continue}if(existing){actions.push({kind:"promotion-code",verb:"conflict",target:code,detail:`already belongs to coupon ${promotionCouponId(existing)}`});continue}actions.push({kind:"promotion-code",verb:"create",target:code,detail:`for ${id}`});if(!dryRun)await stripe.promotionCodes.create({promotion:{type:"coupon",coupon:id},code})}}async function reconcilePortal(dryRun,actions){const params=portalConfigurationParams(saas.portal),live=await findManagedPortalConfiguration(void 0,stripe);if(live&&portalConfigurationMatches(live,params)){actions.push({kind:"portal",verb:"reuse",target:"customer portal",detail:live.id});return}if(live){actions.push({kind:"portal",verb:"update",target:"customer portal",detail:live.id});if(!dryRun)await stripe.billingPortal.configurations.update(live.id,params);return}actions.push({kind:"portal",verb:"create",target:"customer portal"});if(!dryRun)await stripe.billingPortal.configurations.create(params)}export function formatSetupReport(report){if(!report.actions.length)return["No plans, coupons or portal are declared in config/saas.ts, so there is nothing to provision."];const verbs={reuse:"already exists",replace:"moves lookup key to a new price",update:"updates",conflict:"CONFLICT, left alone",create:"creates"};return report.actions.map((action)=>{const verb=verbs[action.verb];return` ${action.kind} "${action.target}" ${verb}${action.detail?` (${action.detail})`:""}`})}
1
+ import{saas}from"@stacksjs/config";import{err,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{stripe}from"@stacksjs/payments";import{findManagedPortalConfiguration,portalConfigurationMatches,portalConfigurationParams}from"./portal";async function findProductByName(name){for await(const product of stripe.products.list({active:true,limit:100})){if(product.name===name)return product}return}async function findPriceByLookupKey(lookupKey){const prices=await stripe.prices.list({lookup_keys:[lookupKey],active:true,limit:1});return prices.data[0]}function priceMatches(price,params){return price.unit_amount===params.unit_amount&&price.currency===params.currency&&price.product===params.product&&(price.recurring?.interval??undefined)===params.recurring?.interval}export async function createStripeProduct(options={}){const dryRun=options.dryRun??false;const actions=[];const plans=saas.plans??[];const productIds=new Map;try{if(!plans.length&&!saas.coupons?.length&&!saas.portal)return ok({dryRun,actions});for(const plan of plans){const existingProduct=await findProductByName(plan.productName);let productId=existingProduct?.id;if(existingProduct){actions.push({kind:"product",verb:"reuse",target:plan.productName,detail:existingProduct.id})}else{actions.push({kind:"product",verb:"create",target:plan.productName});if(!dryRun){const product=await stripe.products.create({name:plan.productName,description:plan.description,metadata:plan.metadata});productId=product.id}}if(productId)productIds.set(plan.productName,productId);for(const pricing of plan.pricing){if(!productId){actions.push({kind:"price",verb:"create",target:pricing.key});continue}const priceParams={unit_amount:pricing.price,currency:pricing.currency,product:productId,lookup_key:pricing.key};if(pricing.interval)priceParams.recurring={interval:pricing.interval};const existingPrice=await findPriceByLookupKey(pricing.key);if(existingPrice&&priceMatches(existingPrice,priceParams)){actions.push({kind:"price",verb:"reuse",target:pricing.key,detail:existingPrice.id});continue}if(existingPrice){actions.push({kind:"price",verb:"replace",target:pricing.key,detail:`${existingPrice.id} -> new price (${pricing.price} ${pricing.currency})`});priceParams.transfer_lookup_key=true}else{actions.push({kind:"price",verb:"create",target:pricing.key})}if(!dryRun)await stripe.prices.create(priceParams)}}for(const coupon of saas.coupons??[])await reconcileCoupon(coupon,productIds,dryRun,actions);if(saas.portal)await reconcilePortal(dryRun,actions);return ok({dryRun,actions})}catch(error){const e=error instanceof Error?error:new Error(String(error));log.error(e);return err(e)}}async function findCoupon(id){try{const coupon=await stripe.coupons.retrieve(id);return coupon.deleted?undefined:coupon}catch(error){if(error.statusCode===404||error.code==="resource_missing")return;throw error}}function promotionCouponId(promotion){const coupon=promotion.promotion?.coupon;return typeof coupon==="string"?coupon:coupon?.id}function couponMatches(live,want){return(live.percent_off??undefined)===want.percentOff&&(live.amount_off??undefined)===want.amountOff&&live.duration===want.duration&&(live.duration_in_months??undefined)===(want.duration==="repeating"?want.durationInMonths:undefined)}async function reconcileCoupon(coupon,productIds,dryRun,actions){const id=coupon.id??coupon.code;if(!id){actions.push({kind:"coupon",verb:"conflict",target:"(unnamed)",detail:"a coupon needs an id or a code"});return}const live=await findCoupon(id);if(live&&!couponMatches(live,coupon)){actions.push({kind:"coupon",verb:"conflict",target:id,detail:"exists with a different discount; coupons cannot change, so give this one a new id"});return}if(live){actions.push({kind:"coupon",verb:"reuse",target:id})}else{const products=(coupon.appliesTo??[]).map((name)=>productIds.get(name));const unresolved=(coupon.appliesTo??[]).filter((_name,index)=>!products[index]);if(unresolved.length&&!dryRun){actions.push({kind:"coupon",verb:"conflict",target:id,detail:`appliesTo names no plan: ${unresolved.join(", ")}`});return}actions.push({kind:"coupon",verb:"create",target:id});if(!dryRun){await stripe.coupons.create({id,...coupon.name?{name:coupon.name}:{},...coupon.percentOff!==undefined?{percent_off:coupon.percentOff}:{},...coupon.amountOff!==undefined?{amount_off:coupon.amountOff,currency:coupon.currency??"usd"}:{},duration:coupon.duration,...coupon.duration==="repeating"&&coupon.durationInMonths?{duration_in_months:coupon.durationInMonths}:{},...coupon.maxRedemptions?{max_redemptions:coupon.maxRedemptions}:{},...products.length?{applies_to:{products}}:{}})}}for(const code of coupon.codes??(coupon.code?[coupon.code]:[])){const existing=(await stripe.promotionCodes.list({code,active:true,limit:1})).data[0];if(existing&&promotionCouponId(existing)===id){actions.push({kind:"promotion-code",verb:"reuse",target:code,detail:existing.id});continue}if(existing){actions.push({kind:"promotion-code",verb:"conflict",target:code,detail:`already belongs to coupon ${promotionCouponId(existing)}`});continue}actions.push({kind:"promotion-code",verb:"create",target:code,detail:`for ${id}`});if(!dryRun)await stripe.promotionCodes.create({promotion:{type:"coupon",coupon:id},code})}}async function reconcilePortal(dryRun,actions){const params=portalConfigurationParams(saas.portal);const live=await findManagedPortalConfiguration(undefined,stripe);if(live&&portalConfigurationMatches(live,params)){actions.push({kind:"portal",verb:"reuse",target:"customer portal",detail:live.id});return}if(live){actions.push({kind:"portal",verb:"update",target:"customer portal",detail:live.id});if(!dryRun)await stripe.billingPortal.configurations.update(live.id,params);return}actions.push({kind:"portal",verb:"create",target:"customer portal"});if(!dryRun)await stripe.billingPortal.configurations.create(params)}export function formatSetupReport(report){if(!report.actions.length)return["No plans, coupons or portal are declared in config/saas.ts, so there is nothing to provision."];const verbs={reuse:"already exists",replace:"moves lookup key to a new price",update:"updates",conflict:"CONFLICT, left alone",create:"creates"};return report.actions.map((action)=>{const verb=verbs[action.verb];return` ${action.kind} "${action.target}" ${verb}${action.detail?` (${action.detail})`:""}`})}
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";import{HttpError}from"@stacksjs/error-handling";import{formatDate,isUniqueViolation}from"@stacksjs/orm";import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";import{managePrice}from"./price";import{subscriptionPeriodEnd}from"../driver/stripe";import{freshIdempotencyKey,stacksIdempotencyKey}from"../idempotency";export const ENTITLING_STATUSES=["active","trialing"],INCOMPLETE_STATUSES=["incomplete"],SUBSCRIPTION_CREATE_EXPAND=["latest_invoice.confirmation_secret"];export function stripeTimestamp(seconds){return typeof seconds==="number"?formatDate(new Date(seconds*1000)):void 0}export const manageSubscription=(()=>{async function create(user,type,lookupKey,params){const price=await managePrice.retrieveByLookupKey(lookupKey);if(!price)throw Error("Price does not exist in Stripe");const subscriptionItems=[{price:price.id,quantity:1}],mergedParams={...{customer:await manageCustomer.createOrGetStripeUser(user,{}).then((customer)=>{if(!customer||!customer.id)throw Error("Customer does not exist in Stripe");return customer.id}),payment_behavior:"allow_incomplete",expand:[...SUBSCRIPTION_CREATE_EXPAND],items:subscriptionItems},...params},subscription=await stripe.subscriptions.create(mergedParams,{idempotencyKey:stacksIdempotencyKey("subscription.create",user.id,type,lookupKey)});await storeSubscription(user,type,lookupKey,subscription);return subscription}async function update(user,type,lookupKey,_params={}){const newPrice=await managePrice.retrieveByLookupKey(lookupKey),activeSubscription=await user?.activeSubscription();if(!newPrice)throw Error("New price does not exist in Stripe");if(!activeSubscription)throw Error("No active subscription for user!");const subscriptionId=activeSubscription.subscription?.provider_id;if(!subscriptionId)throw Error("Active subscription has no provider ID");const subscription=await stripe.subscriptions.retrieve(subscriptionId);if(!subscription)throw Error("Subscription does not exist in Stripe");const subscriptionItemId=subscription.items.data[0]?.id;if(!subscriptionItemId)throw Error("No subscription items found in the subscription");await stripe.subscriptions.update(subscriptionId,{items:[{id:subscriptionItemId,price:newPrice.id,quantity:1}],proration_behavior:"create_prorations"},{idempotencyKey:stacksIdempotencyKey("subscription.update",subscriptionId,newPrice.id)});const updatedSubscription=await stripe.subscriptions.retrieve(subscriptionId);if(!activeSubscription.subscription?.id)throw Error("Active subscription has no database ID");await updateSubscription(activeSubscription.subscription.id,type,updatedSubscription);return updatedSubscription}async function cancel(subscriptionId,params){if(!await stripe.subscriptions.retrieve(subscriptionId))throw Error("Subscription does not exist or does not belong to the user");const updatedSubscription=await stripe.subscriptions.cancel(subscriptionId,params,{idempotencyKey:stacksIdempotencyKey("subscription.cancel",subscriptionId)});await updateStoredSubscription(subscriptionId);return updatedSubscription}async function cancelAtPeriodEnd(subscriptionId){const subscription=await stripe.subscriptions.update(subscriptionId,{cancel_at_period_end:!0},{idempotencyKey:freshIdempotencyKey("subscription.cancel_at_period_end",subscriptionId)}),endsAt=stripeTimestamp(subscriptionPeriodEnd(subscription));if(endsAt)await db.updateTable("subscriptions").set({ends_at:endsAt}).where("provider_id","=",subscriptionId).executeTakeFirst();return subscription}async function resume(subscriptionId){const subscription=await stripe.subscriptions.update(subscriptionId,{cancel_at_period_end:!1},{idempotencyKey:freshIdempotencyKey("subscription.resume",subscriptionId)});await db.updateTable("subscriptions").set({ends_at:null}).where("provider_id","=",subscriptionId).executeTakeFirst();return subscription}async function retrieve(user,subscriptionId){if(!manageCustomer.hasStripeId(user))throw Error("Customer does not exist in Stripe");return await stripe.subscriptions.retrieve(subscriptionId)}async function updateStoredSubscription(subscriptionId){await db.updateTable("subscriptions").set({provider_status:"canceled"}).where("provider_id","=",subscriptionId).executeTakeFirst()}function isActive(subscription){return subscription.provider_status==="active"}function isTrial(subscription){return subscription.provider_status==="trialing"}async function hasSubscriptionInStatus(user,type,statuses){const match=await db.selectFrom("subscriptions").where("user_id","=",user.id).where("type","=",type).whereIn("provider_status",[...statuses]).select(["id"]).limit(1).executeTakeFirst();return Boolean(match)}async function isIncomplete(user,type){return await hasSubscriptionInStatus(user,type,INCOMPLETE_STATUSES)}async function isValid(user,type){return await hasSubscriptionInStatus(user,type,ENTITLING_STATUSES)}async function storeSubscription(user,type,_lookupKey,options){const firstItem=options.items.data[0];if(!firstItem)throw Error("Stripe subscription contains no line items - cannot store subscription");const data=removeNullValues({user_id:user.id,type,unit_price:Number(firstItem.price.unit_amount),provider_id:options.id,provider_status:options.status,provider_price_id:firstItem.price.id,quantity:firstItem.quantity,trial_ends_at:stripeTimestamp(options.trial_end),ends_at:stripeTimestamp(subscriptionPeriodEnd(options)),provider_type:"stripe",last_used_at:stripeTimestamp(subscriptionPeriodEnd(options))});let subscriptionModelCreated;try{subscriptionModelCreated=await db.insertInto("subscriptions").values(data).executeTakeFirst()}catch(error){if(isUniqueViolation(error))throw new HttpError(409,"A subscription with this provider ID already exists");throw error}if(!subscriptionModelCreated)throw Error("Failed to insert subscription record");return await db.selectFrom("subscriptions").where("id","=",Number(subscriptionModelCreated.insertId)).selectAll().executeTakeFirst()}async function updateSubscription(activeSubId,type,options){const subscription=await db.selectFrom("subscriptions").where("id","=",activeSubId).selectAll().executeTakeFirst(),firstItem=options.items.data[0];if(!firstItem)throw Error("Stripe subscription contains no line items - cannot update subscription");await db?.updateTable("subscriptions").set({type,provider_price_id:firstItem.price.id,unit_price:Number(firstItem.price.unit_amount)}).where("id","=",activeSubId).executeTakeFirst();return subscription}function removeNullValues(obj){return Object.fromEntries(Object.entries(obj).filter(([_,value])=>value!=null))}return{create,update,isValid,isIncomplete,cancel,cancelAtPeriodEnd,resume,retrieve}})();
1
+ import{db}from"@stacksjs/database/runtime";import{HttpError}from"@stacksjs/error-handling";import{formatDate,isUniqueViolation}from"@stacksjs/orm";import{stripe}from"../drivers/stripe";import{manageCustomer}from"./customer";import{managePrice}from"./price";import{subscriptionPeriodEnd}from"../driver/stripe";import{freshIdempotencyKey,stacksIdempotencyKey}from"../idempotency";export const ENTITLING_STATUSES=["active","trialing"];export const INCOMPLETE_STATUSES=["incomplete"];export const SUBSCRIPTION_CREATE_EXPAND=["latest_invoice.confirmation_secret"];export function stripeTimestamp(seconds){return typeof seconds==="number"?formatDate(new Date(seconds*1000)):undefined}export const manageSubscription=(()=>{async function create(user,type,lookupKey,params){const price=await managePrice.retrieveByLookupKey(lookupKey);if(!price){throw new Error("Price does not exist in Stripe")}const subscriptionItems=[{price:price.id,quantity:1}];const customerId=await manageCustomer.createOrGetStripeUser(user,{}).then((customer)=>{if(!customer||!customer.id){throw new Error("Customer does not exist in Stripe")}return customer.id});const defaultParams={customer:customerId,payment_behavior:"allow_incomplete",expand:[...SUBSCRIPTION_CREATE_EXPAND],items:subscriptionItems};const mergedParams={...defaultParams,...params};const subscription=await stripe.subscriptions.create(mergedParams,{idempotencyKey:stacksIdempotencyKey("subscription.create",user.id,type,lookupKey)});await storeSubscription(user,type,lookupKey,subscription);return subscription}async function update(user,type,lookupKey,_params={}){const newPrice=await managePrice.retrieveByLookupKey(lookupKey);const activeSubscription=await user?.activeSubscription();if(!newPrice)throw new Error("New price does not exist in Stripe");if(!activeSubscription)throw new Error("No active subscription for user!");const subscriptionId=activeSubscription.subscription?.provider_id;if(!subscriptionId){throw new Error("Active subscription has no provider ID")}const subscription=await stripe.subscriptions.retrieve(subscriptionId);if(!subscription){throw new Error("Subscription does not exist in Stripe")}const subscriptionItemId=subscription.items.data[0]?.id;if(!subscriptionItemId){throw new Error("No subscription items found in the subscription")}await stripe.subscriptions.update(subscriptionId,{items:[{id:subscriptionItemId,price:newPrice.id,quantity:1}],proration_behavior:"create_prorations"},{idempotencyKey:stacksIdempotencyKey("subscription.update",subscriptionId,newPrice.id)});const updatedSubscription=await stripe.subscriptions.retrieve(subscriptionId);if(!activeSubscription.subscription?.id){throw new Error("Active subscription has no database ID")}await updateSubscription(activeSubscription.subscription.id,type,updatedSubscription);return updatedSubscription}async function cancel(subscriptionId,params){const subscription=await stripe.subscriptions.retrieve(subscriptionId);if(!subscription){throw new Error("Subscription does not exist or does not belong to the user")}const updatedSubscription=await stripe.subscriptions.cancel(subscriptionId,params,{idempotencyKey:stacksIdempotencyKey("subscription.cancel",subscriptionId)});await updateStoredSubscription(subscriptionId);return updatedSubscription}async function cancelAtPeriodEnd(subscriptionId){const subscription=await stripe.subscriptions.update(subscriptionId,{cancel_at_period_end:true},{idempotencyKey:freshIdempotencyKey("subscription.cancel_at_period_end",subscriptionId)});const endsAt=stripeTimestamp(subscriptionPeriodEnd(subscription));if(endsAt)await db.updateTable("subscriptions").set({ends_at:endsAt}).where("provider_id","=",subscriptionId).executeTakeFirst();return subscription}async function resume(subscriptionId){const subscription=await stripe.subscriptions.update(subscriptionId,{cancel_at_period_end:false},{idempotencyKey:freshIdempotencyKey("subscription.resume",subscriptionId)});await db.updateTable("subscriptions").set({ends_at:null}).where("provider_id","=",subscriptionId).executeTakeFirst();return subscription}async function retrieve(user,subscriptionId){if(!manageCustomer.hasStripeId(user)){throw new Error("Customer does not exist in Stripe")}const subscription=await stripe.subscriptions.retrieve(subscriptionId);return subscription}async function updateStoredSubscription(subscriptionId){await db.updateTable("subscriptions").set({provider_status:"canceled"}).where("provider_id","=",subscriptionId).executeTakeFirst()}function isActive(subscription){return subscription.provider_status==="active"}function isTrial(subscription){return subscription.provider_status==="trialing"}async function hasSubscriptionInStatus(user,type,statuses){const match=await db.selectFrom("subscriptions").where("user_id","=",user.id).where("type","=",type).whereIn("provider_status",[...statuses]).select(["id"]).limit(1).executeTakeFirst();return Boolean(match)}async function isIncomplete(user,type){return await hasSubscriptionInStatus(user,type,INCOMPLETE_STATUSES)}async function isValid(user,type){return await hasSubscriptionInStatus(user,type,ENTITLING_STATUSES)}async function storeSubscription(user,type,_lookupKey,options){const firstItem=options.items.data[0];if(!firstItem)throw new Error("Stripe subscription contains no line items - cannot store subscription");const data=removeNullValues({user_id:user.id,type,unit_price:Number(firstItem.price.unit_amount),provider_id:options.id,provider_status:options.status,provider_price_id:firstItem.price.id,quantity:firstItem.quantity,trial_ends_at:stripeTimestamp(options.trial_end),ends_at:stripeTimestamp(subscriptionPeriodEnd(options)),provider_type:"stripe",last_used_at:stripeTimestamp(subscriptionPeriodEnd(options))});let subscriptionModelCreated;try{subscriptionModelCreated=await db.insertInto("subscriptions").values(data).executeTakeFirst()}catch(error){if(isUniqueViolation(error))throw new HttpError(409,"A subscription with this provider ID already exists");throw error}if(!subscriptionModelCreated)throw new Error("Failed to insert subscription record");const subscriptionModel=await db.selectFrom("subscriptions").where("id","=",Number(subscriptionModelCreated.insertId)).selectAll().executeTakeFirst();return subscriptionModel}async function updateSubscription(activeSubId,type,options){const subscription=await db.selectFrom("subscriptions").where("id","=",activeSubId).selectAll().executeTakeFirst();const firstItem=options.items.data[0];if(!firstItem)throw new Error("Stripe subscription contains no line items - cannot update subscription");await db?.updateTable("subscriptions").set({type,provider_price_id:firstItem.price.id,unit_price:Number(firstItem.price.unit_amount)}).where("id","=",activeSubId).executeTakeFirst();return subscription}function removeNullValues(obj){return Object.fromEntries(Object.entries(obj).filter(([_,value])=>value!=null))}return{create,update,isValid,isIncomplete,cancel,cancelAtPeriodEnd,resume,retrieve}})();
@@ -1 +1 @@
1
- import{db}from"@stacksjs/database/runtime";import{PaymentTransaction}from"@stacksjs/orm";export const manageTransaction=(()=>{async function store(user,productId,options){const product=await db.selectFrom("payment_products").where("id","=",productId).selectAll().executeTakeFirst();if(!product)throw Error(`Payment product with id ${productId} not found.`);const data={name:product.name,description:options.description??"",amount:product.unit_price,brand:options.brand,type:options.type??"one-time",provider_id:options.provider_id,user_id:user.id},createdTransaction=await db.insertInto("payment_transactions").values(data).executeTakeFirst();if(!createdTransaction)throw Error("Failed to insert payment transaction");return await db.selectFrom("payment_transactions").where("id","=",Number(createdTransaction.insertId)).selectAll().executeTakeFirst()}async function list(user){return await db.selectFrom("payment_transactions").where("user_id","=",user.id).selectAll().execute()}return{store,list}})();
1
+ import{db}from"@stacksjs/database/runtime";import{PaymentTransaction}from"@stacksjs/orm";export const manageTransaction=(()=>{async function store(user,productId,options){const product=await db.selectFrom("payment_products").where("id","=",productId).selectAll().executeTakeFirst();if(!product){throw new Error(`Payment product with id ${productId} not found.`)}const data={name:product.name,description:options.description??"",amount:product.unit_price,brand:options.brand,type:options.type??"one-time",provider_id:options.provider_id,user_id:user.id};const createdTransaction=await db.insertInto("payment_transactions").values(data).executeTakeFirst();if(!createdTransaction)throw new Error("Failed to insert payment transaction");const transaction=await db.selectFrom("payment_transactions").where("id","=",Number(createdTransaction.insertId)).selectAll().executeTakeFirst();return transaction}async function list(user){const transaction=await db.selectFrom("payment_transactions").where("user_id","=",user.id).selectAll().execute();return transaction}return{store,list}})();
@@ -1 +1 @@
1
- import{log}from"@stacksjs/logging";import{db,sqlDateTime}from"@stacksjs/database/runtime";export const WEBHOOK_HANDLERS_PROVIDER="stripe:handlers";const DEFAULT_TTL_SECONDS=345600;export function memoryWebhookEventStore(options={}){const ttl=(options.ttlSeconds??DEFAULT_TTL_SECONDS)*1000,maxEntries=options.maxEntries??1e4,now=options.now??Date.now,seen=new Map;return{async has(eventId){const expires=seen.get(eventId);if(expires===void 0)return!1;if(expires>now())return!0;seen.delete(eventId);return!1},async add(eventId){seen.delete(eventId);seen.set(eventId,now()+ttl);while(seen.size>maxEntries){const oldest=seen.keys().next().value;if(oldest===void 0)break;seen.delete(oldest)}}}}let warnedAboutMissingTable=!1;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=!0;log.warn("[payments/webhook] payment_webhook_events table missing - replayed webhook events are only deduplicated in this process. Run `buddy migrate` to remember them across restarts.")}function isMissingTableError(error){const e=error,message=e?.message??"";return e?.code==="42P01"||message.includes("no such table")||message.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(message)}export function databaseWebhookEventStore(provider=WEBHOOK_HANDLERS_PROVIDER){const fallback=memoryWebhookEventStore();return{async has(eventId){try{return!!await db.selectFrom("payment_webhook_events").where("provider","=",provider).where("event_id","=",eventId).select(["id"]).executeTakeFirst()||await fallback.has(eventId)}catch(error){if(!isMissingTableError(error))throw error;warnOnceAboutMissingTable();return await fallback.has(eventId)}},async add(eventId){await fallback.add(eventId);const now=sqlDateTime(new Date);try{await db.insertOrIgnore("payment_webhook_events",{provider,event_id:eventId,processed_at:now,created_at:now,updated_at:now})}catch(error){if(!isMissingTableError(error))throw error;warnOnceAboutMissingTable()}}}}let defaultStore=null;export function webhookEventStore(){defaultStore??=databaseWebhookEventStore();return defaultStore}export function setWebhookEventStore(store){defaultStore=store}
1
+ import{log}from"@stacksjs/logging";import{db,sqlDateTime}from"@stacksjs/database/runtime";export const WEBHOOK_HANDLERS_PROVIDER="stripe:handlers";const DEFAULT_TTL_SECONDS=4*24*60*60;export function memoryWebhookEventStore(options={}){const ttl=(options.ttlSeconds??DEFAULT_TTL_SECONDS)*1000;const maxEntries=options.maxEntries??1e4;const now=options.now??Date.now;const seen=new Map;return{async has(eventId){const expires=seen.get(eventId);if(expires===undefined)return false;if(expires>now())return true;seen.delete(eventId);return false},async add(eventId){seen.delete(eventId);seen.set(eventId,now()+ttl);while(seen.size>maxEntries){const oldest=seen.keys().next().value;if(oldest===undefined)break;seen.delete(oldest)}}}}let warnedAboutMissingTable=false;function warnOnceAboutMissingTable(){if(warnedAboutMissingTable)return;warnedAboutMissingTable=true;log.warn("[payments/webhook] payment_webhook_events table missing - replayed webhook events are only deduplicated in this process. Run `buddy migrate` to remember them across restarts.")}function isMissingTableError(error){const e=error;const message=e?.message??"";return e?.code==="42P01"||message.includes("no such table")||message.includes("doesn't exist")||/relation "[^"]*" does not exist/i.test(message)}export function databaseWebhookEventStore(provider=WEBHOOK_HANDLERS_PROVIDER){const fallback=memoryWebhookEventStore();return{async has(eventId){try{const row=await db.selectFrom("payment_webhook_events").where("provider","=",provider).where("event_id","=",eventId).select(["id"]).executeTakeFirst();return!!row||await fallback.has(eventId)}catch(error){if(!isMissingTableError(error))throw error;warnOnceAboutMissingTable();return await fallback.has(eventId)}},async add(eventId){await fallback.add(eventId);const now=sqlDateTime(new Date);try{await db.insertOrIgnore("payment_webhook_events",{provider,event_id:eventId,processed_at:now,created_at:now,updated_at:now})}catch(error){if(!isMissingTableError(error))throw error;warnOnceAboutMissingTable()}}}}let defaultStore=null;export function webhookEventStore(){defaultStore??=databaseWebhookEventStore();return defaultStore}export function setWebhookEventStore(store){defaultStore=store}
@@ -1 +1 @@
1
- import{log}from"@stacksjs/logging";import{stripe}from"../drivers/stripe";import{webhookEventStore}from"./webhook-events";const handlers=new Map;export function onWebhookEvent(eventType,handler){const existing=handlers.get(eventType)||[];existing.push(handler);handlers.set(eventType,existing)}export function registerWebhookHandlers(handlerMap){for(const[eventType,handler]of Object.entries(handlerMap))onWebhookEvent(eventType,handler)}export async function constructEvent(payload,signature,secret,tolerance){if(tolerance!=null&&Number.isFinite(tolerance)&&tolerance>0)return await stripe.webhooks.constructEventAsync(payload,signature,secret,tolerance);return await stripe.webhooks.constructEventAsync(payload,signature,secret)}export async function constructEventAsync(payload,signature,secret,tolerance){return await constructEvent(payload,signature,secret,tolerance)}const inFlight=new Map;export async function handleWebhookEvent(event,options={}){const eventHandlers=handlers.get(event.type)||[];if(eventHandlers.length===0)return{handled:!1,eventType:event.type};const eventId=typeof event.id==="string"?event.id:"";if(options.dedupe===!1||!eventId)return await runHandlers(event,eventHandlers);const running=inFlight.get(eventId);if(running)return await running;const store=options.store??webhookEventStore(),attempt=(async()=>{if(await store.has(eventId))return{handled:!0,eventType:event.type,duplicate:!0};const result=await runHandlers(event,eventHandlers);if(!result.errors)try{await store.add(eventId)}catch(error){log.warn(`[payments/webhook] ${event.type} ${eventId} was handled but could not be recorded, so a retry may run it again: ${error instanceof Error?error.message:String(error)}`)}return result})();inFlight.set(eventId,attempt);try{return await attempt}finally{inFlight.delete(eventId)}}async function runHandlers(event,eventHandlers){const errors=[];for(const handler of eventHandlers)try{await handler(event)}catch(error){errors.push(error instanceof Error?error.message:String(error))}return{handled:!0,eventType:event.type,...errors.length>0?{errors}:{}}}export async function processWebhook(payload,signature,config){try{const event=await constructEvent(payload,signature,config.secret,config.tolerance),result=await handleWebhookEvent(event,{dedupe:config.dedupe,store:config.store});if(result.errors&&result.errors.length>0)return{success:!1,eventType:result.eventType,error:result.errors.join("; ")};return{success:!0,eventType:result.eventType,...result.duplicate?{duplicate:!0}:{}}}catch(error){return{success:!1,error:error instanceof Error?error.message:"Unknown error"}}}export function onPaymentIntent(handlers){if(handlers.succeeded)onWebhookEvent("payment_intent.succeeded",handlers.succeeded);if(handlers.failed)onWebhookEvent("payment_intent.payment_failed",handlers.failed);if(handlers.created)onWebhookEvent("payment_intent.created",handlers.created);if(handlers.canceled)onWebhookEvent("payment_intent.canceled",handlers.canceled)}export function onSubscription(handlers){if(handlers.created)onWebhookEvent("customer.subscription.created",handlers.created);if(handlers.updated)onWebhookEvent("customer.subscription.updated",handlers.updated);if(handlers.deleted)onWebhookEvent("customer.subscription.deleted",handlers.deleted);if(handlers.trialWillEnd)onWebhookEvent("customer.subscription.trial_will_end",handlers.trialWillEnd)}export function onInvoice(handlers){if(handlers.paid)onWebhookEvent("invoice.paid",handlers.paid);if(handlers.paymentFailed)onWebhookEvent("invoice.payment_failed",handlers.paymentFailed);if(handlers.created)onWebhookEvent("invoice.created",handlers.created);if(handlers.finalized)onWebhookEvent("invoice.finalized",handlers.finalized)}export function onCheckout(handlers){if(handlers.completed)onWebhookEvent("checkout.session.completed",handlers.completed);if(handlers.expired)onWebhookEvent("checkout.session.expired",handlers.expired)}export function onCharge(handlers){if(handlers.succeeded)onWebhookEvent("charge.succeeded",handlers.succeeded);if(handlers.failed)onWebhookEvent("charge.failed",handlers.failed);if(handlers.refunded)onWebhookEvent("charge.refunded",handlers.refunded);if(handlers.disputed)onWebhookEvent("charge.dispute.created",handlers.disputed)}export function getPaymentIntent(event){if(event.type.startsWith("payment_intent."))return event.data.object;return null}export function getSubscription(event){if(event.type.startsWith("customer.subscription."))return event.data.object;return null}export function getInvoice(event){if(event.type.startsWith("invoice."))return event.data.object;return null}export function getCheckoutSession(event){if(event.type.startsWith("checkout.session."))return event.data.object;return null}export function getCharge(event){if(event.type.startsWith("charge."))return event.data.object;return null}export function getCustomer(event){if(event.type.startsWith("customer.")&&!event.type.includes("subscription"))return event.data.object;return null}export const manageWebhook={onWebhookEvent,registerWebhookHandlers,constructEvent,constructEventAsync,handleWebhookEvent,processWebhook,onPaymentIntent,onSubscription,onInvoice,onCheckout,onCharge,getPaymentIntent,getSubscription,getInvoice,getCheckoutSession,getCharge,getCustomer};
1
+ import{log}from"@stacksjs/logging";import{stripe}from"../drivers/stripe";import{webhookEventStore}from"./webhook-events";const handlers=new Map;export function onWebhookEvent(eventType,handler){const existing=handlers.get(eventType)||[];existing.push(handler);handlers.set(eventType,existing)}export function registerWebhookHandlers(handlerMap){for(const[eventType,handler]of Object.entries(handlerMap)){onWebhookEvent(eventType,handler)}}export async function constructEvent(payload,signature,secret,tolerance){if(tolerance!=null&&Number.isFinite(tolerance)&&tolerance>0){return await stripe.webhooks.constructEventAsync(payload,signature,secret,tolerance)}return await stripe.webhooks.constructEventAsync(payload,signature,secret)}export async function constructEventAsync(payload,signature,secret,tolerance){return await constructEvent(payload,signature,secret,tolerance)}const inFlight=new Map;export async function handleWebhookEvent(event,options={}){const eventHandlers=handlers.get(event.type)||[];if(eventHandlers.length===0){return{handled:false,eventType:event.type}}const eventId=typeof event.id==="string"?event.id:"";if(options.dedupe===false||!eventId)return await runHandlers(event,eventHandlers);const running=inFlight.get(eventId);if(running)return await running;const store=options.store??webhookEventStore();const attempt=(async()=>{if(await store.has(eventId))return{handled:true,eventType:event.type,duplicate:true};const result=await runHandlers(event,eventHandlers);if(!result.errors){try{await store.add(eventId)}catch(error){log.warn(`[payments/webhook] ${event.type} ${eventId} was handled but could not be recorded, so a retry may run it again: ${error instanceof Error?error.message:String(error)}`)}}return result})();inFlight.set(eventId,attempt);try{return await attempt}finally{inFlight.delete(eventId)}}async function runHandlers(event,eventHandlers){const errors=[];for(const handler of eventHandlers){try{await handler(event)}catch(error){errors.push(error instanceof Error?error.message:String(error))}}return{handled:true,eventType:event.type,...errors.length>0?{errors}:{}}}export async function processWebhook(payload,signature,config){try{const event=await constructEvent(payload,signature,config.secret,config.tolerance);const result=await handleWebhookEvent(event,{dedupe:config.dedupe,store:config.store});if(result.errors&&result.errors.length>0){return{success:false,eventType:result.eventType,error:result.errors.join("; ")}}return{success:true,eventType:result.eventType,...result.duplicate?{duplicate:true}:{}}}catch(error){return{success:false,error:error instanceof Error?error.message:"Unknown error"}}}export function onPaymentIntent(handlers){if(handlers.succeeded)onWebhookEvent("payment_intent.succeeded",handlers.succeeded);if(handlers.failed)onWebhookEvent("payment_intent.payment_failed",handlers.failed);if(handlers.created)onWebhookEvent("payment_intent.created",handlers.created);if(handlers.canceled)onWebhookEvent("payment_intent.canceled",handlers.canceled)}export function onSubscription(handlers){if(handlers.created)onWebhookEvent("customer.subscription.created",handlers.created);if(handlers.updated)onWebhookEvent("customer.subscription.updated",handlers.updated);if(handlers.deleted)onWebhookEvent("customer.subscription.deleted",handlers.deleted);if(handlers.trialWillEnd)onWebhookEvent("customer.subscription.trial_will_end",handlers.trialWillEnd)}export function onInvoice(handlers){if(handlers.paid)onWebhookEvent("invoice.paid",handlers.paid);if(handlers.paymentFailed)onWebhookEvent("invoice.payment_failed",handlers.paymentFailed);if(handlers.created)onWebhookEvent("invoice.created",handlers.created);if(handlers.finalized)onWebhookEvent("invoice.finalized",handlers.finalized)}export function onCheckout(handlers){if(handlers.completed)onWebhookEvent("checkout.session.completed",handlers.completed);if(handlers.expired)onWebhookEvent("checkout.session.expired",handlers.expired)}export function onCharge(handlers){if(handlers.succeeded)onWebhookEvent("charge.succeeded",handlers.succeeded);if(handlers.failed)onWebhookEvent("charge.failed",handlers.failed);if(handlers.refunded)onWebhookEvent("charge.refunded",handlers.refunded);if(handlers.disputed)onWebhookEvent("charge.dispute.created",handlers.disputed)}export function getPaymentIntent(event){if(event.type.startsWith("payment_intent.")){return event.data.object}return null}export function getSubscription(event){if(event.type.startsWith("customer.subscription.")){return event.data.object}return null}export function getInvoice(event){if(event.type.startsWith("invoice.")){return event.data.object}return null}export function getCheckoutSession(event){if(event.type.startsWith("checkout.session.")){return event.data.object}return null}export function getCharge(event){if(event.type.startsWith("charge.")){return event.data.object}return null}export function getCustomer(event){if(event.type.startsWith("customer.")&&!event.type.includes("subscription")){return event.data.object}return null}export const manageWebhook={onWebhookEvent,registerWebhookHandlers,constructEvent,constructEventAsync,handleWebhookEvent,processWebhook,onPaymentIntent,onSubscription,onInvoice,onCheckout,onCharge,getPaymentIntent,getSubscription,getInvoice,getCheckoutSession,getCharge,getCustomer};
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";export function connectedAccountIdempotencyKey(scope,userId,params,reference){return stacksIdempotencyKey(scope,userId,reference,idempotencyFingerprint(params))}export const MANAGED_RISK_CONTROLLER={stripe_dashboard:{type:"full"},fees:{payer:"account"},losses:{payments:"stripe"},requirement_collection:"stripe"};export function connectedAccountDefaults(params){return params.type||params.controller?{}:{controller:MANAGED_RISK_CONTROLLER}}export const manageConnectedAccount=(()=>{async function createConnectedAccount(user,params={},options={}){const merged={...{...connectedAccountDefaults(params),email:user.email??void 0,metadata:{stacks_user_id:String(user.id)}},...params};return await stripe.accounts.create(merged,{idempotencyKey:connectedAccountIdempotencyKey("connect.account.create",user.id,merged,options.reference)})}async function createTestConnectedAccount(user,params={},options={}){const merged={...{...connectedAccountDefaults(params),email:user.email??void 0,business_type:"individual",capabilities:{card_payments:{requested:!0},transfers:{requested:!0}},business_profile:{url:"https://example.com",mcc:"5812"},metadata:{stacks_user_id:String(user.id),stacks_test_account:"true"}},...params};return await stripe.accounts.create(merged,{idempotencyKey:connectedAccountIdempotencyKey("connect.account.create_test",user.id,merged,options.reference)})}async function accountOnboardingLink(accountId,options){requireAccountId(accountId,"accountOnboardingLink");if(!options?.refreshUrl||!options?.returnUrl)throw Error("[payments/connect] accountOnboardingLink requires refreshUrl and returnUrl");return await stripe.accountLinks.create({account:accountId,refresh_url:options.refreshUrl,return_url:options.returnUrl,type:options.type??"account_onboarding",...options.collect?{collection_options:{fields:options.collect}}:{}})}async function retrieveConnectedAccount(accountId){requireAccountId(accountId,"retrieveConnectedAccount");return await stripe.accounts.retrieve(accountId)}async function accountStatus(accountId){const account=await retrieveConnectedAccount(accountId),requirements=account.requirements;return{chargesEnabled:account.charges_enabled===!0,payoutsEnabled:account.payouts_enabled===!0,detailsSubmitted:account.details_submitted===!0,currentlyDue:requirements?.currently_due??[],pastDue:requirements?.past_due??[],disabledReason:requirements?.disabled_reason??null,raw:account}}return{createConnectedAccount,createTestConnectedAccount,accountOnboardingLink,accountStatus,retrieveConnectedAccount}})();export function requireAccountId(accountId,caller){if(!accountId||typeof accountId!=="string")throw Error(`[payments/connect] ${caller} requires a connected account id`);if(!accountId.startsWith("acct_"))throw Error(`[payments/connect] ${caller} expects a connected account id (acct_...), got "${accountId}"`)}
1
+ import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";export function connectedAccountIdempotencyKey(scope,userId,params,reference){return stacksIdempotencyKey(scope,userId,reference,idempotencyFingerprint(params))}export const MANAGED_RISK_CONTROLLER={stripe_dashboard:{type:"full"},fees:{payer:"account"},losses:{payments:"stripe"},requirement_collection:"stripe"};export function connectedAccountDefaults(params){return params.type||params.controller?{}:{controller:MANAGED_RISK_CONTROLLER}}export const manageConnectedAccount=(()=>{async function createConnectedAccount(user,params={},options={}){const defaults={...connectedAccountDefaults(params),email:user.email??undefined,metadata:{stacks_user_id:String(user.id)}};const merged={...defaults,...params};return await stripe.accounts.create(merged,{idempotencyKey:connectedAccountIdempotencyKey("connect.account.create",user.id,merged,options.reference)})}async function createTestConnectedAccount(user,params={},options={}){const defaults={...connectedAccountDefaults(params),email:user.email??undefined,business_type:"individual",capabilities:{card_payments:{requested:true},transfers:{requested:true}},business_profile:{url:"https://example.com",mcc:"5812"},metadata:{stacks_user_id:String(user.id),stacks_test_account:"true"}};const merged={...defaults,...params};return await stripe.accounts.create(merged,{idempotencyKey:connectedAccountIdempotencyKey("connect.account.create_test",user.id,merged,options.reference)})}async function accountOnboardingLink(accountId,options){requireAccountId(accountId,"accountOnboardingLink");if(!options?.refreshUrl||!options?.returnUrl)throw new Error("[payments/connect] accountOnboardingLink requires refreshUrl and returnUrl");return await stripe.accountLinks.create({account:accountId,refresh_url:options.refreshUrl,return_url:options.returnUrl,type:options.type??"account_onboarding",...options.collect?{collection_options:{fields:options.collect}}:{}})}async function retrieveConnectedAccount(accountId){requireAccountId(accountId,"retrieveConnectedAccount");return await stripe.accounts.retrieve(accountId)}async function accountStatus(accountId){const account=await retrieveConnectedAccount(accountId);const requirements=account.requirements;return{chargesEnabled:account.charges_enabled===true,payoutsEnabled:account.payouts_enabled===true,detailsSubmitted:account.details_submitted===true,currentlyDue:requirements?.currently_due??[],pastDue:requirements?.past_due??[],disabledReason:requirements?.disabled_reason??null,raw:account}}return{createConnectedAccount,createTestConnectedAccount,accountOnboardingLink,accountStatus,retrieveConnectedAccount}})();export function requireAccountId(accountId,caller){if(!accountId||typeof accountId!=="string")throw new Error(`[payments/connect] ${caller} requires a connected account id`);if(!accountId.startsWith("acct_"))throw new Error(`[payments/connect] ${caller} expects a connected account id (acct_...), got "${accountId}"`)}
@@ -1 +1 @@
1
- import{config}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{manageCustomer}from"../billable/customer";import{freshIdempotencyKey}from"../idempotency";import{requireAccountId}from"./account";function defaultCurrency(){const cfg=config||{};return(cfg.payment?.currency||cfg.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}function configuredFeePercent(){return(config||{}).payment?.connect?.platformFeePercent}export const manageDestinationCharge=(()=>{function applicationFeeFor(amount,options={}){if(options.applicationFeeAmount!=null){if(!Number.isFinite(options.applicationFeeAmount)||options.applicationFeeAmount<0)throw Error("[payments/connect] applicationFeeAmount must be a non-negative number of minor units");if(options.applicationFeeAmount>amount)throw Error(`[payments/connect] applicationFeeAmount ${options.applicationFeeAmount} exceeds the charge amount ${amount}`);return Math.floor(options.applicationFeeAmount)}const percent=options.platformFeePercent??configuredFeePercent();if(percent==null)return;if(!Number.isFinite(percent)||percent<0||percent>100)throw Error(`[payments/connect] platformFeePercent must be between 0 and 100, got ${percent}`);return Math.floor(amount*percent/100)}async function destinationCharge(user,amount,destinationAccountId,options={}){requireAccountId(destinationAccountId,"destinationCharge");if(!Number.isFinite(amount)||amount<=0)throw Error("[payments/connect] destinationCharge requires a positive amount in minor units");const{applicationFeeAmount,platformFeePercent,transferGroup,...intentParams}=options,fee=applicationFeeFor(amount,{applicationFeeAmount,platformFeePercent}),params={amount,currency:defaultCurrency(),transfer_data:{destination:destinationAccountId},...fee!=null&&fee>0?{application_fee_amount:fee}:{},...transferGroup?{transfer_group:transferGroup}:{},...intentParams};if(!params.customer&&manageCustomer.hasStripeId(user))params.customer=user.stripe_id??void 0;return await stripe.paymentIntents.create(params,{idempotencyKey:freshIdempotencyKey("connect.destination_charge",user.id,amount)})}return{destinationCharge,applicationFeeFor}})();
1
+ import{config}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{manageCustomer}from"../billable/customer";import{freshIdempotencyKey}from"../idempotency";import{requireAccountId}from"./account";function defaultCurrency(){const cfg=config||{};const fromConfig=cfg.payment?.currency||cfg.billing?.currency;return(fromConfig||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}function configuredFeePercent(){const cfg=config||{};return cfg.payment?.connect?.platformFeePercent}export const manageDestinationCharge=(()=>{function applicationFeeFor(amount,options={}){if(options.applicationFeeAmount!=null){if(!Number.isFinite(options.applicationFeeAmount)||options.applicationFeeAmount<0)throw new Error("[payments/connect] applicationFeeAmount must be a non-negative number of minor units");if(options.applicationFeeAmount>amount)throw new Error(`[payments/connect] applicationFeeAmount ${options.applicationFeeAmount} exceeds the charge amount ${amount}`);return Math.floor(options.applicationFeeAmount)}const percent=options.platformFeePercent??configuredFeePercent();if(percent==null)return;if(!Number.isFinite(percent)||percent<0||percent>100)throw new Error(`[payments/connect] platformFeePercent must be between 0 and 100, got ${percent}`);return Math.floor(amount*percent/100)}async function destinationCharge(user,amount,destinationAccountId,options={}){requireAccountId(destinationAccountId,"destinationCharge");if(!Number.isFinite(amount)||amount<=0)throw new Error("[payments/connect] destinationCharge requires a positive amount in minor units");const{applicationFeeAmount,platformFeePercent,transferGroup,...intentParams}=options;const fee=applicationFeeFor(amount,{applicationFeeAmount,platformFeePercent});const params={amount,currency:defaultCurrency(),transfer_data:{destination:destinationAccountId},...fee!=null&&fee>0?{application_fee_amount:fee}:{},...transferGroup?{transfer_group:transferGroup}:{},...intentParams};if(!params.customer&&manageCustomer.hasStripeId(user))params.customer=user.stripe_id??undefined;return await stripe.paymentIntents.create(params,{idempotencyKey:freshIdempotencyKey("connect.destination_charge",user.id,amount)})}return{destinationCharge,applicationFeeFor}})();
@@ -1 +1 @@
1
- import{requireAccountId}from"./account";function fail(message){throw Error(`[payments/connect] ${message}`)}function checkPercent(percent){if(!Number.isFinite(percent)||percent<0||percent>100)fail(`feePercent must be between 0 and 100, got ${percent}`)}export function destinationFeeCents(amount,options={}){if(!Number.isSafeInteger(amount)||amount<0)fail(`a charge amount is a non-negative whole number of minor units, got ${amount}`);if(options.feeCents!=null){if(!Number.isSafeInteger(options.feeCents)||options.feeCents<0)fail(`feeCents must be a non-negative whole number of minor units, got ${options.feeCents}`);if(options.feeCents>amount)fail(`feeCents ${options.feeCents} exceeds the charge amount ${amount}`);return options.feeCents}if(options.feePercent==null)return 0;checkPercent(options.feePercent);const exact=amount*options.feePercent/100,snapped=Math.abs(exact-Math.round(exact))<0.000000001?Math.round(exact):exact,rounding=options.rounding??"floor";if(rounding!=="floor"&&rounding!=="round")fail(`rounding must be 'round' or 'floor', got ${String(rounding)}`);return Math.min(amount,rounding==="round"?Math.round(snapped):Math.floor(snapped))}export function destinationFeePercent(options={}){if(options.feeCents!=null)fail("a subscription takes its fee as feePercent (Stripe applies it to every invoice), not feeCents");if(options.feePercent==null)return;checkPercent(options.feePercent);const hundredths=options.feePercent*100;if(Math.abs(hundredths-Math.round(hundredths))>0.000001)fail(`feePercent takes at most two decimal places on a subscription, got ${options.feePercent}`);const percent=Math.round(hundredths)/100;return percent>0?percent:void 0}function common(options,caller){if(!options||typeof options!=="object")fail(`${caller} requires options with a destination`);requireAccountId(options.destination,caller);return{transfer_data:{destination:options.destination},...options.onBehalfOf?{on_behalf_of:options.destination}:{}}}export function destinationPaymentIntentParams(amount,options){const base=common(options,"destinationPaymentIntentParams"),fee=destinationFeeCents(amount,options);return{...base,...fee>0?{application_fee_amount:fee}:{},...options.transferGroup?{transfer_group:options.transferGroup}:{}}}export function destinationCheckoutPaymentData(amount,options,extra={}){const base=common(options,"destinationCheckoutPaymentData"),fee=destinationFeeCents(amount,options),rest={...extra};delete rest.application_fee_amount;return{...rest,...base,...fee>0?{application_fee_amount:fee}:{},...options.transferGroup?{transfer_group:options.transferGroup}:{}}}export function destinationCheckoutSubscriptionData(options,extra={}){const base=common(options,"destinationCheckoutSubscriptionData"),percent=destinationFeePercent(options),rest={...extra};delete rest.application_fee_percent;return{...rest,...base,...percent!=null?{application_fee_percent:percent}:{}}}export function destinationSubscriptionParams(options){const base=common(options,"destinationSubscriptionParams"),percent=destinationFeePercent(options);return{...base,...percent!=null?{application_fee_percent:percent}:{}}}export function checkoutLineItemsTotal(lineItems){let total=0;for(const item of lineItems){const unit=item.price_data?.unit_amount;if(unit==null)fail("checkoutLineItemsTotal counts price_data lines only; a catalog price has no amount here");const quantity=item.quantity??1;if(!Number.isSafeInteger(unit)||unit<0||!Number.isSafeInteger(quantity)||quantity<0)fail("a line item needs a whole unit_amount and quantity");total+=unit*quantity}if(!Number.isSafeInteger(total))fail("line items total more than a safe integer");return total}export function splitFee(amount,weights,fallback){if(!Number.isSafeInteger(amount))fail(`splitFee expects a whole number of minor units, got ${amount}`);const keys=Object.keys(weights);if(!keys.length)fail("splitFee needs at least one share");for(const key of keys){const weight=weights[key];if(!Number.isFinite(weight)||weight<0)fail(`share "${key}" needs a non-negative weight, got ${weight}`)}if(fallback!=null&&!keys.includes(fallback))fail(`fallback "${fallback}" is not one of the shares`);const result=Object.fromEntries(keys.map((key)=>[key,0])),sign=amount<0?-1:1,whole=Math.abs(amount),totalWeight=keys.reduce((sum,key)=>sum+weights[key],0);if(totalWeight===0){result[fallback??keys[0]]=amount;return result}const exact=keys.map((key)=>whole*weights[key]/totalWeight),floors=exact.map((value)=>Math.floor(value+0.000000001));let left=whole-floors.reduce((sum,value)=>sum+value,0);const order=keys.map((_,index)=>index).sort((a,b)=>exact[b]-floors[b]-(exact[a]-floors[a])||a-b);for(const index of order){if(left<=0)break;floors[index]+=1;left--}keys.forEach((key,index)=>{result[key]=sign*floors[index]||0});return result}
1
+ import{requireAccountId}from"./account";function fail(message){throw new Error(`[payments/connect] ${message}`)}function checkPercent(percent){if(!Number.isFinite(percent)||percent<0||percent>100)fail(`feePercent must be between 0 and 100, got ${percent}`)}export function destinationFeeCents(amount,options={}){if(!Number.isSafeInteger(amount)||amount<0)fail(`a charge amount is a non-negative whole number of minor units, got ${amount}`);if(options.feeCents!=null){if(!Number.isSafeInteger(options.feeCents)||options.feeCents<0)fail(`feeCents must be a non-negative whole number of minor units, got ${options.feeCents}`);if(options.feeCents>amount)fail(`feeCents ${options.feeCents} exceeds the charge amount ${amount}`);return options.feeCents}if(options.feePercent==null)return 0;checkPercent(options.feePercent);const exact=amount*options.feePercent/100;const snapped=Math.abs(exact-Math.round(exact))<0.000000001?Math.round(exact):exact;const rounding=options.rounding??"floor";if(rounding!=="floor"&&rounding!=="round")fail(`rounding must be 'round' or 'floor', got ${String(rounding)}`);return Math.min(amount,rounding==="round"?Math.round(snapped):Math.floor(snapped))}export function destinationFeePercent(options={}){if(options.feeCents!=null)fail("a subscription takes its fee as feePercent (Stripe applies it to every invoice), not feeCents");if(options.feePercent==null)return;checkPercent(options.feePercent);const hundredths=options.feePercent*100;if(Math.abs(hundredths-Math.round(hundredths))>0.000001)fail(`feePercent takes at most two decimal places on a subscription, got ${options.feePercent}`);const percent=Math.round(hundredths)/100;return percent>0?percent:undefined}function common(options,caller){if(!options||typeof options!=="object")fail(`${caller} requires options with a destination`);requireAccountId(options.destination,caller);return{transfer_data:{destination:options.destination},...options.onBehalfOf?{on_behalf_of:options.destination}:{}}}export function destinationPaymentIntentParams(amount,options){const base=common(options,"destinationPaymentIntentParams");const fee=destinationFeeCents(amount,options);return{...base,...fee>0?{application_fee_amount:fee}:{},...options.transferGroup?{transfer_group:options.transferGroup}:{}}}export function destinationCheckoutPaymentData(amount,options,extra={}){const base=common(options,"destinationCheckoutPaymentData");const fee=destinationFeeCents(amount,options);const rest={...extra};delete rest.application_fee_amount;return{...rest,...base,...fee>0?{application_fee_amount:fee}:{},...options.transferGroup?{transfer_group:options.transferGroup}:{}}}export function destinationCheckoutSubscriptionData(options,extra={}){const base=common(options,"destinationCheckoutSubscriptionData");const percent=destinationFeePercent(options);const rest={...extra};delete rest.application_fee_percent;return{...rest,...base,...percent!=null?{application_fee_percent:percent}:{}}}export function destinationSubscriptionParams(options){const base=common(options,"destinationSubscriptionParams");const percent=destinationFeePercent(options);return{...base,...percent!=null?{application_fee_percent:percent}:{}}}export function checkoutLineItemsTotal(lineItems){let total=0;for(const item of lineItems){const unit=item.price_data?.unit_amount;if(unit==null)fail("checkoutLineItemsTotal counts price_data lines only; a catalog price has no amount here");const quantity=item.quantity??1;if(!Number.isSafeInteger(unit)||unit<0||!Number.isSafeInteger(quantity)||quantity<0)fail("a line item needs a whole unit_amount and quantity");total+=unit*quantity}if(!Number.isSafeInteger(total))fail("line items total more than a safe integer");return total}export function splitFee(amount,weights,fallback){if(!Number.isSafeInteger(amount))fail(`splitFee expects a whole number of minor units, got ${amount}`);const keys=Object.keys(weights);if(!keys.length)fail("splitFee needs at least one share");for(const key of keys){const weight=weights[key];if(!Number.isFinite(weight)||weight<0)fail(`share "${key}" needs a non-negative weight, got ${weight}`)}if(fallback!=null&&!keys.includes(fallback))fail(`fallback "${fallback}" is not one of the shares`);const result=Object.fromEntries(keys.map((key)=>[key,0]));const sign=amount<0?-1:1;const whole=Math.abs(amount);const totalWeight=keys.reduce((sum,key)=>sum+weights[key],0);if(totalWeight===0){result[fallback??keys[0]]=amount;return result}const exact=keys.map((key)=>whole*weights[key]/totalWeight);const floors=exact.map((value)=>Math.floor(value+0.000000001));let left=whole-floors.reduce((sum,value)=>sum+value,0);const order=keys.map((_,index)=>index).sort((a,b)=>exact[b]-floors[b]-(exact[a]-floors[a])||a-b);for(const index of order){if(left<=0)break;floors[index]+=1;left--}keys.forEach((key,index)=>{result[key]=sign*floors[index]||0});return result}
@@ -1 +1 @@
1
- import{createHmac}from"node:crypto";import{app}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{assertSameOriginUrl}from"../billable/checkout";import{freshIdempotencyKey,idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{requireAccountId}from"./account";import{destinationFeeCents,destinationFeePercent}from"./destination";import{manageDestinationSubscription}from"./subscription";export function asAccount(accountId,extra={}){requireAccountId(accountId,"asAccount");return{...extra,stripeAccount:accountId}}export function directPaymentIntentParams(amount,options={}){const fee=destinationFeeCents(amount,options);return fee>0?{application_fee_amount:fee}:{}}export function directCheckoutPaymentData(amount,options={},extra={}){const rest={...extra};delete rest.application_fee_amount;delete rest.transfer_data;delete rest.on_behalf_of;delete rest.transfer_group;return{...rest,...directPaymentIntentParams(amount,options)}}export function directCheckoutSubscriptionData(options={},extra={}){const percent=destinationFeePercent(options),rest={...extra};delete rest.application_fee_percent;delete rest.transfer_data;delete rest.on_behalf_of;return{...rest,...percent!=null?{application_fee_percent:percent}:{}}}export function directSubscriptionParams(options={}){const percent=destinationFeePercent(options);return percent!=null?{application_fee_percent:percent}:{}}export function connectedCustomerIdempotencyKey(accountId,userId,params={}){return stacksIdempotencyKey("connect.customer.create",userId,accountId,idempotencyFingerprint(params))}export function connectInstallFingerprint(appKey=app?.key,appUrl=app?.url){const secret=String(appKey||"").trim()||String(appUrl||"").trim()||"stacks";return createHmac("sha256",secret).update("stacks.payments.connect.install").digest("hex").slice(0,16)}function normalizedEmail(email){return String(email??"").trim().toLowerCase()}export async function connectedCustomer(user,accountId,client=stripe,customerOptions={}){requireAccountId(accountId,"connectedCustomer");const userId=String(user.id),email=normalizedEmail(user.email),install=customerOptions.install??connectInstallFingerprint(),options=asAccount(accountId),claim=(customer)=>{if("deleted"in customer&&customer.deleted)return 0;const found=customer;if(found.metadata?.stacks_user_id!==userId||normalizedEmail(found.email)!==email)return 0;const mark=found.metadata?.stacks_install;if(mark===install)return 2;return!mark&&email?1:0},best=(customers)=>{let pick,rank=0;for(const customer of customers){const score=claim(customer);if(score>rank){pick=customer;rank=score}}return pick},adopt=async(customer)=>{if(customer.metadata?.stacks_install===install)return customer;try{return await client.customers.update(customer.id,{metadata:{stacks_install:install}},options)}catch{return customer}};if(user.email){const byEmail=await client.customers.list({email:user.email,limit:100},options),found=best(byEmail.data);if(found)return await adopt(found)}try{const searched=await client.customers.search({query:`metadata['stacks_user_id']:'${userId.replace(/'/g,"")}'`,limit:100},options),found=best(searched.data);if(found)return await adopt(found)}catch{}const params={...user.email?{email:user.email}:{},...user.name?{name:user.name}:{},metadata:{stacks_user_id:userId,stacks_install:install}};return await client.customers.create(params,asAccount(accountId,{idempotencyKey:connectedCustomerIdempotencyKey(accountId,userId,params)}))}export async function directCheckout(user,accountId,params,client=stripe,request={}){requireAccountId(accountId,"directCheckout");if(request.idempotencyKey!==void 0&&(typeof request.idempotencyKey!=="string"||!/^[\x21-\x7e]{1,255}$/.test(request.idempotencyKey)))throw TypeError("A checkout idempotency key must contain 1-255 printable ASCII characters");assertSameOriginUrl(params.success_url,"success_url");assertSameOriginUrl(params.cancel_url,"cancel_url");const customer=params.customer??(params.customer_email?void 0:(await connectedCustomer(user,accountId,client)).id);return await client.checkout.sessions.create({mode:"payment",...params,...customer?{customer}:{}},asAccount(accountId,{idempotencyKey:request.idempotencyKey??freshIdempotencyKey("connect.checkout.create",user.id,accountId)}))}export const manageDirectSubscription=(()=>{function subscriptionData(options={}){if(options.trialDays!=null&&(!Number.isInteger(options.trialDays)||options.trialDays<1||options.trialDays>730))throw Error(`[payments/connect] trialDays must be a whole number from 1 to 730, got ${options.trialDays}`);const fee=manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});return{...fee!=null?{application_fee_percent:fee}:{},...options.trialDays?{trial_period_days:options.trialDays}:{},...options.metadata?{metadata:options.metadata}:{}}}async function checkout(user,options,client=stripe){requireAccountId(options.account,"manageDirectSubscription.checkout");const customer=options.customer??(await connectedCustomer(user,options.account,client)).id;return await directCheckout(user,options.account,{mode:"subscription",customer,line_items:[manageDestinationSubscription.lineItem(options.price,options.quantity)],subscription_data:subscriptionData(options),success_url:options.successUrl,cancel_url:options.cancelUrl,...options.clientReferenceId?{client_reference_id:options.clientReferenceId}:{},...options.metadata?{metadata:options.metadata}:{},...options.sessionParams},client,{idempotencyKey:options.idempotencyKey})}return{subscriptionData,checkout}})();
1
+ import{createHmac}from"node:crypto";import{app}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{assertSameOriginUrl}from"../billable/checkout";import{freshIdempotencyKey,idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{requireAccountId}from"./account";import{destinationFeeCents,destinationFeePercent}from"./destination";import{manageDestinationSubscription}from"./subscription";export function asAccount(accountId,extra={}){requireAccountId(accountId,"asAccount");return{...extra,stripeAccount:accountId}}export function directPaymentIntentParams(amount,options={}){const fee=destinationFeeCents(amount,options);return fee>0?{application_fee_amount:fee}:{}}export function directCheckoutPaymentData(amount,options={},extra={}){const rest={...extra};delete rest.application_fee_amount;delete rest.transfer_data;delete rest.on_behalf_of;delete rest.transfer_group;return{...rest,...directPaymentIntentParams(amount,options)}}export function directCheckoutSubscriptionData(options={},extra={}){const percent=destinationFeePercent(options);const rest={...extra};delete rest.application_fee_percent;delete rest.transfer_data;delete rest.on_behalf_of;return{...rest,...percent!=null?{application_fee_percent:percent}:{}}}export function directSubscriptionParams(options={}){const percent=destinationFeePercent(options);return percent!=null?{application_fee_percent:percent}:{}}export function connectedCustomerIdempotencyKey(accountId,userId,params={}){return stacksIdempotencyKey("connect.customer.create",userId,accountId,idempotencyFingerprint(params))}export function connectInstallFingerprint(appKey=app?.key,appUrl=app?.url){const secret=String(appKey||"").trim()||String(appUrl||"").trim()||"stacks";return createHmac("sha256",secret).update("stacks.payments.connect.install").digest("hex").slice(0,16)}function normalizedEmail(email){return String(email??"").trim().toLowerCase()}export async function connectedCustomer(user,accountId,client=stripe,customerOptions={}){requireAccountId(accountId,"connectedCustomer");const userId=String(user.id);const email=normalizedEmail(user.email);const install=customerOptions.install??connectInstallFingerprint();const options=asAccount(accountId);const claim=(customer)=>{if("deleted"in customer&&customer.deleted)return 0;const found=customer;if(found.metadata?.stacks_user_id!==userId||normalizedEmail(found.email)!==email)return 0;const mark=found.metadata?.stacks_install;if(mark===install)return 2;return!mark&&email?1:0};const best=(customers)=>{let pick;let rank=0;for(const customer of customers){const score=claim(customer);if(score>rank){pick=customer;rank=score}}return pick};const adopt=async(customer)=>{if(customer.metadata?.stacks_install===install)return customer;try{return await client.customers.update(customer.id,{metadata:{stacks_install:install}},options)}catch{return customer}};if(user.email){const byEmail=await client.customers.list({email:user.email,limit:100},options);const found=best(byEmail.data);if(found)return await adopt(found)}try{const searched=await client.customers.search({query:`metadata['stacks_user_id']:'${userId.replace(/'/g,"")}'`,limit:100},options);const found=best(searched.data);if(found)return await adopt(found)}catch{}const params={...user.email?{email:user.email}:{},...user.name?{name:user.name}:{},metadata:{stacks_user_id:userId,stacks_install:install}};return await client.customers.create(params,asAccount(accountId,{idempotencyKey:connectedCustomerIdempotencyKey(accountId,userId,params)}))}export async function directCheckout(user,accountId,params,client=stripe,request={}){requireAccountId(accountId,"directCheckout");if(request.idempotencyKey!==undefined&&(typeof request.idempotencyKey!=="string"||!/^[\x21-\x7e]{1,255}$/.test(request.idempotencyKey)))throw new TypeError("A checkout idempotency key must contain 1-255 printable ASCII characters");assertSameOriginUrl(params.success_url,"success_url");assertSameOriginUrl(params.cancel_url,"cancel_url");const customer=params.customer??(params.customer_email?undefined:(await connectedCustomer(user,accountId,client)).id);return await client.checkout.sessions.create({mode:"payment",...params,...customer?{customer}:{}},asAccount(accountId,{idempotencyKey:request.idempotencyKey??freshIdempotencyKey("connect.checkout.create",user.id,accountId)}))}export const manageDirectSubscription=(()=>{function subscriptionData(options={}){if(options.trialDays!=null&&(!Number.isInteger(options.trialDays)||options.trialDays<1||options.trialDays>730))throw new Error(`[payments/connect] trialDays must be a whole number from 1 to 730, got ${options.trialDays}`);const fee=manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});return{...fee!=null?{application_fee_percent:fee}:{},...options.trialDays?{trial_period_days:options.trialDays}:{},...options.metadata?{metadata:options.metadata}:{}}}async function checkout(user,options,client=stripe){requireAccountId(options.account,"manageDirectSubscription.checkout");const customer=options.customer??(await connectedCustomer(user,options.account,client)).id;return await directCheckout(user,options.account,{mode:"subscription",customer,line_items:[manageDestinationSubscription.lineItem(options.price,options.quantity)],subscription_data:subscriptionData(options),success_url:options.successUrl,cancel_url:options.cancelUrl,...options.clientReferenceId?{client_reference_id:options.clientReferenceId}:{},...options.metadata?{metadata:options.metadata}:{},...options.sessionParams},client,{idempotencyKey:options.idempotencyKey})}return{subscriptionData,checkout}})();
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{asAccount}from"./direct";import{allPages}from"./pagination";export class DirectChargeFinancialsPendingError extends Error{}export function directChargeFeeAmounts(facts){const cents=(value)=>{if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw Error("Invalid direct-charge fee amount");return value},currency=facts.charge.currency.toUpperCase(),chargedCents=cents(facts.charge.application_fee_amount??0),unknown=()=>({currency,chargedCents,returnedCents:null,remainingCents:null,requiresReview:!0}),known=(returnedCents)=>({currency,chargedCents,returnedCents,remainingCents:chargedCents-returnedCents,requiresReview:!1}),fee=facts.applicationFee;if(!fee)return chargedCents===0&&!facts.applicationFeeRefunds.length?known(0):unknown();const amount=cents(fee.amount),returned=cents(fee.amount_refunded),feeCurrency=fee.currency?.toUpperCase(),refunds=facts.applicationFeeRefunds,amounts=refunds.map((refund)=>cents(refund.amount)),recorded=refunds.every((refund)=>refund.currency?.toUpperCase()===feeCurrency)?amounts.reduce((sum,value)=>sum+value,0):null;if(id(fee.account)!==facts.account||id(fee.charge)!==facts.charge.id||!/^[A-Z]{3}$/.test(feeCurrency||"")||refunds.some((refund)=>id(refund.fee)!==fee.id||!/^[a-z]{3}$/i.test(refund.currency||"")||refund.amount<=0)||recorded!==null&&(!Number.isSafeInteger(recorded)||recorded!==returned)||returned>0!==refunds.length>0||returned>amount||chargedCents===0&&amount>0)return unknown();if(feeCurrency===currency)return amount===chargedCents?known(returned):unknown();if(returned===0)return known(0);if(returned===amount)return known(chargedCents);return unknown()}function id(value){return typeof value==="string"?value:String(value?.id||"")}export async function directChargeFinancials(paymentIntentId,account,client=stripe){const options=asAccount(account);if(!/^pi_[a-z0-9_]+$/i.test(paymentIntentId))throw Error("Expected a Stripe PaymentIntent ID");const intent=await client.paymentIntents.retrieve(paymentIntentId,{},options);if(intent.id!==paymentIntentId||intent.status!=="succeeded"||!id(intent.latest_charge))throw new DirectChargeFinancialsPendingError("The original payment has no successful charge yet");const charge=await client.charges.retrieve(id(intent.latest_charge),{},options);if(id(charge.payment_intent)!==paymentIntentId||charge.id!==id(intent.latest_charge)||!charge.paid||!charge.captured)throw Error("Charge does not match the successful direct payment");const refunds=await allPages((after)=>client.refunds.list({charge:charge.id,limit:100,...after?{starting_after:after}:{}},options)),disputes=await allPages((after)=>client.disputes.list({charge:charge.id,limit:100,...after?{starting_after:after}:{}},options));for(const item of[...refunds,...disputes])if(id(item.charge)!==charge.id||item.payment_intent&&id(item.payment_intent)!==paymentIntentId)throw Error("Foreign refund or dispute in direct-charge financials");let applicationFee=null;if(id(charge.application_fee))applicationFee=await client.applicationFees.retrieve(id(charge.application_fee));else if(Number(charge.application_fee_amount)>0){const fees=await allPages((after)=>client.applicationFees.list({charge:charge.id,limit:100,...after?{starting_after:after}:{}}));if(fees.length!==1)throw new DirectChargeFinancialsPendingError("The direct-charge application fee is not available yet");applicationFee=fees[0]}if(applicationFee&&(id(applicationFee.account)!==account||id(applicationFee.charge)!==charge.id))throw Error("Application fee belongs to another direct charge or account");const applicationFeeRefunds=applicationFee?await allPages((after)=>client.applicationFees.listRefunds(applicationFee.id,{limit:100,...after?{starting_after:after}:{}})):[];if(applicationFeeRefunds.some((refund)=>id(refund.fee)!==applicationFee.id))throw Error("Foreign application-fee refund");const movements=[],seen=new Map;async function movement(reference,sourceId,kind,scope,required=!0,providerSourceId=sourceId){const transactionId=id(reference);if(!transactionId){if(required)throw new DirectChargeFinancialsPendingError("A provider balance transaction is not available yet");return}if(!/^txn_[a-z0-9_]+$/i.test(transactionId))throw Error("Invalid provider balance transaction");const transaction=await client.balanceTransactions.retrieve(transactionId,{},scope==="platform"?void 0:options);if(transaction.id!==transactionId||id(transaction.source)&&id(transaction.source)!==providerSourceId)throw Error("Foreign provider balance transaction");const entry={account:scope,sourceId,kind,transaction},key=`${scope}:${transactionId}`;if(seen.has(key)){if(JSON.stringify(seen.get(key))!==JSON.stringify(entry))throw Error("Conflicting provider balance transaction");return}seen.set(key,entry);movements.push(entry)}await movement(charge.balance_transaction,charge.id,"charge",account);for(const refund of refunds){await movement(refund.balance_transaction,refund.id,"refund",account,refund.status==="succeeded");await movement(refund.failure_balance_transaction,refund.id,"refund",account,!1)}for(const dispute of disputes)for(const transaction of dispute.balance_transactions)await movement(transaction,dispute.id,"dispute",account);if(applicationFee)await movement(applicationFee.balance_transaction,applicationFee.id,"application_fee","platform");for(const refund of applicationFeeRefunds)await movement(refund.balance_transaction,refund.id,"application_fee_refund","platform",!0,applicationFee.id);return{account,charge,refunds,disputes,applicationFee,applicationFeeRefunds,movements}}
1
+ import{stripe}from"../drivers/stripe";import{asAccount}from"./direct";import{allPages}from"./pagination";export class DirectChargeFinancialsPendingError extends Error{}export function directChargeFeeAmounts(facts){const cents=(value)=>{if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new Error("Invalid direct-charge fee amount");return value};const currency=facts.charge.currency.toUpperCase();const chargedCents=cents(facts.charge.application_fee_amount??0);const unknown=()=>({currency,chargedCents,returnedCents:null,remainingCents:null,requiresReview:true});const known=(returnedCents)=>({currency,chargedCents,returnedCents,remainingCents:chargedCents-returnedCents,requiresReview:false});const fee=facts.applicationFee;if(!fee)return chargedCents===0&&!facts.applicationFeeRefunds.length?known(0):unknown();const amount=cents(fee.amount);const returned=cents(fee.amount_refunded);const feeCurrency=fee.currency?.toUpperCase();const refunds=facts.applicationFeeRefunds;const amounts=refunds.map((refund)=>cents(refund.amount));const sameCurrency=refunds.every((refund)=>refund.currency?.toUpperCase()===feeCurrency);const recorded=sameCurrency?amounts.reduce((sum,value)=>sum+value,0):null;if(id(fee.account)!==facts.account||id(fee.charge)!==facts.charge.id||!/^[A-Z]{3}$/.test(feeCurrency||"")||refunds.some((refund)=>id(refund.fee)!==fee.id||!/^[a-z]{3}$/i.test(refund.currency||"")||refund.amount<=0)||recorded!==null&&(!Number.isSafeInteger(recorded)||recorded!==returned)||returned>0!==refunds.length>0||returned>amount||chargedCents===0&&amount>0)return unknown();if(feeCurrency===currency)return amount===chargedCents?known(returned):unknown();if(returned===0)return known(0);if(returned===amount)return known(chargedCents);return unknown()}function id(value){return typeof value==="string"?value:String(value?.id||"")}export async function directChargeFinancials(paymentIntentId,account,client=stripe){const options=asAccount(account);if(!/^pi_[a-z0-9_]+$/i.test(paymentIntentId))throw new Error("Expected a Stripe PaymentIntent ID");const intent=await client.paymentIntents.retrieve(paymentIntentId,{},options);if(intent.id!==paymentIntentId||intent.status!=="succeeded"||!id(intent.latest_charge))throw new DirectChargeFinancialsPendingError("The original payment has no successful charge yet");const charge=await client.charges.retrieve(id(intent.latest_charge),{},options);if(id(charge.payment_intent)!==paymentIntentId||charge.id!==id(intent.latest_charge)||!charge.paid||!charge.captured)throw new Error("Charge does not match the successful direct payment");const refunds=await allPages((after)=>client.refunds.list({charge:charge.id,limit:100,...after?{starting_after:after}:{}},options));const disputes=await allPages((after)=>client.disputes.list({charge:charge.id,limit:100,...after?{starting_after:after}:{}},options));for(const item of[...refunds,...disputes]){if(id(item.charge)!==charge.id||item.payment_intent&&id(item.payment_intent)!==paymentIntentId)throw new Error("Foreign refund or dispute in direct-charge financials")}let applicationFee=null;if(id(charge.application_fee))applicationFee=await client.applicationFees.retrieve(id(charge.application_fee));else if(Number(charge.application_fee_amount)>0){const fees=await allPages((after)=>client.applicationFees.list({charge:charge.id,limit:100,...after?{starting_after:after}:{}}));if(fees.length!==1)throw new DirectChargeFinancialsPendingError("The direct-charge application fee is not available yet");applicationFee=fees[0]}if(applicationFee&&(id(applicationFee.account)!==account||id(applicationFee.charge)!==charge.id))throw new Error("Application fee belongs to another direct charge or account");const applicationFeeRefunds=applicationFee?await allPages((after)=>client.applicationFees.listRefunds(applicationFee.id,{limit:100,...after?{starting_after:after}:{}})):[];if(applicationFeeRefunds.some((refund)=>id(refund.fee)!==applicationFee.id))throw new Error("Foreign application-fee refund");const movements=[];const seen=new Map;async function movement(reference,sourceId,kind,scope,required=true,providerSourceId=sourceId){const transactionId=id(reference);if(!transactionId){if(required)throw new DirectChargeFinancialsPendingError("A provider balance transaction is not available yet");return}if(!/^txn_[a-z0-9_]+$/i.test(transactionId))throw new Error("Invalid provider balance transaction");const transaction=await client.balanceTransactions.retrieve(transactionId,{},scope==="platform"?undefined:options);if(transaction.id!==transactionId||id(transaction.source)&&id(transaction.source)!==providerSourceId)throw new Error("Foreign provider balance transaction");const entry={account:scope,sourceId,kind,transaction};const key=`${scope}:${transactionId}`;if(seen.has(key)){if(JSON.stringify(seen.get(key))!==JSON.stringify(entry))throw new Error("Conflicting provider balance transaction");return}seen.set(key,entry);movements.push(entry)}await movement(charge.balance_transaction,charge.id,"charge",account);for(const refund of refunds){await movement(refund.balance_transaction,refund.id,"refund",account,refund.status==="succeeded");await movement(refund.failure_balance_transaction,refund.id,"refund",account,false)}for(const dispute of disputes)for(const transaction of dispute.balance_transactions)await movement(transaction,dispute.id,"dispute",account);if(applicationFee)await movement(applicationFee.balance_transaction,applicationFee.id,"application_fee","platform");for(const refund of applicationFeeRefunds)await movement(refund.balance_transaction,refund.id,"application_fee_refund","platform",true,applicationFee.id);return{account,charge,refunds,disputes,applicationFee,applicationFeeRefunds,movements}}
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{splitFee}from"./destination";import{prepareDirectInvoiceFee}from"./invoice-fee";import{allPages}from"./pagination";import{manageDestinationSubscription}from"./subscription";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:value?.id}export async function collectDirectInvoice(invoiceId,account,options,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^cus_[a-z0-9_]+$/i.test(options.customer)||options.subscription!=null&&!/^sub_[a-z0-9_]+$/i.test(options.subscription)||!/^[a-z]{3}$/i.test(options.currency)||options.paymentMethod!==void 0&&!/^pm_[a-z0-9_]+$/i.test(options.paymentMethod)||!Number.isSafeInteger(options.approvedTotal)||options.approvedTotal<0)throw Error("[payments/connect] Expected original invoice, customer, subscription, currency, saved method and approved total");if(options.platformFeePercent==null)throw Error("[payments/connect] An explicit invoice fee percentage is required");manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});const verify=(value)=>{if(value.id!==invoiceId||!["draft","open","paid"].includes(value.status||"")||id(value.customer)!==options.customer||id(value.parent?.subscription_details?.subscription)!==options.subscription||value.currency.toUpperCase()!==options.currency.toUpperCase()||value.amount_due!==options.approvedTotal)throw Error("[payments/connect] Collection requires the original collectible invoice and approved amount");const totals=invoiceTaxAmounts(value);if(totals.gross!==options.approvedTotal)throw Error("[payments/connect] Invoice total differs from the buyer-approved amount");return totals};let invoice=await client.invoices.retrieve(invoiceId,{},request);const basis=verify(invoice),bps=Math.round(options.platformFeePercent*100),fee=splitFee(basis.net,{platform:bps,merchant:1e4-bps},"merchant").platform,stable=(value)=>{const totals=verify(value);if(totals.net!==basis.net||totals.tax!==basis.tax)throw Error("[payments/connect] Invoice tax changed during collection; payment was not authorized")};if(invoice.status!=="paid"&&invoice.auto_advance!==!1){invoice=await client.invoices.update(invoiceId,{auto_advance:!1},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.hold",account,invoiceId)});stable(invoice)}if(invoice.status!=="paid"&&basis.gross>0&&options.paymentMethod){const method=await client.paymentMethods.retrieve(options.paymentMethod,{},request);if(method.id!==options.paymentMethod||id(method.customer)!==options.customer)throw Error("[payments/connect] Saved payment method belongs to another customer")}if(invoice.status==="draft"){const prepared=await prepareDirectInvoiceFee(invoiceId,account,options,client);stable(prepared.invoice);invoice=await client.invoices.finalizeInvoice(invoiceId,{auto_advance:!1},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.finalize",account,invoiceId,basis.gross,basis.tax,fee)});stable(invoice)}const result=(status,intent)=>({invoice,status,...intent?{paymentIntent:intent}:{},...status==="requires_payment"&&invoice.hosted_invoice_url?{paymentUrl:invoice.hosted_invoice_url}:{},currency:invoice.currency.toUpperCase(),...basis,fee});if(basis.gross===0){if(invoice.status!=="paid")throw Error("[payments/connect] Zero invoice has not been marked paid by the provider");return result("paid")}const candidates=(await allPages((after)=>client.invoicePayments.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request))).filter((payment)=>payment.status!=="canceled"&&payment.payment.type==="payment_intent");if(candidates.length!==1||id(candidates[0].invoice)!==invoiceId||!id(candidates[0].payment.payment_intent))throw Error("[payments/connect] Expected one canonical invoice payment intent");const intentId=id(candidates[0].payment.payment_intent),readIntent=async()=>{const intent=await client.paymentIntents.retrieve(intentId,{},request);if(intent.id!==intentId||id(intent.customer)!==options.customer||intent.currency.toUpperCase()!==options.currency.toUpperCase()||intent.amount!==basis.gross||(intent.application_fee_amount??0)!==fee||intent.status==="canceled")throw Error("[payments/connect] Invoice payment does not match its original customer, currency, amount or after-tax fee");return intent};let intent=await readIntent();if(invoice.status==="paid"){if(intent.status!=="succeeded")throw Error("[payments/connect] Paid invoice has no successful original payment");return result("paid",intent)}if(intent.status==="processing"||intent.status==="succeeded")return result("processing",intent);if(intent.status==="requires_action")return result("requires_payment",intent);if(!["requires_confirmation","requires_payment_method"].includes(intent.status))throw Error("[payments/connect] Invoice payment is not ready for automatic collection");if(!options.paymentMethod)return result("requires_payment",intent);try{invoice=await client.invoices.pay(invoiceId,{payment_method:options.paymentMethod,off_session:!0},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.pay",account,invoiceId,intentId,options.paymentMethod,basis.gross,basis.tax,fee)});stable(invoice);intent=await readIntent();if(invoice.status==="paid"&&intent.status!=="succeeded")throw Error("[payments/connect] Paid invoice has no successful original payment");return result(invoice.status==="paid"?"paid":["processing","succeeded"].includes(intent.status)?"processing":"requires_payment",intent)}catch(error){if(error?.type!=="StripeCardError")throw error;invoice=await client.invoices.retrieve(invoiceId,{},request);stable(invoice);intent=await readIntent();if(invoice.status==="paid"&&intent.status!=="succeeded")throw Error("[payments/connect] Paid invoice has no successful original payment");return result(invoice.status==="paid"?"paid":"requires_payment",intent)}}
1
+ import{stripe}from"../drivers/stripe";import{stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{splitFee}from"./destination";import{prepareDirectInvoiceFee}from"./invoice-fee";import{allPages}from"./pagination";import{manageDestinationSubscription}from"./subscription";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:value?.id}export async function collectDirectInvoice(invoiceId,account,options,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^cus_[a-z0-9_]+$/i.test(options.customer)||options.subscription!=null&&!/^sub_[a-z0-9_]+$/i.test(options.subscription)||!/^[a-z]{3}$/i.test(options.currency)||options.paymentMethod!==undefined&&!/^pm_[a-z0-9_]+$/i.test(options.paymentMethod)||!Number.isSafeInteger(options.approvedTotal)||options.approvedTotal<0)throw new Error("[payments/connect] Expected original invoice, customer, subscription, currency, saved method and approved total");if(options.platformFeePercent==null)throw new Error("[payments/connect] An explicit invoice fee percentage is required");manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});const verify=(value)=>{if(value.id!==invoiceId||!["draft","open","paid"].includes(value.status||"")||id(value.customer)!==options.customer||id(value.parent?.subscription_details?.subscription)!==options.subscription||value.currency.toUpperCase()!==options.currency.toUpperCase()||value.amount_due!==options.approvedTotal)throw new Error("[payments/connect] Collection requires the original collectible invoice and approved amount");const totals=invoiceTaxAmounts(value);if(totals.gross!==options.approvedTotal)throw new Error("[payments/connect] Invoice total differs from the buyer-approved amount");return totals};let invoice=await client.invoices.retrieve(invoiceId,{},request);const basis=verify(invoice);const bps=Math.round(options.platformFeePercent*100);const fee=splitFee(basis.net,{platform:bps,merchant:1e4-bps},"merchant").platform;const stable=(value)=>{const totals=verify(value);if(totals.net!==basis.net||totals.tax!==basis.tax)throw new Error("[payments/connect] Invoice tax changed during collection; payment was not authorized")};if(invoice.status!=="paid"&&invoice.auto_advance!==false){invoice=await client.invoices.update(invoiceId,{auto_advance:false},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.hold",account,invoiceId)});stable(invoice)}if(invoice.status!=="paid"&&basis.gross>0&&options.paymentMethod){const method=await client.paymentMethods.retrieve(options.paymentMethod,{},request);if(method.id!==options.paymentMethod||id(method.customer)!==options.customer)throw new Error("[payments/connect] Saved payment method belongs to another customer")}if(invoice.status==="draft"){const prepared=await prepareDirectInvoiceFee(invoiceId,account,options,client);stable(prepared.invoice);invoice=await client.invoices.finalizeInvoice(invoiceId,{auto_advance:false},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.finalize",account,invoiceId,basis.gross,basis.tax,fee)});stable(invoice)}const result=(status,intent)=>({invoice,status,...intent?{paymentIntent:intent}:{},...status==="requires_payment"&&invoice.hosted_invoice_url?{paymentUrl:invoice.hosted_invoice_url}:{},currency:invoice.currency.toUpperCase(),...basis,fee});if(basis.gross===0){if(invoice.status!=="paid")throw new Error("[payments/connect] Zero invoice has not been marked paid by the provider");return result("paid")}const payments=await allPages((after)=>client.invoicePayments.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request));const candidates=payments.filter((payment)=>payment.status!=="canceled"&&payment.payment.type==="payment_intent");if(candidates.length!==1||id(candidates[0].invoice)!==invoiceId||!id(candidates[0].payment.payment_intent))throw new Error("[payments/connect] Expected one canonical invoice payment intent");const intentId=id(candidates[0].payment.payment_intent);const readIntent=async()=>{const intent=await client.paymentIntents.retrieve(intentId,{},request);if(intent.id!==intentId||id(intent.customer)!==options.customer||intent.currency.toUpperCase()!==options.currency.toUpperCase()||intent.amount!==basis.gross||(intent.application_fee_amount??0)!==fee||intent.status==="canceled")throw new Error("[payments/connect] Invoice payment does not match its original customer, currency, amount or after-tax fee");return intent};let intent=await readIntent();if(invoice.status==="paid"){if(intent.status!=="succeeded")throw new Error("[payments/connect] Paid invoice has no successful original payment");return result("paid",intent)}if(intent.status==="processing"||intent.status==="succeeded")return result("processing",intent);if(intent.status==="requires_action")return result("requires_payment",intent);if(!["requires_confirmation","requires_payment_method"].includes(intent.status))throw new Error("[payments/connect] Invoice payment is not ready for automatic collection");if(!options.paymentMethod)return result("requires_payment",intent);try{invoice=await client.invoices.pay(invoiceId,{payment_method:options.paymentMethod,off_session:true},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.pay",account,invoiceId,intentId,options.paymentMethod,basis.gross,basis.tax,fee)});stable(invoice);intent=await readIntent();if(invoice.status==="paid"&&intent.status!=="succeeded")throw new Error("[payments/connect] Paid invoice has no successful original payment");return result(invoice.status==="paid"?"paid":["processing","succeeded"].includes(intent.status)?"processing":"requires_payment",intent)}catch(error){if(error?.type!=="StripeCardError")throw error;invoice=await client.invoices.retrieve(invoiceId,{},request);stable(invoice);intent=await readIntent();if(invoice.status==="paid"&&intent.status!=="succeeded")throw new Error("[payments/connect] Paid invoice has no successful original payment");return result(invoice.status==="paid"?"paid":"requires_payment",intent)}}
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{allPages}from"./pagination";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:String(value?.id||"")}export async function creditDirectInvoiceRefund(invoiceId,account,refundId,lines,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^re_[a-z0-9_]+$/i.test(refundId)||!lines.length||lines.length>100||lines.some((line)=>!/^il_[a-z0-9_]+$/i.test(line.invoiceLineItem)||!Number.isSafeInteger(line.amount)||line.amount<=0)||new Set(lines.map((line)=>line.invoiceLineItem)).size!==lines.length)throw Error("[payments/connect] Expected original invoice, refund and unique positive credit lines");const invoice=await client.invoices.retrieve(invoiceId,{},request),refund=await client.refunds.retrieve(refundId,{},request);if(invoice.id!==invoiceId||invoice.status!=="paid"||refund.id!==refundId||refund.status!=="succeeded"||refund.currency!==invoice.currency||!Number.isSafeInteger(refund.amount)||refund.amount<=0||!id(refund.payment_intent))throw Error("[payments/connect] Expected the original paid invoice and successful refund in its currency");if(!(await allPages((after)=>client.invoicePayments.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request))).some((payment)=>payment.status==="paid"&&id(payment.payment.payment_intent)===id(refund.payment_intent)))throw Error("[payments/connect] Refund belongs to another invoice payment");const invoiceLines=await allPages((after)=>client.invoices.listLineItems(invoiceId,{limit:100,...after?{starting_after:after}:{}},request));if(lines.some((line)=>!invoiceLines.some((original)=>original.id===line.invoiceLineItem)))throw Error("[payments/connect] Credit line belongs to another invoice");const params={invoice:invoiceId,lines:[...lines].sort((a,b)=>a.invoiceLineItem.localeCompare(b.invoiceLineItem)).map((line)=>({type:"invoice_line_item",invoice_line_item:line.invoiceLineItem,amount:line.amount})),refunds:[{refund:refundId,amount_refunded:refund.amount}]},verify=(credit)=>{if(id(credit.invoice)!==invoiceId||id(credit.customer)!==id(invoice.customer)||credit.currency!==invoice.currency||credit.total!==refund.amount)throw Error("[payments/connect] Credit does not match the original invoice or refund amount");return{creditNote:credit,...invoiceTaxAmounts(credit),currency:invoice.currency.toUpperCase()}},validateIssued=async(credit)=>{const result=verify(credit);if(credit.status!=="issued"||credit.refunds.length!==1||id(credit.refunds[0].refund)!==refundId||credit.refunds[0].amount_refunded!==refund.amount)throw Error("[payments/connect] Credit does not bind the complete original refund");const actual=await allPages((after)=>client.creditNotes.listLineItems(credit.id,{limit:100,...after?{starting_after:after}:{}},request));if(actual.length!==lines.length||actual.some((line)=>line.type!=="invoice_line_item"||!lines.some((expected)=>expected.invoiceLineItem===line.invoice_line_item&&expected.amount===line.amount)))throw Error("[payments/connect] Refund was credited with different invoice lines");return result},previous=(await allPages((after)=>client.creditNotes.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request))).filter((credit)=>credit.status==="issued"&&credit.refunds.some((row)=>id(row.refund)===refundId));if(previous.length>1)throw Error("[payments/connect] Refund is associated with several credit notes");if(previous[0])return validateIssued(previous[0]);verify(await client.creditNotes.preview(params,request));const credit=await client.creditNotes.create({...params,email_type:"none"},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.refund-credit",account,invoiceId,refundId,idempotencyFingerprint(params))});return validateIssued(credit)}
1
+ import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{allPages}from"./pagination";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:String(value?.id||"")}export async function creditDirectInvoiceRefund(invoiceId,account,refundId,lines,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^re_[a-z0-9_]+$/i.test(refundId)||!lines.length||lines.length>100||lines.some((line)=>!/^il_[a-z0-9_]+$/i.test(line.invoiceLineItem)||!Number.isSafeInteger(line.amount)||line.amount<=0)||new Set(lines.map((line)=>line.invoiceLineItem)).size!==lines.length)throw new Error("[payments/connect] Expected original invoice, refund and unique positive credit lines");const invoice=await client.invoices.retrieve(invoiceId,{},request);const refund=await client.refunds.retrieve(refundId,{},request);if(invoice.id!==invoiceId||invoice.status!=="paid"||refund.id!==refundId||refund.status!=="succeeded"||refund.currency!==invoice.currency||!Number.isSafeInteger(refund.amount)||refund.amount<=0||!id(refund.payment_intent))throw new Error("[payments/connect] Expected the original paid invoice and successful refund in its currency");const payments=await allPages((after)=>client.invoicePayments.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request));if(!payments.some((payment)=>payment.status==="paid"&&id(payment.payment.payment_intent)===id(refund.payment_intent)))throw new Error("[payments/connect] Refund belongs to another invoice payment");const invoiceLines=await allPages((after)=>client.invoices.listLineItems(invoiceId,{limit:100,...after?{starting_after:after}:{}},request));if(lines.some((line)=>!invoiceLines.some((original)=>original.id===line.invoiceLineItem)))throw new Error("[payments/connect] Credit line belongs to another invoice");const params={invoice:invoiceId,lines:[...lines].sort((a,b)=>a.invoiceLineItem.localeCompare(b.invoiceLineItem)).map((line)=>({type:"invoice_line_item",invoice_line_item:line.invoiceLineItem,amount:line.amount})),refunds:[{refund:refundId,amount_refunded:refund.amount}]};const verify=(credit)=>{if(id(credit.invoice)!==invoiceId||id(credit.customer)!==id(invoice.customer)||credit.currency!==invoice.currency||credit.total!==refund.amount)throw new Error("[payments/connect] Credit does not match the original invoice or refund amount");return{creditNote:credit,...invoiceTaxAmounts(credit),currency:invoice.currency.toUpperCase()}};const validateIssued=async(credit)=>{const result=verify(credit);if(credit.status!=="issued"||credit.refunds.length!==1||id(credit.refunds[0].refund)!==refundId||credit.refunds[0].amount_refunded!==refund.amount)throw new Error("[payments/connect] Credit does not bind the complete original refund");const actual=await allPages((after)=>client.creditNotes.listLineItems(credit.id,{limit:100,...after?{starting_after:after}:{}},request));if(actual.length!==lines.length||actual.some((line)=>line.type!=="invoice_line_item"||!lines.some((expected)=>expected.invoiceLineItem===line.invoice_line_item&&expected.amount===line.amount)))throw new Error("[payments/connect] Refund was credited with different invoice lines");return result};const credits=await allPages((after)=>client.creditNotes.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request));const previous=credits.filter((credit)=>credit.status==="issued"&&credit.refunds.some((row)=>id(row.refund)===refundId));if(previous.length>1)throw new Error("[payments/connect] Refund is associated with several credit notes");if(previous[0])return validateIssued(previous[0]);verify(await client.creditNotes.preview(params,request));const credit=await client.creditNotes.create({...params,email_type:"none"},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.refund-credit",account,invoiceId,refundId,idempotencyFingerprint(params))});return validateIssued(credit)}
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{splitFee}from"./destination";import{manageDestinationSubscription}from"./subscription";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:value?.id}function amounts(invoice){const totals=invoiceTaxAmounts(invoice);if(invoice.amount_due!==totals.gross)throw Error("[payments/connect] Invoice credits or balance adjustments require a separate fee settlement");return totals}export async function prepareDirectInvoiceFee(invoiceId,account,options,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^cus_[a-z0-9_]+$/i.test(options.customer)||options.subscription!=null&&!/^sub_[a-z0-9_]+$/i.test(options.subscription)||!/^[a-z]{3}$/i.test(options.currency))throw Error("[payments/connect] Expected original invoice, customer, subscription and currency");if(options.platformFeePercent==null)throw Error("[payments/connect] An explicit invoice fee percentage is required");manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});const invoice=await client.invoices.retrieve(invoiceId,{},request),verify=(value)=>{if(value.id!==invoiceId||value.status!=="draft"||id(value.customer)!==options.customer||id(value.parent?.subscription_details?.subscription)!==options.subscription||value.currency.toUpperCase()!==options.currency.toUpperCase())throw Error("[payments/connect] Fee requires the original draft invoice, customer, subscription and currency");return amounts(value)},basis=verify(invoice),feeBps=Math.round(options.platformFeePercent*100),fee=splitFee(basis.net,{platform:feeBps,merchant:1e4-feeBps},"merchant").platform,updated=await client.invoices.update(invoiceId,{auto_advance:!1,application_fee_amount:fee},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.tax-fee",account,invoiceId,basis.gross,basis.tax,fee)}),current=verify(updated);if(current.gross!==basis.gross||current.tax!==basis.tax)throw Error("[payments/connect] Invoice tax or amount changed while preparing the fee; collection remains held");return{invoice:updated,currency:invoice.currency.toUpperCase(),...basis,fee}}
1
+ import{stripe}from"../drivers/stripe";import{stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{splitFee}from"./destination";import{manageDestinationSubscription}from"./subscription";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:value?.id}function amounts(invoice){const totals=invoiceTaxAmounts(invoice);if(invoice.amount_due!==totals.gross)throw new Error("[payments/connect] Invoice credits or balance adjustments require a separate fee settlement");return totals}export async function prepareDirectInvoiceFee(invoiceId,account,options,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^cus_[a-z0-9_]+$/i.test(options.customer)||options.subscription!=null&&!/^sub_[a-z0-9_]+$/i.test(options.subscription)||!/^[a-z]{3}$/i.test(options.currency))throw new Error("[payments/connect] Expected original invoice, customer, subscription and currency");if(options.platformFeePercent==null)throw new Error("[payments/connect] An explicit invoice fee percentage is required");manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});const invoice=await client.invoices.retrieve(invoiceId,{},request);const verify=(value)=>{if(value.id!==invoiceId||value.status!=="draft"||id(value.customer)!==options.customer||id(value.parent?.subscription_details?.subscription)!==options.subscription||value.currency.toUpperCase()!==options.currency.toUpperCase())throw new Error("[payments/connect] Fee requires the original draft invoice, customer, subscription and currency");return amounts(value)};const basis=verify(invoice);const feeBps=Math.round(options.platformFeePercent*100);const fee=splitFee(basis.net,{platform:feeBps,merchant:1e4-feeBps},"merchant").platform;const updated=await client.invoices.update(invoiceId,{auto_advance:false,application_fee_amount:fee},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.tax-fee",account,invoiceId,basis.gross,basis.tax,fee)});const current=verify(updated);if(current.gross!==basis.gross||current.tax!==basis.tax)throw new Error("[payments/connect] Invoice tax or amount changed while preparing the fee; collection remains held");return{invoice:updated,currency:invoice.currency.toUpperCase(),...basis,fee}}
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";export async function ensureDirectInvoicePrice(account,options,client=stripe){const request=asAccount(account);if(typeof options.reference!=="string"||!/^[a-z0-9:._-]{1,160}$/i.test(options.reference)||typeof options.name!=="string"||!options.name.trim()||options.name.length>250||!Number.isSafeInteger(options.amount)||options.amount<=0||!/^[a-z]{3}$/i.test(options.currency)||!/^txcd_\d{8}$/.test(options.taxCode)||options.interval!==void 0&&!["day","week","month","year"].includes(options.interval)||options.intervalCount!==void 0&&(!options.interval||!Number.isSafeInteger(options.intervalCount)||options.intervalCount<1))throw Error("[payments/connect] Expected stable offer identity, name, positive minor-unit price, currency and merchant tax code");const terms={reference:options.reference,name:options.name.trim(),amount:options.amount,currency:options.currency.toLowerCase(),taxCode:options.taxCode,interval:options.interval??null,intervalCount:options.interval?options.intervalCount??1:null},fingerprint=idempotencyFingerprint(terms),lookup=`stacks.invoice-price.${fingerprint}`,listed=await client.prices.list({lookup_keys:[lookup],limit:100},request);if(listed.has_more||listed.data.length>1)throw Error("[payments/connect] Merchant invoice price lookup is ambiguous");const price=listed.data[0]??await client.prices.create({currency:terms.currency,unit_amount:terms.amount,tax_behavior:"inclusive",lookup_key:lookup,metadata:{stacks_invoice_price:fingerprint,stacks_offer_reference:terms.reference},product_data:{name:terms.name,tax_code:terms.taxCode,metadata:{stacks_invoice_price:fingerprint,stacks_offer_reference:terms.reference}},...options.interval?{recurring:{interval:options.interval,interval_count:options.intervalCount??1}}:{}},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.price",account,fingerprint)});if(!/^price_[a-z0-9_]+$/i.test(price.id))throw Error("[payments/connect] Provider returned no catalog price identity");const current=await client.prices.retrieve(price.id,{expand:["product"]},request),{product,recurring}=current;if(current.id!==price.id||!current.active||current.lookup_key!==lookup||current.metadata?.stacks_invoice_price!==fingerprint||current.currency!==terms.currency||current.unit_amount!==terms.amount||current.tax_behavior!=="inclusive"||current.type!==(terms.interval?"recurring":"one_time")||(terms.interval?!recurring||recurring.interval!==terms.interval||recurring.interval_count!==terms.intervalCount||recurring.usage_type!=="licensed":recurring!=null)||typeof product==="string"||product.deleted||!product.active||product.name!==terms.name||(typeof product.tax_code==="string"?product.tax_code:product.tax_code?.id)!==terms.taxCode)throw Error("[payments/connect] Existing merchant price differs from the frozen inclusive offer or is inactive");return current}
1
+ import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";export async function ensureDirectInvoicePrice(account,options,client=stripe){const request=asAccount(account);if(typeof options.reference!=="string"||!/^[a-z0-9:._-]{1,160}$/i.test(options.reference)||typeof options.name!=="string"||!options.name.trim()||options.name.length>250||!Number.isSafeInteger(options.amount)||options.amount<=0||!/^[a-z]{3}$/i.test(options.currency)||!/^txcd_\d{8}$/.test(options.taxCode)||options.interval!==undefined&&!["day","week","month","year"].includes(options.interval)||options.intervalCount!==undefined&&(!options.interval||!Number.isSafeInteger(options.intervalCount)||options.intervalCount<1))throw new Error("[payments/connect] Expected stable offer identity, name, positive minor-unit price, currency and merchant tax code");const terms={reference:options.reference,name:options.name.trim(),amount:options.amount,currency:options.currency.toLowerCase(),taxCode:options.taxCode,interval:options.interval??null,intervalCount:options.interval?options.intervalCount??1:null};const fingerprint=idempotencyFingerprint(terms);const lookup=`stacks.invoice-price.${fingerprint}`;const listed=await client.prices.list({lookup_keys:[lookup],limit:100},request);if(listed.has_more||listed.data.length>1)throw new Error("[payments/connect] Merchant invoice price lookup is ambiguous");const previous=listed.data[0];const price=previous??await client.prices.create({currency:terms.currency,unit_amount:terms.amount,tax_behavior:"inclusive",lookup_key:lookup,metadata:{stacks_invoice_price:fingerprint,stacks_offer_reference:terms.reference},product_data:{name:terms.name,tax_code:terms.taxCode,metadata:{stacks_invoice_price:fingerprint,stacks_offer_reference:terms.reference}},...options.interval?{recurring:{interval:options.interval,interval_count:options.intervalCount??1}}:{}},{...request,idempotencyKey:stacksIdempotencyKey("connect.invoice.price",account,fingerprint)});if(!/^price_[a-z0-9_]+$/i.test(price.id))throw new Error("[payments/connect] Provider returned no catalog price identity");const current=await client.prices.retrieve(price.id,{expand:["product"]},request);const product=current.product;const recurring=current.recurring;if(current.id!==price.id||!current.active||current.lookup_key!==lookup||current.metadata?.stacks_invoice_price!==fingerprint||current.currency!==terms.currency||current.unit_amount!==terms.amount||current.tax_behavior!=="inclusive"||current.type!==(terms.interval?"recurring":"one_time")||(terms.interval?!recurring||recurring.interval!==terms.interval||recurring.interval_count!==terms.intervalCount||recurring.usage_type!=="licensed":recurring!=null)||typeof product==="string"||product.deleted||!product.active||product.name!==terms.name||(typeof product.tax_code==="string"?product.tax_code:product.tax_code?.id)!==terms.taxCode)throw new Error("[payments/connect] Existing merchant price differs from the frozen inclusive offer or is inactive");return current}
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{collectDirectInvoice}from"./invoice-collection";import{allPages}from"./pagination";import{manageDestinationSubscription}from"./subscription";export class DirectInvoicePurchaseExpiredError extends Error{}export function directInvoicePurchaseMetadata(account,options){asAccount(account);if(typeof options.reference!=="string"||!/^[a-z0-9:._-]{1,160}$/i.test(options.reference)||!/^cus_[a-z0-9_]+$/i.test(options.customer)||!/^price_[a-z0-9_]+$/i.test(options.price)||!Number.isSafeInteger(options.expiresAt)||options.expiresAt<=0||!Number.isSafeInteger(options.amount)||options.amount<=0||!/^[a-z]{3}$/i.test(options.currency)||!/^txcd_\d{8}$/.test(options.taxCode)||options.interval!==void 0&&!["day","week","month","year"].includes(options.interval)||options.intervalCount!==void 0&&(!options.interval||!Number.isSafeInteger(options.intervalCount)||options.intervalCount<1)||options.trialDays!==void 0&&(!Number.isSafeInteger(options.trialDays)||options.trialDays<0||options.trialDays>730||!options.interval&&options.trialDays>0))throw Error("[payments/connect] Expected original customer, price and frozen invoice purchase terms");if(options.platformFeePercent==null)throw Error("[payments/connect] An explicit invoice fee percentage is required");manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});const metadata=options.metadata??{};if(typeof metadata!=="object"||Array.isArray(metadata)||Object.keys(metadata).length>47||Object.entries(metadata).some(([key,value])=>!key||key.length>40||/[\[\]]/.test(key)||key.startsWith("stacks_purchase_")||typeof value!=="string"||value.length>500))throw Error("[payments/connect] Invalid purchase metadata or reserved binding fields");const terms={account,reference:options.reference,customer:options.customer,price:options.price,amount:options.amount,currency:options.currency.toLowerCase(),taxCode:options.taxCode,expiresAt:options.expiresAt,interval:options.interval??null,intervalCount:options.interval?options.intervalCount??1:null,trialDays:options.trialDays??0,platformFeePercent:options.platformFeePercent,metadata};return{...metadata,stacks_purchase_reference:options.reference,stacks_purchase_quote:idempotencyFingerprint(terms)}}function id(value){return typeof value==="string"?value:value?.id}export async function completeDirectInvoicePurchase(setupIntentId,account,options,client=stripe){const quote=directInvoicePurchaseMetadata(account,options),request=asAccount(account);if(!/^seti_[a-z0-9_]+$/i.test(setupIntentId))throw Error("[payments/connect] Expected original successful payment setup");const setup=await client.setupIntents.retrieve(setupIntentId,{},request),matches=(metadata,expected)=>Object.entries(expected).every(([key,value])=>metadata?.[key]===value);if(setup.id!==setupIntentId||setup.status!=="succeeded"||setup.usage!=="off_session"||!Number.isSafeInteger(setup.created)||setup.created<=0||id(setup.customer)!==options.customer||!/^pm_[a-z0-9_]+$/i.test(id(setup.payment_method)||"")||!matches(setup.metadata,quote))throw Error("[payments/connect] Payment setup does not match the original customer and frozen quote");const paymentMethod=id(setup.payment_method),metadata={...quote,stacks_purchase_setup:setupIntentId},key=(operation)=>stacksIdempotencyKey(`connect.invoice.purchase.${operation}`,account,options.reference,quote.stacks_purchase_quote),canCreate=(rows)=>{if(Date.now()/1000>=Math.min(options.expiresAt,setup.created+86400)){if(rows.some((row)=>!row.metadata?.stacks_purchase_reference||!row.metadata.stacks_purchase_quote||!row.metadata.stacks_purchase_setup||row.metadata.stacks_purchase_setup===setupIntentId))throw Error("[payments/connect] Expired purchase requires review of unbound original-customer resources");throw new DirectInvoicePurchaseExpiredError("[payments/connect] Expired purchase can only recover its original provider invoice or schedule")}},existing=(rows)=>{const own=rows.filter((row)=>row.metadata?.stacks_purchase_reference===options.reference);if(own.length>1||own.some((row)=>!matches(row.metadata,metadata)))throw Error("[payments/connect] Purchase reference has ambiguous or different provider bindings");return own[0]},verifyPrice=async()=>{const price=await client.prices.retrieve(options.price,{expand:["product"]},request),product=price.product;if(price.id!==options.price||!price.active||price.currency!==options.currency.toLowerCase()||price.unit_amount!==options.amount||price.tax_behavior!=="inclusive"||price.type!==(options.interval?"recurring":"one_time")||(options.interval?price.recurring?.interval!==options.interval||price.recurring?.interval_count!==(options.intervalCount??1)||price.recurring?.usage_type!=="licensed":price.recurring!=null)||typeof product==="string"||product.deleted||!product.active||id(product.tax_code)!==options.taxCode)throw Error("[payments/connect] Catalog price does not match the approved inclusive purchase");const method=await client.paymentMethods.retrieve(paymentMethod,{},request);if(method.id!==paymentMethod||id(method.customer)!==options.customer)throw Error("[payments/connect] Purchase payment method belongs to another customer")};let invoice,subscription,reloadSubscription;if(options.interval){const schedules=await allPages((after)=>client.subscriptionSchedules.list({customer:options.customer,limit:100,...after?{starting_after:after}:{}},request));let schedule=existing(schedules);if(!schedule){canCreate(schedules);await verifyPrice();const phase={items:[{price:options.price,quantity:1}],automatic_tax:{enabled:!0},metadata};schedule=await client.subscriptionSchedules.create({customer:options.customer,start_date:"now",end_behavior:"release",default_settings:{default_payment_method:paymentMethod},phases:options.trialDays?[{...phase,trial:!0,duration:{interval:"day",interval_count:options.trialDays}},phase]:[phase],metadata},{...request,idempotencyKey:key("schedule")})}const subscriptionId=id(schedule.subscription)??id(schedule.released_subscription);if(!/^sub_sched_[a-z0-9_]+$/i.test(schedule.id)||id(schedule.customer)!==options.customer||!matches(schedule.metadata,metadata)||!/^sub_[a-z0-9_]+$/i.test(subscriptionId||""))throw Error("[payments/connect] Purchase schedule has no original customer and subscription");const readSubscription=async()=>{const value=await client.subscriptions.retrieve(subscriptionId,{},request);if(value.id!==subscriptionId||id(value.customer)!==options.customer||!matches(value.metadata,metadata)||value.items.has_more||value.items.data.length!==1||id(value.items.data[0].price)!==options.price||value.items.data[0].quantity!==1)throw Error("[payments/connect] Subscription does not match the original frozen purchase");return value};reloadSubscription=readSubscription;subscription=await readSubscription();const initial=(await allPages((after)=>client.invoices.list({customer:options.customer,subscription:subscriptionId,limit:100,...after?{starting_after:after}:{}},request))).filter((value)=>value.billing_reason==="subscription_create"&&id(value.parent?.subscription_details?.subscription)===subscriptionId);if(initial.length!==1)throw Error("[payments/connect] Purchase has no unique original subscription invoice");invoice=await client.invoices.retrieve(initial[0].id,{},request);if(invoice.id!==initial[0].id||id(invoice.customer)!==options.customer||id(invoice.parent?.subscription_details?.subscription)!==subscriptionId||!matches(invoice.parent?.subscription_details?.metadata,metadata))throw Error("[payments/connect] First invoice does not match the original subscription quote");if(invoice.status!=="paid"&&["canceled","incomplete_expired","unpaid"].includes(subscription.status))throw Error("[payments/connect] Subscription no longer permits its initial collection");if(invoice.status==="draft"&&invoice.auto_advance!==!1){invoice=await client.invoices.update(invoice.id,{auto_advance:!1},{...request,idempotencyKey:key("hold")});if(invoice.id!==initial[0].id||id(invoice.customer)!==options.customer||id(invoice.parent?.subscription_details?.subscription)!==subscriptionId||!matches(invoice.parent?.subscription_details?.metadata,metadata))throw Error("[payments/connect] Held invoice no longer matches the original subscription")}if(schedule.status==="active"){if(id(subscription.schedule)!==schedule.id)throw Error("[payments/connect] Subscription belongs to another schedule");const trialEnd=subscription.trial_end,released=await client.subscriptionSchedules.release(schedule.id,{},{...request,idempotencyKey:key("release")});if(released.id!==schedule.id||released.status!=="released"||id(released.released_subscription)!==subscriptionId)throw Error("[payments/connect] Schedule release did not preserve its original subscription");subscription=await readSubscription();if(subscription.schedule!=null||subscription.trial_end!==trialEnd)throw Error("[payments/connect] Released purchase changed its schedule or native trial");if(invoice.status!=="paid"&&["canceled","incomplete_expired","unpaid"].includes(subscription.status))throw Error("[payments/connect] Subscription no longer permits its initial collection")}else if(!["released","completed","canceled"].includes(schedule.status))throw Error("[payments/connect] Purchase schedule has not started")}else{const invoices=await allPages((after)=>client.invoices.list({customer:options.customer,limit:100,...after?{starting_after:after}:{}},request)),previous=existing(invoices);if(previous)invoice=await client.invoices.retrieve(previous.id,{},request);else{canCreate(invoices);await verifyPrice();invoice=await client.invoices.create({customer:options.customer,currency:options.currency.toLowerCase(),auto_advance:!1,automatic_tax:{enabled:!0},default_payment_method:paymentMethod,pending_invoice_items_behavior:"exclude",metadata},{...request,idempotencyKey:key("create")})}if(!/^in_[a-z0-9_]+$/i.test(invoice.id)||previous&&invoice.id!==previous.id||id(invoice.customer)!==options.customer||!matches(invoice.metadata,metadata))throw Error("[payments/connect] Purchase invoice belongs to another customer or quote");let lines=await allPages((after)=>client.invoices.listLineItems(invoice.id,{limit:100,...after?{starting_after:after}:{}},request));if(lines.length===0&&invoice.status==="draft"){if(previous)await verifyPrice();await client.invoiceItems.create({customer:options.customer,invoice:invoice.id,pricing:{price:options.price},quantity:1},{...request,idempotencyKey:key("line")});lines=await allPages((after)=>client.invoices.listLineItems(invoice.id,{limit:100,...after?{starting_after:after}:{}},request))}if(lines.length!==1||lines[0].quantity!==1||id(lines[0].pricing?.price_details?.price)!==options.price)throw Error("[payments/connect] Purchase invoice contains different catalog lines")}if(!invoice.automatic_tax.enabled)throw Error("[payments/connect] Purchase invoice no longer uses its original automatic tax policy");return{...await collectDirectInvoice(invoice.id,account,{customer:options.customer,...subscription?{subscription:subscription.id}:{},currency:options.currency,platformFeePercent:options.platformFeePercent,approvedTotal:options.trialDays?0:options.amount,paymentMethod},client),...reloadSubscription?{subscription:await reloadSubscription()}:{}}}
1
+ import{stripe}from"../drivers/stripe";import{idempotencyFingerprint,stacksIdempotencyKey}from"../idempotency";import{asAccount}from"./direct";import{collectDirectInvoice}from"./invoice-collection";import{allPages}from"./pagination";import{manageDestinationSubscription}from"./subscription";export class DirectInvoicePurchaseExpiredError extends Error{}export function directInvoicePurchaseMetadata(account,options){asAccount(account);if(typeof options.reference!=="string"||!/^[a-z0-9:._-]{1,160}$/i.test(options.reference)||!/^cus_[a-z0-9_]+$/i.test(options.customer)||!/^price_[a-z0-9_]+$/i.test(options.price)||!Number.isSafeInteger(options.expiresAt)||options.expiresAt<=0||!Number.isSafeInteger(options.amount)||options.amount<=0||!/^[a-z]{3}$/i.test(options.currency)||!/^txcd_\d{8}$/.test(options.taxCode)||options.interval!==undefined&&!["day","week","month","year"].includes(options.interval)||options.intervalCount!==undefined&&(!options.interval||!Number.isSafeInteger(options.intervalCount)||options.intervalCount<1)||options.trialDays!==undefined&&(!Number.isSafeInteger(options.trialDays)||options.trialDays<0||options.trialDays>730||!options.interval&&options.trialDays>0))throw new Error("[payments/connect] Expected original customer, price and frozen invoice purchase terms");if(options.platformFeePercent==null)throw new Error("[payments/connect] An explicit invoice fee percentage is required");manageDestinationSubscription.feePercentFor({platformFeePercent:options.platformFeePercent});const metadata=options.metadata??{};if(typeof metadata!=="object"||Array.isArray(metadata)||Object.keys(metadata).length>47||Object.entries(metadata).some(([key,value])=>!key||key.length>40||/[\[\]]/.test(key)||key.startsWith("stacks_purchase_")||typeof value!=="string"||value.length>500))throw new Error("[payments/connect] Invalid purchase metadata or reserved binding fields");const terms={account,reference:options.reference,customer:options.customer,price:options.price,amount:options.amount,currency:options.currency.toLowerCase(),taxCode:options.taxCode,expiresAt:options.expiresAt,interval:options.interval??null,intervalCount:options.interval?options.intervalCount??1:null,trialDays:options.trialDays??0,platformFeePercent:options.platformFeePercent,metadata};return{...metadata,stacks_purchase_reference:options.reference,stacks_purchase_quote:idempotencyFingerprint(terms)}}function id(value){return typeof value==="string"?value:value?.id}export async function completeDirectInvoicePurchase(setupIntentId,account,options,client=stripe){const quote=directInvoicePurchaseMetadata(account,options);const request=asAccount(account);if(!/^seti_[a-z0-9_]+$/i.test(setupIntentId))throw new Error("[payments/connect] Expected original successful payment setup");const setup=await client.setupIntents.retrieve(setupIntentId,{},request);const matches=(metadata,expected)=>Object.entries(expected).every(([key,value])=>metadata?.[key]===value);if(setup.id!==setupIntentId||setup.status!=="succeeded"||setup.usage!=="off_session"||!Number.isSafeInteger(setup.created)||setup.created<=0||id(setup.customer)!==options.customer||!/^pm_[a-z0-9_]+$/i.test(id(setup.payment_method)||"")||!matches(setup.metadata,quote))throw new Error("[payments/connect] Payment setup does not match the original customer and frozen quote");const paymentMethod=id(setup.payment_method);const metadata={...quote,stacks_purchase_setup:setupIntentId};const key=(operation)=>stacksIdempotencyKey(`connect.invoice.purchase.${operation}`,account,options.reference,quote.stacks_purchase_quote);const canCreate=(rows)=>{if(Date.now()/1000>=Math.min(options.expiresAt,setup.created+24*60*60)){if(rows.some((row)=>!row.metadata?.stacks_purchase_reference||!row.metadata.stacks_purchase_quote||!row.metadata.stacks_purchase_setup||row.metadata.stacks_purchase_setup===setupIntentId))throw new Error("[payments/connect] Expired purchase requires review of unbound original-customer resources");throw new DirectInvoicePurchaseExpiredError("[payments/connect] Expired purchase can only recover its original provider invoice or schedule")}};const existing=(rows)=>{const own=rows.filter((row)=>row.metadata?.stacks_purchase_reference===options.reference);if(own.length>1||own.some((row)=>!matches(row.metadata,metadata)))throw new Error("[payments/connect] Purchase reference has ambiguous or different provider bindings");return own[0]};const verifyPrice=async()=>{const price=await client.prices.retrieve(options.price,{expand:["product"]},request);const product=price.product;if(price.id!==options.price||!price.active||price.currency!==options.currency.toLowerCase()||price.unit_amount!==options.amount||price.tax_behavior!=="inclusive"||price.type!==(options.interval?"recurring":"one_time")||(options.interval?price.recurring?.interval!==options.interval||price.recurring?.interval_count!==(options.intervalCount??1)||price.recurring?.usage_type!=="licensed":price.recurring!=null)||typeof product==="string"||product.deleted||!product.active||id(product.tax_code)!==options.taxCode)throw new Error("[payments/connect] Catalog price does not match the approved inclusive purchase");const method=await client.paymentMethods.retrieve(paymentMethod,{},request);if(method.id!==paymentMethod||id(method.customer)!==options.customer)throw new Error("[payments/connect] Purchase payment method belongs to another customer")};let invoice;let subscription;let reloadSubscription;if(options.interval){const schedules=await allPages((after)=>client.subscriptionSchedules.list({customer:options.customer,limit:100,...after?{starting_after:after}:{}},request));let schedule=existing(schedules);if(!schedule){canCreate(schedules);await verifyPrice();const phase={items:[{price:options.price,quantity:1}],automatic_tax:{enabled:true},metadata};schedule=await client.subscriptionSchedules.create({customer:options.customer,start_date:"now",end_behavior:"release",default_settings:{default_payment_method:paymentMethod},phases:options.trialDays?[{...phase,trial:true,duration:{interval:"day",interval_count:options.trialDays}},phase]:[phase],metadata},{...request,idempotencyKey:key("schedule")})}const subscriptionId=id(schedule.subscription)??id(schedule.released_subscription);if(!/^sub_sched_[a-z0-9_]+$/i.test(schedule.id)||id(schedule.customer)!==options.customer||!matches(schedule.metadata,metadata)||!/^sub_[a-z0-9_]+$/i.test(subscriptionId||""))throw new Error("[payments/connect] Purchase schedule has no original customer and subscription");const readSubscription=async()=>{const value=await client.subscriptions.retrieve(subscriptionId,{},request);if(value.id!==subscriptionId||id(value.customer)!==options.customer||!matches(value.metadata,metadata)||value.items.has_more||value.items.data.length!==1||id(value.items.data[0].price)!==options.price||value.items.data[0].quantity!==1)throw new Error("[payments/connect] Subscription does not match the original frozen purchase");return value};reloadSubscription=readSubscription;subscription=await readSubscription();const invoices=await allPages((after)=>client.invoices.list({customer:options.customer,subscription:subscriptionId,limit:100,...after?{starting_after:after}:{}},request));const initial=invoices.filter((value)=>value.billing_reason==="subscription_create"&&id(value.parent?.subscription_details?.subscription)===subscriptionId);if(initial.length!==1)throw new Error("[payments/connect] Purchase has no unique original subscription invoice");invoice=await client.invoices.retrieve(initial[0].id,{},request);if(invoice.id!==initial[0].id||id(invoice.customer)!==options.customer||id(invoice.parent?.subscription_details?.subscription)!==subscriptionId||!matches(invoice.parent?.subscription_details?.metadata,metadata))throw new Error("[payments/connect] First invoice does not match the original subscription quote");if(invoice.status!=="paid"&&["canceled","incomplete_expired","unpaid"].includes(subscription.status))throw new Error("[payments/connect] Subscription no longer permits its initial collection");if(invoice.status==="draft"&&invoice.auto_advance!==false){invoice=await client.invoices.update(invoice.id,{auto_advance:false},{...request,idempotencyKey:key("hold")});if(invoice.id!==initial[0].id||id(invoice.customer)!==options.customer||id(invoice.parent?.subscription_details?.subscription)!==subscriptionId||!matches(invoice.parent?.subscription_details?.metadata,metadata))throw new Error("[payments/connect] Held invoice no longer matches the original subscription")}if(schedule.status==="active"){if(id(subscription.schedule)!==schedule.id)throw new Error("[payments/connect] Subscription belongs to another schedule");const trialEnd=subscription.trial_end;const released=await client.subscriptionSchedules.release(schedule.id,{},{...request,idempotencyKey:key("release")});if(released.id!==schedule.id||released.status!=="released"||id(released.released_subscription)!==subscriptionId)throw new Error("[payments/connect] Schedule release did not preserve its original subscription");subscription=await readSubscription();if(subscription.schedule!=null||subscription.trial_end!==trialEnd)throw new Error("[payments/connect] Released purchase changed its schedule or native trial");if(invoice.status!=="paid"&&["canceled","incomplete_expired","unpaid"].includes(subscription.status))throw new Error("[payments/connect] Subscription no longer permits its initial collection")}else if(!["released","completed","canceled"].includes(schedule.status)){throw new Error("[payments/connect] Purchase schedule has not started")}}else{const invoices=await allPages((after)=>client.invoices.list({customer:options.customer,limit:100,...after?{starting_after:after}:{}},request));const previous=existing(invoices);if(previous)invoice=await client.invoices.retrieve(previous.id,{},request);else{canCreate(invoices);await verifyPrice();invoice=await client.invoices.create({customer:options.customer,currency:options.currency.toLowerCase(),auto_advance:false,automatic_tax:{enabled:true},default_payment_method:paymentMethod,pending_invoice_items_behavior:"exclude",metadata},{...request,idempotencyKey:key("create")})}if(!/^in_[a-z0-9_]+$/i.test(invoice.id)||previous&&invoice.id!==previous.id||id(invoice.customer)!==options.customer||!matches(invoice.metadata,metadata))throw new Error("[payments/connect] Purchase invoice belongs to another customer or quote");let lines=await allPages((after)=>client.invoices.listLineItems(invoice.id,{limit:100,...after?{starting_after:after}:{}},request));if(lines.length===0&&invoice.status==="draft"){if(previous)await verifyPrice();await client.invoiceItems.create({customer:options.customer,invoice:invoice.id,pricing:{price:options.price},quantity:1},{...request,idempotencyKey:key("line")});lines=await allPages((after)=>client.invoices.listLineItems(invoice.id,{limit:100,...after?{starting_after:after}:{}},request))}if(lines.length!==1||lines[0].quantity!==1||id(lines[0].pricing?.price_details?.price)!==options.price)throw new Error("[payments/connect] Purchase invoice contains different catalog lines")}if(!invoice.automatic_tax.enabled)throw new Error("[payments/connect] Purchase invoice no longer uses its original automatic tax policy");const collected=await collectDirectInvoice(invoice.id,account,{customer:options.customer,...subscription?{subscription:subscription.id}:{},currency:options.currency,platformFeePercent:options.platformFeePercent,approvedTotal:options.trialDays?0:options.amount,paymentMethod},client);return{...collected,...reloadSubscription?{subscription:await reloadSubscription()}:{}}}
@@ -1 +1 @@
1
- import{stripe}from"../drivers/stripe";import{asAccount}from"./direct";import{allPages}from"./pagination";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:String(value?.id||"")}export async function directInvoiceTaxFinancials(invoiceId,paymentIntentId,account,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^pi_[a-z0-9_]+$/i.test(paymentIntentId))throw Error("[payments/connect] Expected original invoice and payment identities");const invoice=await client.invoices.retrieve(invoiceId,{},request);if(invoice.id!==invoiceId||invoice.status!=="paid")throw Error("[payments/connect] Expected the original paid invoice");const basis=invoiceTaxAmounts(invoice);if(!(await allPages((after)=>client.invoicePayments.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request))).some((payment)=>payment.status==="paid"&&id(payment.payment.payment_intent)===paymentIntentId))throw Error("[payments/connect] Invoice belongs to another payment");const refunds=await allPages((after)=>client.refunds.list({payment_intent:paymentIntentId,limit:100,...after?{starting_after:after}:{}},request));if(refunds.some((refund)=>id(refund.payment_intent)!==paymentIntentId||refund.currency!==invoice.currency||!Number.isSafeInteger(refund.amount)||refund.amount<=0))throw Error("[payments/connect] Foreign or invalid invoice refund");const creditNotes=await allPages((after)=>client.creditNotes.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request)),invoiceLines=await allPages((after)=>client.invoices.listLineItems(invoiceId,{limit:100,...after?{starting_after:after}:{}},request));let requiresReview=refunds.some((refund)=>!["succeeded","failed","canceled"].includes(String(refund.status))),creditedGross=0,creditedNet=0,creditedTax=0;const creditedRefunds=new Map;for(const credit of creditNotes){if(id(credit.invoice)!==invoiceId||id(credit.customer)!==id(invoice.customer)||credit.currency!==invoice.currency)throw Error("[payments/connect] Foreign invoice tax credit");if(credit.status==="void")continue;if(credit.status!=="issued")throw Error("[payments/connect] Unknown invoice credit status");const amounts=invoiceTaxAmounts(credit),lines=await allPages((after)=>client.creditNotes.listLineItems(credit.id,{limit:100,...after?{starting_after:after}:{}},request));if(!lines.length||lines.some((line)=>line.type!=="invoice_line_item"))requiresReview=!0;if(lines.some((line)=>line.type==="invoice_line_item"&&!invoiceLines.some((original)=>original.id===line.invoice_line_item)))throw Error("[payments/connect] Tax credit references another invoice line");creditedGross+=amounts.gross;creditedNet+=amounts.net;creditedTax+=amounts.tax;let linkedGross=0;for(const link of credit.refunds){const refund=refunds.find((row)=>row.id===id(link.refund));if(!refund||refund.status!=="succeeded"||!Number.isSafeInteger(link.amount_refunded)||link.amount_refunded<0){requiresReview=!0;continue}const credited=(creditedRefunds.get(refund.id)||0)+link.amount_refunded;creditedRefunds.set(refund.id,credited);if(credited>refund.amount)throw Error("[payments/connect] Tax credits exceed the original refund");linkedGross+=link.amount_refunded}if(linkedGross!==amounts.gross)requiresReview=!0}const refunded=refunds.filter((refund)=>refund.status==="succeeded").reduce((sum,refund)=>sum+refund.amount,0);if(creditedGross>basis.gross||creditedNet>basis.net||creditedTax>basis.tax||basis.tax>0&&(creditedGross!==refunded||refunds.some((refund)=>refund.status==="succeeded"&&creditedRefunds.get(refund.id)!==refund.amount)))requiresReview=!0;return{invoice,creditNotes,currency:invoice.currency.toUpperCase(),...basis,creditedGross,creditedNet,creditedTax,requiresReview}}
1
+ import{stripe}from"../drivers/stripe";import{asAccount}from"./direct";import{allPages}from"./pagination";import{invoiceTaxAmounts}from"./tax";function id(value){return typeof value==="string"?value:String(value?.id||"")}export async function directInvoiceTaxFinancials(invoiceId,paymentIntentId,account,client=stripe){const request=asAccount(account);if(!/^in_[a-z0-9_]+$/i.test(invoiceId)||!/^pi_[a-z0-9_]+$/i.test(paymentIntentId))throw new Error("[payments/connect] Expected original invoice and payment identities");const invoice=await client.invoices.retrieve(invoiceId,{},request);if(invoice.id!==invoiceId||invoice.status!=="paid")throw new Error("[payments/connect] Expected the original paid invoice");const basis=invoiceTaxAmounts(invoice);const payments=await allPages((after)=>client.invoicePayments.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request));if(!payments.some((payment)=>payment.status==="paid"&&id(payment.payment.payment_intent)===paymentIntentId))throw new Error("[payments/connect] Invoice belongs to another payment");const refunds=await allPages((after)=>client.refunds.list({payment_intent:paymentIntentId,limit:100,...after?{starting_after:after}:{}},request));if(refunds.some((refund)=>id(refund.payment_intent)!==paymentIntentId||refund.currency!==invoice.currency||!Number.isSafeInteger(refund.amount)||refund.amount<=0))throw new Error("[payments/connect] Foreign or invalid invoice refund");const creditNotes=await allPages((after)=>client.creditNotes.list({invoice:invoiceId,limit:100,...after?{starting_after:after}:{}},request));const invoiceLines=await allPages((after)=>client.invoices.listLineItems(invoiceId,{limit:100,...after?{starting_after:after}:{}},request));let requiresReview=refunds.some((refund)=>!["succeeded","failed","canceled"].includes(String(refund.status)));let creditedGross=0;let creditedNet=0;let creditedTax=0;const creditedRefunds=new Map;for(const credit of creditNotes){if(id(credit.invoice)!==invoiceId||id(credit.customer)!==id(invoice.customer)||credit.currency!==invoice.currency)throw new Error("[payments/connect] Foreign invoice tax credit");if(credit.status==="void")continue;if(credit.status!=="issued")throw new Error("[payments/connect] Unknown invoice credit status");const amounts=invoiceTaxAmounts(credit);const lines=await allPages((after)=>client.creditNotes.listLineItems(credit.id,{limit:100,...after?{starting_after:after}:{}},request));if(!lines.length||lines.some((line)=>line.type!=="invoice_line_item"))requiresReview=true;if(lines.some((line)=>line.type==="invoice_line_item"&&!invoiceLines.some((original)=>original.id===line.invoice_line_item)))throw new Error("[payments/connect] Tax credit references another invoice line");creditedGross+=amounts.gross;creditedNet+=amounts.net;creditedTax+=amounts.tax;let linkedGross=0;for(const link of credit.refunds){const refund=refunds.find((row)=>row.id===id(link.refund));if(!refund||refund.status!=="succeeded"||!Number.isSafeInteger(link.amount_refunded)||link.amount_refunded<0){requiresReview=true;continue}const credited=(creditedRefunds.get(refund.id)||0)+link.amount_refunded;creditedRefunds.set(refund.id,credited);if(credited>refund.amount)throw new Error("[payments/connect] Tax credits exceed the original refund");linkedGross+=link.amount_refunded}if(linkedGross!==amounts.gross)requiresReview=true}const refunded=refunds.filter((refund)=>refund.status==="succeeded").reduce((sum,refund)=>sum+refund.amount,0);if(creditedGross>basis.gross||creditedNet>basis.net||creditedTax>basis.tax||basis.tax>0&&(creditedGross!==refunded||refunds.some((refund)=>refund.status==="succeeded"&&creditedRefunds.get(refund.id)!==refund.amount)))requiresReview=true;return{invoice,creditNotes,currency:invoice.currency.toUpperCase(),...basis,creditedGross,creditedNet,creditedTax,requiresReview}}
@@ -1 +1 @@
1
- export async function allPages(read){const rows=[],seen=new Set;let after;for(let page=0;page<100;page++){const result=await read(after);for(const row of result.data){if(!row.id||seen.has(row.id))throw Error("Incomplete or repeated Stripe financial page");seen.add(row.id);rows.push(row)}if(!result.has_more)return rows;if(!result.data.length)throw Error("Incomplete Stripe financial page");after=result.data.at(-1).id}throw Error("Stripe financial pagination exceeded its bound")}
1
+ export async function allPages(read){const rows=[];const seen=new Set;let after;for(let page=0;page<100;page++){const result=await read(after);for(const row of result.data){if(!row.id||seen.has(row.id))throw new Error("Incomplete or repeated Stripe financial page");seen.add(row.id);rows.push(row)}if(!result.has_more)return rows;if(!result.data.length)throw new Error("Incomplete Stripe financial page");after=result.data.at(-1).id}throw new Error("Stripe financial pagination exceeded its bound")}