@stacksjs/payments 0.70.83 → 0.70.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createRequire as $x}from"module";import{services as r}from"@stacksjs/config";var zx=$x(import.meta.url);function Gx(){try{return zx("stripe")}catch{throw Error("Stripe payments are being used but the `stripe` package is not installed. "+"It is an opt-in dependency \u2014 run `bun add stripe` to enable server-side Stripe payments.")}}var I=null,_=new Proxy({},{get(x,T){if(!I){let w=r?.stripe?.secretKey;if(!w)throw Error("Stripe secret key is not configured. Set STRIPE_SECRET_KEY in your .env file.");let B="2026-03-25.dahlia",$=r?.stripe?.apiVersion;if($&&$!==B)throw Error(`Stripe API version ${$} does not match the installed SDK version ${B}`);I=new(Gx())(w,{apiVersion:B})}return I[T]}});import{config as Qx}from"@stacksjs/config";import{log as Zx}from"@stacksjs/logging";import{createHash as s}from"crypto";var y="stacks",l="v1",Jx=255;function U(x,...T){let w=T.filter((Q)=>Q!==null&&Q!==void 0&&Q!=="").map((Q)=>String(Q)).join(":"),B=w?`${y}:${x}:${w}:${l}`:`${y}:${x}:${l}`;if(B.length<=Jx)return B;let $=s("sha256").update(w).digest("hex").slice(0,32);return`${y}:${x}:${$}:${l}`}function j(x,...T){let w=s("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,16);return U(x,...T,w)}function t(){let x=Qx||{};return(x.payment?.currency||x.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}var M=(()=>{async function x($,Q,X){let z={currency:t(),amount:Q};if($.hasStripeId())z.customer=$.stripe_id??void 0;let H={...z,...X};return await _.paymentIntents.create(H,{idempotencyKey:j("payment_intent.create",$.id,Q)})}async function T($){try{return await _.paymentIntents.retrieve($)}catch(Q){return Zx.error(Q),null}}async function w($,Q={}){if(!$||typeof $!=="string")throw Error("[payments/refund] paymentIntentId is required");if(Q.amount!=null){if(typeof Q.amount!=="number"||!Number.isFinite(Q.amount)||Q.amount<=0)throw Error("[payments/refund] amount must be a positive finite number");try{let J=await _.paymentIntents.retrieve($),L=J.amount_received??J.amount;if(L&&Q.amount>L)throw Error(`[payments/refund] amount ${Q.amount} exceeds captured amount ${L}`)}catch(J){if(J instanceof Error&&J.message.startsWith("[payments/refund]"))throw J}}let{idempotencyKey:X,...z}=Q,H={payment_intent:$,...z},N={idempotencyKey:X||`refund:${$}:${z.amount??"full"}`};return await _.refunds.create(H,N)}async function B($,Q,X,z){let N={...{confirmation_method:"automatic",confirm:!0,payment_method:X,currency:t(),amount:Q},...z};return await x($,Q,N)}return{createPayment:x,charge:B,findPayment:T,refund:w}})();import{config as Lx}from"@stacksjs/config";function e(x,T){if(!x)return;let w;try{w=new URL(x)}catch{throw Error(`[payments/checkout] ${T} is not a valid URL: ${x}`)}let B=Lx?.app?.url;if(!B)return;let $;try{$=new URL(B.startsWith("http")?B:`https://${B}`).origin}catch{return}if(w.origin!==$)throw Error(`[payments/checkout] ${T} origin (${w.origin}) does not match app origin (${$})`)}var h=(()=>{async function x(T,w){let B=w.customer||T.stripe_id;if(!B)throw Error("User has no Stripe customer");e(w.success_url,"success_url"),e(w.cancel_url,"cancel_url");let Q={...{customer:B,mode:"payment",success_url:w.success_url,cancel_url:w.cancel_url},...w};return await _.checkout.sessions.create(Q,{idempotencyKey:j("checkout.session.create",T.id)})}return{create:x}})();var D=(()=>{function x(F){return F.stripe_id||""}function T(F){return{line1:F.address?.line1,city:F.address?.city,state:F.address?.state,postal_code:F.address?.postal_code,country:F.address?.country}}function w(){return[]}function B(F){return F}function $(F){return Boolean(F.stripe_id)}async function Q(F,Z={}){if($(F))throw Error("Customer already created");if(!Z.name&&G(F))Z.name=G(F);if(!Z.email&&R(F))Z.email=R(F);let A=await _.customers.create(Z,{idempotencyKey:U("customer.create",F.id)});return await F.update({stripe_id:A.id}),A}async function X(F,Z={}){if(!F.stripe_id)throw Error("User does not have a Stripe customer ID. Create a customer first.");return await _.customers.update(F.stripe_id,Z,{idempotencyKey:U("customer.update",F.id,F.stripe_id)})}async function z(F){if(!$(F))throw Error("User does not have a Stripe ID");try{if(!F.stripe_id)throw Error("User has no Stripe ID");let Z=await _.customers.del(F.stripe_id);return await F.update({stripe_id:""}),Z}catch(Z){if(Z.statusCode===404)throw Error("Customer not found in Stripe");throw Z}}async function H(F,Z={}){if(!$(F))return await Q(F,Z);try{let A=await _.customers.retrieve(F.stripe_id);if(A.deleted)throw Error("Customer was deleted");return A}catch(A){if(A.statusCode===404)return await Q(F,Z);throw A}}async function N(F){if(!$(F))return;try{let Z=await _.customers.retrieve(F.stripe_id);if(Z.deleted)throw Error("Customer was deleted in Stripe");return Z}catch(Z){if(Z.statusCode===404)throw Error("Customer not found in Stripe");throw Z}}async function J(F,Z){if(!$(F))return await Q(F,Z);try{if((await _.customers.retrieve(F.stripe_id)).deleted)return await Q(F,Z);return await X(F,Z)}catch(A){if(A.statusCode===404)return await Q(F,Z);throw A}}async function L(F,Z){return await X(F,{name:G(F),email:R(F),address:T(Z),preferred_locales:w(),metadata:Z.metadata?B(Z.metadata):{}})}function G(F){return F.name||""}function R(F){return F.email||""}return{stripeId:x,hasStripeId:$,createStripeCustomer:Q,updateStripeCustomer:X,createOrGetStripeUser:H,createOrUpdateStripeUser:J,deleteStripeUser:z,retrieveStripeUser:N,syncStripeCustomerDetails:L}})();var c=(()=>{async function x(T){if(!T.hasStripeId())throw Error("Customer does not exist in Stripe");if(!T.stripe_id)throw Error("User has no Stripe ID");return await _.invoices.list({customer:T.stripe_id,expand:["data.payment_intent.payment_method"]})}return{list:x}})();import{db as V}from"@stacksjs/database";import{PaymentMethod as m}from"@stacksjs/orm";var P=(()=>{async function x(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G;if(typeof L==="string")G=await _.paymentMethods.retrieve(L);else G=L;if(G.customer!==J.stripe_id)G=await _.paymentMethods.attach(G.id,{customer:J.stripe_id});return await B(J,G),G}async function T(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=await _.paymentMethods.retrieve(L),R=await V.selectFrom("payment_methods").where("provider_id","=",L).selectAll().executeTakeFirst();if(!J.stripe_id)throw Error("User has no Stripe ID");if(G.customer!==J.stripe_id)await _.paymentMethods.attach(G.id,{customer:J.stripe_id});let F=await _.customers.update(J.stripe_id,{invoice_settings:{default_payment_method:L}});if(await V.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",J.id).executeTakeFirst(),R)await $(R);return F}async function w(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=await V.selectFrom("payment_methods").where("id","=",L).selectAll().executeTakeFirst();if(!G?.provider_id)throw Error(`Payment method with id ${L} not found`);let R=await _.paymentMethods.retrieve(String(G.provider_id));if(R.customer!==J.stripe_id)await _.paymentMethods.attach(R.id,{customer:J.stripe_id});if(!J.stripe_id)throw Error("User has no Stripe ID");let F=await _.customers.update(J.stripe_id,{invoice_settings:{default_payment_method:String(G.provider_id)}});return await V.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",J.id).executeTakeFirst(),await V.updateTable("payment_methods").set({is_default:!0}).where("id","=",L).executeTakeFirst(),F}async function B(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");if(!L.card?.brand||!L.card?.exp_year||!L.card?.exp_month)throw Error("Invalid payment method: missing required card details");let G={type:"card",last_four:String(L.card.last4),brand:L.card.brand,exp_year:L.card.exp_year,exp_month:L.card.exp_month,user_id:J.id,provider_id:L.id};if(L.customer!==J.stripe_id)await _.paymentMethods.attach(L.id,{customer:J.stripe_id});return await m.create(G)}async function $(J){return await J.update({is_default:!0})}async function Q(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=typeof L==="string"?await V.selectFrom("payment_methods").where("provider_id","=",L).selectAll().executeTakeFirst():await m.find(L);if(!G?.provider_id)throw Error(`Payment method with id ${L} not found`);if((await _.paymentMethods.retrieve(String(G.provider_id))).customer!==J.stripe_id)throw Error("Payment method does not belong to this customer");return await G.delete(),await _.paymentMethods.detach(String(G.provider_id))}async function X(J,L,G){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");if((await _.paymentMethods.retrieve(L)).customer!==J.stripe_id)throw Error("Payment method does not belong to this customer");return await _.paymentMethods.update(L,G)}async function z(J){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await V.selectFrom("payment_methods").selectAll().where("user_id","=",J.id).execute()}async function H(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await V.selectFrom("payment_methods").where("id","=",L).selectAll().executeTakeFirst()}async function N(J){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await m.where("user_id",J.id).where("is_default",!0).first()}return{addPaymentMethod:x,deletePaymentMethod:Q,retrieveDefaultPaymentMethod:N,updatePaymentMethod:X,listPaymentMethods:z,setDefaultPaymentMethod:w,storePaymentMethod:B,retrievePaymentMethod:H,setUserDefaultPayment:T}})();var S=(()=>{async function x(w){let B=await _.prices.list({lookup_keys:[w]});if(!B.data.length)return;return B.data[0]}async function T(w,B){let $=await x(w);if($)return $;return await _.prices.create({...B,lookup_key:w})}return{retrieveByLookupKey:x,createOrGet:T}})();var v=(()=>{async function x(z){return await _.products.create(z)}async function T(z){return await _.products.retrieve(z)}async function w(z,H){return await _.products.update(z,H)}async function B(z={}){return await _.products.list({active:!0,...z})}async function $(z){return await _.products.update(z,{active:!1})}async function Q(z,H){let N=await _.products.create(z),J=await _.prices.create({...H,product:N.id});return{product:N,price:J}}async function X(z,H={query:""}){return await _.products.search({...H,query:z})}return{create:x,retrieve:T,update:w,list:B,archive:$,createWithPrice:Q,search:X}})(),xx=(()=>{async function x(z){return await _.prices.create(z)}async function T(z){return await _.prices.retrieve(z)}async function w(z,H){return await _.prices.update(z,H)}async function B(z={}){return await _.prices.list({active:!0,...z})}async function $(z,H={}){return await _.prices.list({product:z,active:!0,...H})}async function Q(z,H={query:""}){return await _.prices.search({...H,query:z})}async function X(z){return await _.prices.update(z,{active:!1})}return{create:x,retrieve:T,update:w,list:B,listByProduct:$,search:Q,archive:X}})(),C=(()=>{async function x(z){return await _.coupons.create(z)}async function T(z){return await _.coupons.retrieve(z)}async function w(z,H){return await _.coupons.update(z,H)}async function B(z){return await _.coupons.del(z)}async function $(z={}){return await _.coupons.list(z)}async function Q(z){return await _.promotionCodes.create(z)}async function X(z){try{let H=await _.promotionCodes.list({code:z,active:!0});if(H.data.length>0)return H.data[0]??null;return null}catch{return null}}return{create:x,retrieve:T,update:w,delete:B,list:$,createPromotionCode:Q,retrievePromotionCode:X}})();import{db as W}from"@stacksjs/database";import{HttpError as Ax}from"@stacksjs/error-handling";import{isUniqueViolation as Rx}from"@stacksjs/orm";var K=(()=>{async function x(G,R,F,Z){let A=await S.retrieveByLookupKey(F);if(!A)throw Error("Price does not exist in Stripe");let O=[{price:A.id,quantity:1}],f={...{customer:await D.createOrGetStripeUser(G,{}).then((b)=>{if(!b||!b.id)throw Error("Customer does not exist in Stripe");return b.id}),payment_behavior:"allow_incomplete",expand:["latest_invoice.payment_intent"],items:O},...Z},E=await _.subscriptions.create(f,{idempotencyKey:U("subscription.create",G.id,R,F)});return await N(G,R,F,E),E}async function T(G,R,F,Z={}){let A=await S.retrieveByLookupKey(F),O=await G?.activeSubscription();if(!A)throw Error("New price does not exist in Stripe");if(!O)throw Error("No active subscription for user!");let q=O.subscription?.provider_id;if(!q)throw Error("Active subscription has no provider ID");let k=await _.subscriptions.retrieve(q);if(!k)throw Error("Subscription does not exist in Stripe");let f=k.items.data[0]?.id;if(!f)throw Error("No subscription items found in the subscription");await _.subscriptions.update(q,{items:[{id:f,price:A.id,quantity:1}],proration_behavior:"create_prorations"},{idempotencyKey:U("subscription.update",q,A.id)});let E=await _.subscriptions.retrieve(q);if(!O.subscription?.id)throw Error("Active subscription has no database ID");return await J(O.subscription.id,R,E),E}async function w(G,R){if(!await _.subscriptions.retrieve(G))throw Error("Subscription does not exist or does not belong to the user");let Z=await _.subscriptions.cancel(G,R,{idempotencyKey:U("subscription.cancel",G)});return await $(G),Z}async function B(G,R){if(!G.hasStripeId())throw Error("Customer does not exist in Stripe");return await _.subscriptions.retrieve(R)}async function $(G){await W.updateTable("subscriptions").set({provider_status:"canceled"}).where("provider_id","=",G).executeTakeFirst()}function Q(G){return G.provider_status==="active"}function X(G){return G.provider_status==="trialing"}async function z(G,R){let F=await W.selectFrom("subscriptions").where("user_id","=",G.id).where("type","=",R).selectAll().executeTakeFirst();if(!F)return!1;return F.provider_status==="incomplete"}async function H(G,R){let F=await W.selectFrom("subscriptions").where("user_id","=",G.id).where("type","=",R).selectAll().executeTakeFirst();if(!F)return!1;let Z=await Q(F),A=await X(F);return Z||A}async function N(G,R,F,Z){let A=Z.items.data[0];if(!A)throw Error("Stripe subscription contains no line items \u2014 cannot store subscription");let O=L({user_id:G.id,type:R,unit_price:Number(A.price.unit_amount),provider_id:Z.id,provider_status:Z.status,provider_price_id:A.price.id,quantity:A.quantity,trial_ends_at:Z.trial_end!=null?String(Z.trial_end):void 0,ends_at:Z.current_period_end!=null?String(Z.current_period_end):void 0,provider_type:"stripe",last_used_at:Z.current_period_end!=null?String(Z.current_period_end):void 0}),q;try{q=await W.insertInto("subscriptions").values(O).executeTakeFirst()}catch(f){if(Rx(f))throw new Ax(409,"A subscription with this provider ID already exists");throw f}if(!q)throw Error("Failed to insert subscription record");return await W.selectFrom("subscriptions").where("id","=",Number(q.insertId)).selectAll().executeTakeFirst()}async function J(G,R,F){let Z=await W.selectFrom("subscriptions").where("id","=",G).selectAll().executeTakeFirst(),A=F.items.data[0];if(!A)throw Error("Stripe subscription contains no line items \u2014 cannot update subscription");return await W?.updateTable("subscriptions").set({type:R,provider_price_id:A.price.id,unit_price:Number(A.price.unit_amount)}).where("id","=",G).executeTakeFirst(),Z}function L(G){return Object.fromEntries(Object.entries(G).filter(([R,F])=>F!=null))}return{create:x,update:T,isValid:H,isIncomplete:z,cancel:w,retrieve:B}})();var Tx=(()=>{async function x(T,w){let Q={...{customer:await D.createOrGetStripeUser(T,{}).then((X)=>{if(!X||!X.id)throw Error("Customer does not exist in Stripe");return X.id}),payment_method_types:["card"]},...w};return await _.setupIntents.create(Q,{idempotencyKey:j("setup_intent.create",T.id)})}return{create:x}})();var u=new Map;function Y(x,T){let w=u.get(x)||[];w.push(T),u.set(x,w)}function Hx(x){for(let[T,w]of Object.entries(x))Y(T,w)}function Xx(x,T,w,B){if(B!=null&&Number.isFinite(B)&&B>0)return _.webhooks.constructEvent(x,T,w,B);return _.webhooks.constructEvent(x,T,w)}async function wx(x,T,w,B){if(B!=null&&Number.isFinite(B)&&B>0)return await _.webhooks.constructEventAsync(x,T,w,B);return await _.webhooks.constructEventAsync(x,T,w)}async function _x(x){let T=u.get(x.type)||[];if(T.length===0)return{handled:!1,eventType:x.type};let w=[];for(let B of T)try{await B(x)}catch($){w.push($ instanceof Error?$.message:String($))}return{handled:!0,eventType:x.type,...w.length>0?{errors:w}:{}}}async function d(x,T,w){try{let B=await wx(x,T,w.secret,w.tolerance),$=await _x(B);if($.errors&&$.errors.length>0)return{success:!1,eventType:$.eventType,error:$.errors.join("; ")};return{success:!0,eventType:$.eventType}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Unknown error"}}}function i(x){if(x.succeeded)Y("payment_intent.succeeded",x.succeeded);if(x.failed)Y("payment_intent.payment_failed",x.failed);if(x.created)Y("payment_intent.created",x.created);if(x.canceled)Y("payment_intent.canceled",x.canceled)}function p(x){if(x.created)Y("customer.subscription.created",x.created);if(x.updated)Y("customer.subscription.updated",x.updated);if(x.deleted)Y("customer.subscription.deleted",x.deleted);if(x.trialWillEnd)Y("customer.subscription.trial_will_end",x.trialWillEnd)}function a(x){if(x.paid)Y("invoice.paid",x.paid);if(x.paymentFailed)Y("invoice.payment_failed",x.paymentFailed);if(x.created)Y("invoice.created",x.created);if(x.finalized)Y("invoice.finalized",x.finalized)}function n(x){if(x.completed)Y("checkout.session.completed",x.completed);if(x.expired)Y("checkout.session.expired",x.expired)}function o(x){if(x.succeeded)Y("charge.succeeded",x.succeeded);if(x.failed)Y("charge.failed",x.failed);if(x.refunded)Y("charge.refunded",x.refunded);if(x.disputed)Y("charge.dispute.created",x.disputed)}function Yx(x){if(x.type.startsWith("payment_intent."))return x.data.object;return null}function Nx(x){if(x.type.startsWith("customer.subscription."))return x.data.object;return null}function qx(x){if(x.type.startsWith("invoice."))return x.data.object;return null}function Ux(x){if(x.type.startsWith("checkout.session."))return x.data.object;return null}function Dx(x){if(x.type.startsWith("charge."))return x.data.object;return null}function Ox(x){if(x.type.startsWith("customer.")&&!x.type.includes("subscription"))return x.data.object;return null}var Fx={onWebhookEvent:Y,registerWebhookHandlers:Hx,constructEvent:Xx,constructEventAsync:wx,handleWebhookEvent:_x,processWebhook:d,onPaymentIntent:i,onSubscription:p,onInvoice:a,onCheckout:n,onCharge:o,getPaymentIntent:Yx,getSubscription:Nx,getInvoice:qx,getCheckoutSession:Ux,getCharge:Dx,getCustomer:Ox};async function Vx(x,T,w,B={}){return M.charge(x,T,w,B)}async function fx(x,T,w={}){return M.createPayment(x,T,w)}async function jx(x,T,w={}){return M.refund(x,{amount:T,...w})}async function Wx(x,T,w={}){return h.create(x,{line_items:T,mode:"payment",...w})}async function Kx(x,T,w={}){return h.create(x,{line_items:[{price:T,quantity:1}],mode:"subscription",...w})}async function Ex(x,T,w={}){return K.create(x,"default",T,w)}async function Px(x,T=!1){return K.cancel(x,{prorate:!T,invoice_now:T})}async function Sx(x,T="default"){return K.isValid(x,T)}async function Cx(x,T,w="default"){return K.update(x,w,T,{})}async function kx(x,T={}){return D.createOrGetStripeUser(x,T)}async function Mx(x,T){return D.updateStripeCustomer(x,T)}async function vx(x){return D.deleteStripeUser(x)}async function gx(x,T){return P.addPaymentMethod(x,T)}async function bx(x,T){return P.setUserDefaultPayment(x,T)}async function Ix(x,T){return P.deletePaymentMethod(x,T)}async function yx(x,T={}){return Tx.create(x,T)}async function lx(x){return c.list(x)}async function hx(x,T={}){return _.invoices.create({customer:x,...T})}async function cx(x){return _.invoices.pay(x)}async function mx(x,T,w={}){let{currency:B="usd",interval:$,description:Q,metadata:X}=w,z={unit_amount:T,currency:B};if($)z.recurring={interval:$};return v.createWithPrice({name:x,description:Q,metadata:X},z)}async function ux(x){return S.retrieveByLookupKey(x)}async function dx(x={}){return v.list(x)}async function ix(x){let T={duration:x.duration||"once"};if(x.percentOff)T.percent_off=x.percentOff;else if(x.amountOff)T.amount_off=x.amountOff,T.currency=x.currency||"usd";if(x.name)T.name=x.name;if(x.durationInMonths)T.duration_in_months=x.durationInMonths;if(x.maxRedemptions)T.max_redemptions=x.maxRedemptions;return C.create(T)}async function px(x,T,w={}){return C.createPromotionCode({promotion:{type:"coupon",coupon:x},code:T,...w})}async function ax(x){return C.retrievePromotionCode(x)}function nx(x,T){let w=globalThis.config||{},B=(T||w.payment?.currency||w.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase(),$=w.app?.locale||"en-US";return new Intl.NumberFormat($,{style:"currency",currency:B.toUpperCase()}).format(x/100)}function ox(x){return Math.round(x*100)}function rx(x){return x/100}var sx={charge:Vx,createPayment:fx,refund:jx,checkout:Wx,subscriptionCheckout:Kx,subscribe:Ex,cancelSubscription:Px,hasActiveSubscription:Sx,changeSubscription:Cx,getOrCreateCustomer:kx,updateCustomer:Mx,deleteCustomer:vx,addPaymentMethod:gx,setDefaultPaymentMethod:bx,removePaymentMethod:Ix,createSetupIntent:yx,getInvoices:lx,createInvoice:hx,payInvoice:cx,createProduct:mx,getPrice:ux,listProducts:dx,createCoupon:ix,createPromoCode:px,validatePromoCode:ax,formatAmount:nx,toCents:ox,toDollars:rx,webhook:Fx,onPaymentIntent:i,onSubscription:p,onInvoice:a,onCheckout:n,onCharge:o,processWebhook:d,stripe:_,customer:D,subscription:K,invoice:c,paymentMethod:P,product:v,price:xx,coupon:C},tx=sx;import{saas as ex}from"@stacksjs/config";import{err as xT,ok as TT}from"@stacksjs/error-handling";import{log as wT}from"@stacksjs/logging";import{stripe as Bx}from"@stacksjs/payments";async function _w(){let x=ex.plans;try{if(x!==void 0&&x.length)for(let T of x){let w=await Bx.products.create({name:T.productName,description:T.description,metadata:T.metadata});for(let B of T.pricing)if(w){let $={unit_amount:B.price,currency:B.currency,product:w.id,lookup_key:B.key};if(B.interval)$.recurring={interval:B.interval};await Bx.prices.create($)}}return TT("Migrations generated")}catch(T){let w=T instanceof Error?T:Error(String(T));return wT.error(w),xT(w)}}import{db as g}from"@stacksjs/database";var $w=(()=>{async function x(w,B,$){let Q=await g.selectFrom("payment_products").where("id","=",B).selectAll().executeTakeFirst();if(!Q)throw Error(`Payment product with id ${B} not found.`);let X={name:Q.name,description:$.description??"",amount:Q.unit_price,brand:$.brand,type:$.type??"one-time",provider_id:$.provider_id,user_id:w.id},z=await g.insertInto("payment_transactions").values(X).executeTakeFirst();if(!z)throw Error("Failed to insert payment transaction");return await g.selectFrom("payment_transactions").where("id","=",Number(z.insertId)).selectAll().executeTakeFirst()}async function T(w){return await g.selectFrom("payment_transactions").where("user_id","=",w.id).selectAll().execute()}return{store:x,list:T}})();export{ax as validatePromoCode,Mx as updateCustomer,rx as toDollars,ox as toCents,Kx as subscriptionCheckout,Ex as subscribe,_ as stripe,U as stacksIdempotencyKey,bx as setDefaultPaymentMethod,Ix as removePaymentMethod,Hx as registerWebhookHandlers,jx as refund,d as processWebhook,cx as payInvoice,Y as onWebhookEvent,p as onSubscription,i as onPaymentIntent,a as onInvoice,n as onCheckout,o as onCharge,Fx as manageWebhook,$w as manageTransaction,K as manageSubscription,Tx as manageSetupIntent,v as manageProduct,xx as managePriceExtended,S as managePrice,P as managePaymentMethod,c as manageInvoice,D as manageCustomer,C as manageCoupon,h as manageCheckout,M as manageCharge,dx as listProducts,Sx as hasActiveSubscription,_x as handleWebhookEvent,Nx as getSubscription,ux as getPrice,Yx as getPaymentIntent,kx as getOrCreateCustomer,lx as getInvoices,qx as getInvoice,Ox as getCustomer,Ux as getCheckoutSession,Dx as getCharge,j as freshIdempotencyKey,nx as formatAmount,vx as deleteCustomer,_w as createStripeProduct,yx as createSetupIntent,px as createPromoCode,mx as createProduct,fx as createPayment,hx as createInvoice,ix as createCoupon,wx as constructEventAsync,Xx as constructEvent,Wx as checkout,Vx as charge,Cx as changeSubscription,Px as cancelSubscription,gx as addPaymentMethod,tx as Payment};
|
|
2
|
+
import{createRequire as t}from"module";import{services as u}from"@stacksjs/config";var e=t(import.meta.url);function TT(){try{return e("stripe")}catch{throw Error("Stripe payments are being used but the `stripe` package is not installed. "+"It is an opt-in dependency \u2014 run `bun add stripe` to enable server-side Stripe payments.")}}var b=null,_=new Proxy({},{get(T,x){if(!b){let w=u?.stripe?.secretKey;if(!w)throw Error("Stripe secret key is not configured. Set STRIPE_SECRET_KEY in your .env file.");let $="2026-03-25.dahlia",z=u?.stripe?.apiVersion;if(z&&z!==$)throw Error(`Stripe API version ${z} does not match the installed SDK version ${$}`);b=new(TT())(w,{apiVersion:$})}return b[x]}});import{config as wT}from"@stacksjs/config";import{log as _T}from"@stacksjs/logging";import{createHash as d}from"crypto";var I="stacks",y="v1",xT=255;function D(T,...x){let w=x.filter((Q)=>Q!==null&&Q!==void 0&&Q!=="").map((Q)=>String(Q)).join(":"),$=w?`${I}:${T}:${w}:${y}`:`${I}:${T}:${y}`;if($.length<=xT)return $;let z=d("sha256").update(w).digest("hex").slice(0,32);return`${I}:${T}:${z}:${y}`}function W(T,...x){let w=d("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,16);return D(T,...x,w)}function i(){let T=wT||{};return(T.payment?.currency||T.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}var C=(()=>{async function T(z,Q,X){let B={currency:i(),amount:Q};if(z.hasStripeId())B.customer=z.stripe_id??void 0;let H={...B,...X};return await _.paymentIntents.create(H,{idempotencyKey:W("payment_intent.create",z.id,Q)})}async function x(z){try{return await _.paymentIntents.retrieve(z)}catch(Q){return _T.error(Q),null}}async function w(z,Q={}){if(!z||typeof z!=="string")throw Error("[payments/refund] paymentIntentId is required");if(Q.amount!=null){if(typeof Q.amount!=="number"||!Number.isFinite(Q.amount)||Q.amount<=0)throw Error("[payments/refund] amount must be a positive finite number");try{let J=await _.paymentIntents.retrieve(z),L=J.amount_received??J.amount;if(L&&Q.amount>L)throw Error(`[payments/refund] amount ${Q.amount} exceeds captured amount ${L}`)}catch(J){if(J instanceof Error&&J.message.startsWith("[payments/refund]"))throw J}}let{idempotencyKey:X,...B}=Q,H={payment_intent:z,...B},N={idempotencyKey:X||`refund:${z}:${B.amount??"full"}`};return await _.refunds.create(H,N)}async function $(z,Q,X,B){let N={...{confirmation_method:"automatic",confirm:!0,payment_method:X,currency:i(),amount:Q},...B};return await T(z,Q,N)}return{createPayment:T,charge:$,findPayment:x,refund:w}})();import{config as FT}from"@stacksjs/config";function a(T,x){if(!T)return;let w;try{w=new URL(T)}catch{throw Error(`[payments/checkout] ${x} is not a valid URL: ${T}`)}let $=FT?.app?.url;if(!$)return;let z;try{z=new URL($.startsWith("http")?$:`https://${$}`).origin}catch{return}if(w.origin!==z)throw Error(`[payments/checkout] ${x} origin (${w.origin}) does not match app origin (${z})`)}var l=(()=>{async function T(x,w){let $=w.customer||x.stripe_id;if(!$)throw Error("User has no Stripe customer");a(w.success_url,"success_url"),a(w.cancel_url,"cancel_url");let Q={...{customer:$,mode:"payment",success_url:w.success_url,cancel_url:w.cancel_url},...w};return await _.checkout.sessions.create(Q,{idempotencyKey:W("checkout.session.create",x.id)})}return{create:T}})();var O=(()=>{function T(F){return F.stripe_id||""}function x(F){return{line1:F.address?.line1,city:F.address?.city,state:F.address?.state,postal_code:F.address?.postal_code,country:F.address?.country}}function w(){return[]}function $(F){return F}function z(F){return Boolean(F.stripe_id)}async function Q(F,Z={}){if(z(F))throw Error("Customer already created");if(!Z.name&&G(F))Z.name=G(F);if(!Z.email&&R(F))Z.email=R(F);let A=await _.customers.create(Z,{idempotencyKey:D("customer.create",F.id)});return await F.update({stripe_id:A.id}),A}async function X(F,Z={}){if(!F.stripe_id)throw Error("User does not have a Stripe customer ID. Create a customer first.");return await _.customers.update(F.stripe_id,Z,{idempotencyKey:D("customer.update",F.id,F.stripe_id)})}async function B(F){if(!z(F))throw Error("User does not have a Stripe ID");try{if(!F.stripe_id)throw Error("User has no Stripe ID");let Z=await _.customers.del(F.stripe_id);return await F.update({stripe_id:""}),Z}catch(Z){if(Z.statusCode===404)throw Error("Customer not found in Stripe");throw Z}}async function H(F,Z={}){if(!z(F))return await Q(F,Z);try{let A=await _.customers.retrieve(F.stripe_id);if(A.deleted)throw Error("Customer was deleted");return A}catch(A){if(A.statusCode===404)return await Q(F,Z);throw A}}async function N(F){if(!z(F))return;try{let Z=await _.customers.retrieve(F.stripe_id);if(Z.deleted)throw Error("Customer was deleted in Stripe");return Z}catch(Z){if(Z.statusCode===404)throw Error("Customer not found in Stripe");throw Z}}async function J(F,Z){if(!z(F))return await Q(F,Z);try{if((await _.customers.retrieve(F.stripe_id)).deleted)return await Q(F,Z);return await X(F,Z)}catch(A){if(A.statusCode===404)return await Q(F,Z);throw A}}async function L(F,Z){return await X(F,{name:G(F),email:R(F),address:x(Z),preferred_locales:w(),metadata:Z.metadata?$(Z.metadata):{}})}function G(F){return F.name||""}function R(F){return F.email||""}return{stripeId:T,hasStripeId:z,createStripeCustomer:Q,updateStripeCustomer:X,createOrGetStripeUser:H,createOrUpdateStripeUser:J,deleteStripeUser:B,retrieveStripeUser:N,syncStripeCustomerDetails:L}})();var p=(()=>{async function T(x){if(!x.hasStripeId())throw Error("Customer does not exist in Stripe");if(!x.stripe_id)throw Error("User has no Stripe ID");return await _.invoices.list({customer:x.stripe_id,expand:["data.payment_intent.payment_method"]})}return{list:T}})();import{db as V}from"@stacksjs/database";import{PaymentMethod as h}from"@stacksjs/orm";var k=(()=>{async function T(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G;if(typeof L==="string")G=await _.paymentMethods.retrieve(L);else G=L;if(G.customer!==J.stripe_id)G=await _.paymentMethods.attach(G.id,{customer:J.stripe_id});return await $(J,G),G}async function x(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=await _.paymentMethods.retrieve(L),R=await V.selectFrom("payment_methods").where("provider_id","=",L).selectAll().executeTakeFirst();if(!J.stripe_id)throw Error("User has no Stripe ID");if(G.customer!==J.stripe_id)await _.paymentMethods.attach(G.id,{customer:J.stripe_id});let F=await _.customers.update(J.stripe_id,{invoice_settings:{default_payment_method:L}});if(await V.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",J.id).executeTakeFirst(),R)await z(R);return F}async function w(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=await V.selectFrom("payment_methods").where("id","=",L).selectAll().executeTakeFirst();if(!G?.provider_id)throw Error(`Payment method with id ${L} not found`);let R=await _.paymentMethods.retrieve(String(G.provider_id));if(R.customer!==J.stripe_id)await _.paymentMethods.attach(R.id,{customer:J.stripe_id});if(!J.stripe_id)throw Error("User has no Stripe ID");let F=await _.customers.update(J.stripe_id,{invoice_settings:{default_payment_method:String(G.provider_id)}});return await V.updateTable("payment_methods").set({is_default:!1}).where("user_id","=",J.id).executeTakeFirst(),await V.updateTable("payment_methods").set({is_default:!0}).where("id","=",L).executeTakeFirst(),F}async function $(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");if(!L.card?.brand||!L.card?.exp_year||!L.card?.exp_month)throw Error("Invalid payment method: missing required card details");let G={type:"card",last_four:String(L.card.last4),brand:L.card.brand,exp_year:L.card.exp_year,exp_month:L.card.exp_month,user_id:J.id,provider_id:L.id};if(L.customer!==J.stripe_id)await _.paymentMethods.attach(L.id,{customer:J.stripe_id});return await h.create(G)}async function z(J){return await J.update({is_default:!0})}async function Q(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");let G=typeof L==="string"?await V.selectFrom("payment_methods").where("provider_id","=",L).selectAll().executeTakeFirst():await h.find(L);if(!G?.provider_id)throw Error(`Payment method with id ${L} not found`);if((await _.paymentMethods.retrieve(String(G.provider_id))).customer!==J.stripe_id)throw Error("Payment method does not belong to this customer");return await G.delete(),await _.paymentMethods.detach(String(G.provider_id))}async function X(J,L,G){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");if((await _.paymentMethods.retrieve(L)).customer!==J.stripe_id)throw Error("Payment method does not belong to this customer");return await _.paymentMethods.update(L,G)}async function B(J){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await V.selectFrom("payment_methods").selectAll().where("user_id","=",J.id).execute()}async function H(J,L){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await V.selectFrom("payment_methods").where("id","=",L).selectAll().executeTakeFirst()}async function N(J){if(!J.hasStripeId())throw Error("Customer does not exist in Stripe");return await h.where("user_id",J.id).where("is_default",!0).first()}return{addPaymentMethod:T,deletePaymentMethod:Q,retrieveDefaultPaymentMethod:N,updatePaymentMethod:X,listPaymentMethods:B,setDefaultPaymentMethod:w,storePaymentMethod:$,retrievePaymentMethod:H,setUserDefaultPayment:x}})();var E=(()=>{async function T(w){let $=await _.prices.list({lookup_keys:[w]});if(!$.data.length)return;return $.data[0]}async function x(w,$){let z=await T(w);if(z)return z;return await _.prices.create({...$,lookup_key:w})}return{retrieveByLookupKey:T,createOrGet:x}})();var c=(()=>{async function T(B){return await _.products.create(B)}async function x(B){return await _.products.retrieve(B)}async function w(B,H){return await _.products.update(B,H)}async function $(B={}){return await _.products.list({active:!0,...B})}async function z(B){return await _.products.update(B,{active:!1})}async function Q(B,H){let N=await _.products.create(B),J=await _.prices.create({...H,product:N.id});return{product:N,price:J}}async function X(B,H={query:""}){return await _.products.search({...H,query:B})}return{create:T,retrieve:x,update:w,list:$,archive:z,createWithPrice:Q,search:X}})(),$T=(()=>{async function T(B){return await _.prices.create(B)}async function x(B){return await _.prices.retrieve(B)}async function w(B,H){return await _.prices.update(B,H)}async function $(B={}){return await _.prices.list({active:!0,...B})}async function z(B,H={}){return await _.prices.list({product:B,active:!0,...H})}async function Q(B,H={query:""}){return await _.prices.search({...H,query:B})}async function X(B){return await _.prices.update(B,{active:!1})}return{create:T,retrieve:x,update:w,list:$,listByProduct:z,search:Q,archive:X}})(),M=(()=>{async function T(B){return await _.coupons.create(B)}async function x(B){return await _.coupons.retrieve(B)}async function w(B,H){return await _.coupons.update(B,H)}async function $(B){return await _.coupons.del(B)}async function z(B={}){return await _.coupons.list(B)}async function Q(B){return await _.promotionCodes.create(B)}async function X(B){try{let H=await _.promotionCodes.list({code:B,active:!0});if(H.data.length>0)return H.data[0]??null;return null}catch{return null}}return{create:T,retrieve:x,update:w,delete:$,list:z,createPromotionCode:Q,retrievePromotionCode:X}})();import{db as f}from"@stacksjs/database";import{HttpError as zT}from"@stacksjs/error-handling";import{isUniqueViolation as BT}from"@stacksjs/orm";var P=(()=>{async function T(G,R,F,Z){let A=await E.retrieveByLookupKey(F);if(!A)throw Error("Price does not exist in Stripe");let U=[{price:A.id,quantity:1}],j={...{customer:await O.createOrGetStripeUser(G,{}).then((g)=>{if(!g||!g.id)throw Error("Customer does not exist in Stripe");return g.id}),payment_behavior:"allow_incomplete",expand:["latest_invoice.payment_intent"],items:U},...Z},K=await _.subscriptions.create(j,{idempotencyKey:D("subscription.create",G.id,R,F)});return await N(G,R,F,K),K}async function x(G,R,F,Z={}){let A=await E.retrieveByLookupKey(F),U=await G?.activeSubscription();if(!A)throw Error("New price does not exist in Stripe");if(!U)throw Error("No active subscription for user!");let q=U.subscription?.provider_id;if(!q)throw Error("Active subscription has no provider ID");let S=await _.subscriptions.retrieve(q);if(!S)throw Error("Subscription does not exist in Stripe");let j=S.items.data[0]?.id;if(!j)throw Error("No subscription items found in the subscription");await _.subscriptions.update(q,{items:[{id:j,price:A.id,quantity:1}],proration_behavior:"create_prorations"},{idempotencyKey:D("subscription.update",q,A.id)});let K=await _.subscriptions.retrieve(q);if(!U.subscription?.id)throw Error("Active subscription has no database ID");return await J(U.subscription.id,R,K),K}async function w(G,R){if(!await _.subscriptions.retrieve(G))throw Error("Subscription does not exist or does not belong to the user");let Z=await _.subscriptions.cancel(G,R,{idempotencyKey:D("subscription.cancel",G)});return await z(G),Z}async function $(G,R){if(!G.hasStripeId())throw Error("Customer does not exist in Stripe");return await _.subscriptions.retrieve(R)}async function z(G){await f.updateTable("subscriptions").set({provider_status:"canceled"}).where("provider_id","=",G).executeTakeFirst()}function Q(G){return G.provider_status==="active"}function X(G){return G.provider_status==="trialing"}async function B(G,R){let F=await f.selectFrom("subscriptions").where("user_id","=",G.id).where("type","=",R).selectAll().executeTakeFirst();if(!F)return!1;return F.provider_status==="incomplete"}async function H(G,R){let F=await f.selectFrom("subscriptions").where("user_id","=",G.id).where("type","=",R).selectAll().executeTakeFirst();if(!F)return!1;let Z=await Q(F),A=await X(F);return Z||A}async function N(G,R,F,Z){let A=Z.items.data[0];if(!A)throw Error("Stripe subscription contains no line items \u2014 cannot store subscription");let U=L({user_id:G.id,type:R,unit_price:Number(A.price.unit_amount),provider_id:Z.id,provider_status:Z.status,provider_price_id:A.price.id,quantity:A.quantity,trial_ends_at:Z.trial_end!=null?String(Z.trial_end):void 0,ends_at:Z.current_period_end!=null?String(Z.current_period_end):void 0,provider_type:"stripe",last_used_at:Z.current_period_end!=null?String(Z.current_period_end):void 0}),q;try{q=await f.insertInto("subscriptions").values(U).executeTakeFirst()}catch(j){if(BT(j))throw new zT(409,"A subscription with this provider ID already exists");throw j}if(!q)throw Error("Failed to insert subscription record");return await f.selectFrom("subscriptions").where("id","=",Number(q.insertId)).selectAll().executeTakeFirst()}async function J(G,R,F){let Z=await f.selectFrom("subscriptions").where("id","=",G).selectAll().executeTakeFirst(),A=F.items.data[0];if(!A)throw Error("Stripe subscription contains no line items \u2014 cannot update subscription");return await f?.updateTable("subscriptions").set({type:R,provider_price_id:A.price.id,unit_price:Number(A.price.unit_amount)}).where("id","=",G).executeTakeFirst(),Z}function L(G){return Object.fromEntries(Object.entries(G).filter(([R,F])=>F!=null))}return{create:T,update:x,isValid:H,isIncomplete:B,cancel:w,retrieve:$}})();var n=(()=>{async function T(x,w){let Q={...{customer:await O.createOrGetStripeUser(x,{}).then((X)=>{if(!X||!X.id)throw Error("Customer does not exist in Stripe");return X.id}),payment_method_types:["card"]},...w};return await _.setupIntents.create(Q,{idempotencyKey:W("setup_intent.create",x.id)})}return{create:T}})();var m=new Map;function Y(T,x){let w=m.get(T)||[];w.push(x),m.set(T,w)}function GT(T){for(let[x,w]of Object.entries(T))Y(x,w)}function JT(T,x,w,$){if($!=null&&Number.isFinite($)&&$>0)return _.webhooks.constructEvent(T,x,w,$);return _.webhooks.constructEvent(T,x,w)}async function o(T,x,w,$){if($!=null&&Number.isFinite($)&&$>0)return await _.webhooks.constructEventAsync(T,x,w,$);return await _.webhooks.constructEventAsync(T,x,w)}async function r(T){let x=m.get(T.type)||[];if(x.length===0)return{handled:!1,eventType:T.type};let w=[];for(let $ of x)try{await $(T)}catch(z){w.push(z instanceof Error?z.message:String(z))}return{handled:!0,eventType:T.type,...w.length>0?{errors:w}:{}}}async function QT(T,x,w){try{let $=await o(T,x,w.secret,w.tolerance),z=await r($);if(z.errors&&z.errors.length>0)return{success:!1,eventType:z.eventType,error:z.errors.join("; ")};return{success:!0,eventType:z.eventType}}catch($){return{success:!1,error:$ instanceof Error?$.message:"Unknown error"}}}function ZT(T){if(T.succeeded)Y("payment_intent.succeeded",T.succeeded);if(T.failed)Y("payment_intent.payment_failed",T.failed);if(T.created)Y("payment_intent.created",T.created);if(T.canceled)Y("payment_intent.canceled",T.canceled)}function LT(T){if(T.created)Y("customer.subscription.created",T.created);if(T.updated)Y("customer.subscription.updated",T.updated);if(T.deleted)Y("customer.subscription.deleted",T.deleted);if(T.trialWillEnd)Y("customer.subscription.trial_will_end",T.trialWillEnd)}function AT(T){if(T.paid)Y("invoice.paid",T.paid);if(T.paymentFailed)Y("invoice.payment_failed",T.paymentFailed);if(T.created)Y("invoice.created",T.created);if(T.finalized)Y("invoice.finalized",T.finalized)}function RT(T){if(T.completed)Y("checkout.session.completed",T.completed);if(T.expired)Y("checkout.session.expired",T.expired)}function HT(T){if(T.succeeded)Y("charge.succeeded",T.succeeded);if(T.failed)Y("charge.failed",T.failed);if(T.refunded)Y("charge.refunded",T.refunded);if(T.disputed)Y("charge.dispute.created",T.disputed)}function XT(T){if(T.type.startsWith("payment_intent."))return T.data.object;return null}function YT(T){if(T.type.startsWith("customer.subscription."))return T.data.object;return null}function NT(T){if(T.type.startsWith("invoice."))return T.data.object;return null}function qT(T){if(T.type.startsWith("checkout.session."))return T.data.object;return null}function UT(T){if(T.type.startsWith("charge."))return T.data.object;return null}function DT(T){if(T.type.startsWith("customer.")&&!T.type.includes("subscription"))return T.data.object;return null}var Jx={onWebhookEvent:Y,registerWebhookHandlers:GT,constructEvent:JT,constructEventAsync:o,handleWebhookEvent:r,processWebhook:QT,onPaymentIntent:ZT,onSubscription:LT,onInvoice:AT,onCheckout:RT,onCharge:HT,getPaymentIntent:XT,getSubscription:YT,getInvoice:NT,getCheckoutSession:qT,getCharge:UT,getCustomer:DT};async function Dx(T,x,w,$={}){return C.charge(T,x,w,$)}async function Ox(T,x,w={}){return C.createPayment(T,x,w)}async function Vx(T,x,w={}){return C.refund(T,{amount:x,...w})}async function jx(T,x,w={}){return l.create(T,{line_items:x,mode:"payment",...w})}async function fx(T,x,w={}){return l.create(T,{line_items:[{price:x,quantity:1}],mode:"subscription",...w})}async function Wx(T,x,w={}){return P.create(T,"default",x,w)}async function Kx(T,x=!1){return P.cancel(T,{prorate:!x,invoice_now:x})}async function Ex(T,x="default"){return P.isValid(T,x)}async function Px(T,x,w="default"){return P.update(T,w,x,{})}async function Sx(T,x={}){return O.createOrGetStripeUser(T,x)}async function Cx(T,x){return O.updateStripeCustomer(T,x)}async function kx(T){return O.deleteStripeUser(T)}async function Mx(T,x){return k.addPaymentMethod(T,x)}async function vx(T,x){return k.setUserDefaultPayment(T,x)}async function gx(T,x){return k.deletePaymentMethod(T,x)}async function bx(T,x={}){return n.create(T,x)}async function Ix(T){return p.list(T)}async function yx(T,x={}){return _.invoices.create({customer:T,...x})}async function lx(T){return _.invoices.pay(T)}async function hx(T,x,w={}){let{currency:$="usd",interval:z,description:Q,metadata:X}=w,B={unit_amount:x,currency:$};if(z)B.recurring={interval:z};return c.createWithPrice({name:T,description:Q,metadata:X},B)}async function cx(T){return E.retrieveByLookupKey(T)}async function mx(T={}){return c.list(T)}async function ux(T){let x={duration:T.duration||"once"};if(T.percentOff)x.percent_off=T.percentOff;else if(T.amountOff)x.amount_off=T.amountOff,x.currency=T.currency||"usd";if(T.name)x.name=T.name;if(T.durationInMonths)x.duration_in_months=T.durationInMonths;if(T.maxRedemptions)x.max_redemptions=T.maxRedemptions;return M.create(x)}async function dx(T,x,w={}){return M.createPromotionCode({promotion:{type:"coupon",coupon:T},code:x,...w})}async function ix(T){return M.retrievePromotionCode(T)}function ax(T,x){let w=globalThis.config||{},$=(x||w.payment?.currency||w.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase(),z=w.app?.locale||"en-US";return new Intl.NumberFormat(z,{style:"currency",currency:$.toUpperCase()}).format(T/100)}function px(T){return Math.round(T*100)}function nx(T){return T/100}import{saas as OT}from"@stacksjs/config";import{err as VT,ok as jT}from"@stacksjs/error-handling";import{log as fT}from"@stacksjs/logging";import{stripe as s}from"@stacksjs/payments";async function Tw(){let T=OT.plans;try{if(T!==void 0&&T.length)for(let x of T){let w=await s.products.create({name:x.productName,description:x.description,metadata:x.metadata});for(let $ of x.pricing)if(w){let z={unit_amount:$.price,currency:$.currency,product:w.id,lookup_key:$.key};if($.interval)z.recurring={interval:$.interval};await s.prices.create(z)}}return jT("Migrations generated")}catch(x){let w=x instanceof Error?x:Error(String(x));return fT.error(w),VT(w)}}import{db as v}from"@stacksjs/database";var _w=(()=>{async function T(w,$,z){let Q=await v.selectFrom("payment_products").where("id","=",$).selectAll().executeTakeFirst();if(!Q)throw Error(`Payment product with id ${$} not found.`);let X={name:Q.name,description:z.description??"",amount:Q.unit_price,brand:z.brand,type:z.type??"one-time",provider_id:z.provider_id,user_id:w.id},B=await v.insertInto("payment_transactions").values(X).executeTakeFirst();if(!B)throw Error("Failed to insert payment transaction");return await v.selectFrom("payment_transactions").where("id","=",Number(B.insertId)).selectAll().executeTakeFirst()}async function x(w){return await v.selectFrom("payment_transactions").where("user_id","=",w.id).selectAll().execute()}return{store:T,list:x}})();export{ix as validatePromoCode,Cx as updateCustomer,nx as toDollars,px as toCents,fx as subscriptionCheckout,Wx as subscribe,_ as stripe,Aw as stacksIdempotencyKey,vx as setDefaultPaymentMethod,gx as removePaymentMethod,GT as registerWebhookHandlers,Vx as refund,QT as processWebhook,lx as payInvoice,Y as onWebhookEvent,LT as onSubscription,ZT as onPaymentIntent,AT as onInvoice,RT as onCheckout,HT as onCharge,Jx as manageWebhook,_w as manageTransaction,P as manageSubscription,n as manageSetupIntent,c as manageProduct,$T as managePriceExtended,E as managePrice,k as managePaymentMethod,p as manageInvoice,O as manageCustomer,M as manageCoupon,l as manageCheckout,C as manageCharge,mx as listProducts,Ex as hasActiveSubscription,r as handleWebhookEvent,YT as getSubscription,cx as getPrice,XT as getPaymentIntent,Sx as getOrCreateCustomer,Ix as getInvoices,NT as getInvoice,DT as getCustomer,qT as getCheckoutSession,UT as getCharge,Lw as freshIdempotencyKey,ax as formatAmount,kx as deleteCustomer,Tw as createStripeProduct,bx as createSetupIntent,dx as createPromoCode,hx as createProduct,Ox as createPayment,yx as createInvoice,ux as createCoupon,o as constructEventAsync,JT as constructEvent,jx as checkout,Dx as charge,Px as changeSubscription,Kx as cancelSubscription,Mx as addPaymentMethod,Gw as Payment};
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/payments",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"
|
|
4
|
+
"sideEffects": false,
|
|
5
|
+
"version": "0.70.85",
|
|
5
6
|
"description": "The Stacks payments package. Currently supporting Stripe.",
|
|
6
7
|
"author": "Chris Breuer",
|
|
7
8
|
"contributors": [
|
|
@@ -66,9 +67,9 @@
|
|
|
66
67
|
}
|
|
67
68
|
},
|
|
68
69
|
"devDependencies": {
|
|
69
|
-
"@stacksjs/config": "0.70.
|
|
70
|
+
"@stacksjs/config": "0.70.85",
|
|
70
71
|
"better-dx": "^0.2.16",
|
|
71
|
-
"@stacksjs/utils": "0.70.
|
|
72
|
+
"@stacksjs/utils": "0.70.85",
|
|
72
73
|
"@stripe/stripe-js": "^8.7.0",
|
|
73
74
|
"stripe": "^21.0.1"
|
|
74
75
|
}
|