@stacksjs/payments 0.75.661 → 0.75.667
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/billable/checkout.d.ts +5 -1
- package/dist/billable/checkout.js +1 -1
- package/dist/billable/portal.js +1 -1
- package/dist/driver/adyen.js +1 -1
- package/dist/driver/index.js +1 -1
- package/dist/driver/lemonsqueezy.js +1 -1
- package/dist/driver/paddle.js +1 -1
- package/dist/driver/stripe.d.ts +1 -1
- package/dist/driver/stripe.js +1 -1
- package/dist/driver/types.d.ts +1 -0
- package/package.json +8 -8
|
@@ -10,5 +10,9 @@ import type Stripe from 'stripe';
|
|
|
10
10
|
export declare function assertSameOriginUrl(url: string | undefined, label: string): void;
|
|
11
11
|
export declare const manageCheckout: Checkout;
|
|
12
12
|
export declare interface Checkout {
|
|
13
|
-
create: (user: UserModel, params: Stripe.Checkout.SessionCreateParams) => Promise<Stripe.Response<Stripe.Checkout.Session>>
|
|
13
|
+
create: (user: UserModel, params: Stripe.Checkout.SessionCreateParams, options?: CheckoutOptions) => Promise<Stripe.Response<Stripe.Checkout.Session>>
|
|
14
14
|
}
|
|
15
|
+
declare interface CheckoutOptions {
|
|
16
|
+
idempotencyKey?: string
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -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 new Error(`[payments/checkout] ${label} is not a valid URL: ${url}`)}if(!["http:","https:"].includes(parsed.protocol)||parsed.username||parsed.password)throw new Error(`[payments/checkout] ${label} must be an HTTP URL without credentials`);const appUrl=config?.app?.url;if(!appUrl)return;let appOrigin;try{appOrigin=new URL(appUrl.startsWith("http")?appUrl:`https://${appUrl}`).origin}catch{return}const browserOrigins=config.payment?.checkoutReturnOrigins??[];const allowedOrigins=browserOrigins.map((value)=>{try{const origin=new URL(value);if(!["http:","https:"].includes(origin.protocol)||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash)throw new Error("Not a bare origin");return origin.origin}catch{throw new Error("[payments/checkout] checkoutReturnOrigins must contain bare HTTP origins without credentials")}});if(parsed.origin!==appOrigin&&!allowedOrigins.includes(parsed.origin)){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
|
+
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}`)}if(!["http:","https:"].includes(parsed.protocol)||parsed.username||parsed.password)throw new Error(`[payments/checkout] ${label} must be an HTTP URL without credentials`);const appUrl=config?.app?.url;if(!appUrl)return;let appOrigin;try{appOrigin=new URL(appUrl.startsWith("http")?appUrl:`https://${appUrl}`).origin}catch{return}const browserOrigins=config.payment?.checkoutReturnOrigins??[];const allowedOrigins=browserOrigins.map((value)=>{try{const origin=new URL(value);if(!["http:","https:"].includes(origin.protocol)||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash)throw new Error("Not a bare origin");return origin.origin}catch{throw new Error("[payments/checkout] checkoutReturnOrigins must contain bare HTTP origins without credentials")}});if(parsed.origin!==appOrigin&&!allowedOrigins.includes(parsed.origin)){throw new Error(`[payments/checkout] ${label} origin (${parsed.origin}) does not match app origin (${appOrigin})`)}}export const manageCheckout=(()=>{async function create(user,params,options={}){const{idempotencyKey}=options;if(idempotencyKey!==undefined&&(!idempotencyKey.trim()||idempotencyKey.length>255))throw new TypeError("A Stripe checkout idempotency key must be nonblank and at most 255 characters.");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:idempotencyKey??freshIdempotencyKey("checkout.session.create",user.id)})}return{create}})();
|
package/dist/billable/portal.js
CHANGED
|
@@ -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!==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
|
+
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 subscriptionUpdate=portal.subscriptionUpdate;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},...subscriptionUpdate!==undefined&&{subscription_update:subscriptionUpdate===false?{enabled:false}:{enabled:true,default_allowed_updates:subscriptionUpdate.allowedUpdates,proration_behavior:subscriptionUpdate.prorationBehavior,products:subscriptionUpdate.products.map(({product,prices,adjustableQuantity})=>({product,prices,adjustable_quantity:adjustableQuantity?{enabled:true,...adjustableQuantity}:{enabled:false}}))}}},...Object.keys(businessProfile).length?{business_profile:businessProfile}:{},...portal.returnUrl?{default_return_url:portal.returnUrl}:{},metadata:managedPortalTag(appName)}}function sameStrings(actual,expected){const sorted=actual.toSorted();return actual.length===expected.length&&expected.toSorted().every((value,index)=>sorted[index]===value)}function subscriptionUpdateMatches(live,desired){if(!desired)return true;if(live.enabled!==desired.enabled)return false;if(!desired.enabled)return true;const products=live.products??[];const allowedProducts=desired.products||[];return live.proration_behavior===desired.proration_behavior&&sameStrings(live.default_allowed_updates,desired.default_allowed_updates||[])&&products.length===allowedProducts.length&&allowedProducts.every((product)=>{const current=products.find((candidate)=>candidate.product===product.product);const quantity=product.adjustable_quantity;return current!==undefined&&sameStrings(current.prices,product.prices)&¤t.adjustable_quantity.enabled===Boolean(quantity?.enabled)&&(!quantity?.enabled||current.adjustable_quantity.minimum===quantity.minimum&¤t.adjustable_quantity.maximum===quantity.maximum)})}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)&&subscriptionUpdateMatches(have.subscription_update,want.subscription_update)&&(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}:{}})}};
|
package/dist/driver/adyen.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHmac,randomUUID,timingSafeEqual}from"node:crypto";import{assertMoney,PaymentProviderError,PaymentUnsupportedError,WebhookNotConfiguredError,WebhookSignatureError}from"./types";export const ADYEN_API_VERSION="v72";const CAPABILITIES=new Set(["customers","charge","createPayment","refund","checkout","paymentMethods","webhooks"]);export function adyenStatus(resultCode){switch(resultCode){case"Authorised":return"succeeded";case"Refused":case"Error":return"failed";case"Cancelled":return"canceled";case"RedirectShopper":case"ChallengeShopper":case"IdentifyShopper":case"PresentToShopper":return"requires_action";default:return"processing"}}const ADYEN_PAYMENT_METHODS={card:"scheme",sepa_debit:"sepadirectdebit"};const EVENT_TYPES={AUTHORISATION:["payment.succeeded","payment.failed"],CANCELLATION:["payment.canceled","unknown"],REFUND:["refund.succeeded","refund.failed"],REFUND_FAILED:["refund.failed","refund.failed"],CANCEL_OR_REFUND:["refund.succeeded","refund.failed"]};export function adyenSigningPayload(item){return[item.pspReference??"",item.originalReference??"",item.merchantAccountCode??"",item.merchantReference??"",item.amount?.value??"",item.amount?.currency??"",item.eventCode??"",String(item.success??"")].join(":")}export function adyenSignature(item,hmacKey){return createHmac("sha256",Buffer.from(hmacKey,"hex")).update(adyenSigningPayload(item),"utf8").digest("base64")}export class AdyenDriver{name="adyen";capabilities=CAPABILITIES;config;fetch;constructor(config,options={}){if(!config.apiKey)throw new Error("The Adyen payment driver needs an API key: set ADYEN_API_KEY or payment.adyen.apiKey.");if(!config.merchantAccount)throw new Error("The Adyen payment driver needs a merchant account: set ADYEN_MERCHANT_ACCOUNT or payment.adyen.merchantAccount.");if(config.environment==="live"&&!config.liveUrlPrefix)throw new Error("Adyen live requests go to your account's own endpoint: set ADYEN_LIVE_URL_PREFIX or payment.adyen.liveUrlPrefix.");this.config=config;this.fetch=options.fetch??fetch}get baseUrl(){return this.config.environment==="live"?`https://${this.config.liveUrlPrefix}-checkout-live.adyenpayments.com/checkout/${ADYEN_API_VERSION}`:`https://checkout-test.adyen.com/${ADYEN_API_VERSION}`}shopperReference(payer){return`${this.config.shopperReferencePrefix??"user-"}${payer.id}`}async request(method,path,options={}){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(options.query??{}))url.searchParams.set(key,value);const headers={"X-API-Key":this.config.apiKey,Accept:"application/json"};if(options.body!==undefined)headers["Content-Type"]="application/json";if(options.idempotencyKey)headers["Idempotency-Key"]=options.idempotencyKey;const response=await this.fetch(url,{method,headers,body:options.body===undefined?undefined:JSON.stringify(options.body)});if(response.status===204)return;const text=await response.text();const body=text?JSON.parse(text):undefined;if(!response.ok){const error=body;throw new PaymentProviderError("adyen",response.status,error?.message??response.statusText,error?.errorCode??null)}return body}assertReturnUrl(url,label){let target;try{target=new URL(url)}catch{throw new TypeError(`${label} is not a valid URL: ${url}`)}if(!this.config.appUrl)return;const app=new URL(/^https?:\/\//.test(this.config.appUrl)?this.config.appUrl:`https://${this.config.appUrl}`);if(target.origin!==app.origin)throw new TypeError(`${label} (${target.origin}) is not on the application's origin (${app.origin})`)}amount(money){assertMoney(money);return{value:money.amount,currency:money.currency.toUpperCase()}}async customer(payer){return{id:this.shopperReference(payer),email:payer.email??null,name:payer.name??null}}async charge(payer,amount,paymentMethod,options={}){const response=await this.request("POST","/payments",{body:{merchantAccount:this.config.merchantAccount,amount:this.amount(amount),reference:options.reference??randomUUID(),paymentMethod:{type:"scheme",storedPaymentMethodId:paymentMethod},shopperReference:this.shopperReference(payer),shopperInteraction:"ContAuth",recurringProcessingModel:"UnscheduledCardOnFile",...options.metadata?{metadata:options.metadata}:{}},idempotencyKey:options.idempotencyKey});return{id:response.pspReference,status:adyenStatus(response.resultCode),amount:{amount:amount.amount,currency:amount.currency.toLowerCase()},...response.action?.url?{redirectUrl:response.action.url}:{},...response.refusalReason?{failureReason:response.refusalReason}:{},raw:response}}async createPayment(payer,amount,options={}){if(!options.returnUrl)throw new TypeError("An Adyen payment session needs a returnUrl: where the payer comes back after authenticating.");this.assertReturnUrl(options.returnUrl,"returnUrl");const session=await this.request("POST","/sessions",{body:{merchantAccount:this.config.merchantAccount,amount:this.amount(amount),reference:options.reference??randomUUID(),returnUrl:options.returnUrl,mode:"embedded",shopperReference:this.shopperReference(payer),...options.metadata?{metadata:options.metadata}:{}},idempotencyKey:options.idempotencyKey});return{id:session.id,status:"requires_payment_method",amount:{amount:amount.amount,currency:amount.currency.toLowerCase()},clientConfirmation:{provider:"adyen",sessionId:session.id,sessionData:session.sessionData},raw:session}}async refund(paymentId,options={}){const reference=randomUUID();const response=options.amount?await this.request("POST",`/payments/${encodeURIComponent(paymentId)}/refunds`,{body:{merchantAccount:this.config.merchantAccount,amount:this.amount(options.amount),reference},idempotencyKey:options.idempotencyKey}):await this.request("POST",`/payments/${encodeURIComponent(paymentId)}/reversals`,{body:{merchantAccount:this.config.merchantAccount,reference},idempotencyKey:options.idempotencyKey});return{id:response.pspReference,paymentId,status:"pending",amount:options.amount?{amount:options.amount.amount,currency:options.amount.currency.toLowerCase()}:null,raw:response}}async checkout(payer,request){if(request.trialDays&&request.mode!=="subscription")throw new TypeError("trialDays applies to a subscription checkout.");if(request.mode==="subscription")throw new PaymentUnsupportedError("adyen","subscription checkout",'Adyen has no subscriptions; store a card with mode "setup" and charge it on your schedule');if(request.cancelUrl&&request.cancelUrl!==request.successUrl)throw new PaymentUnsupportedError("adyen","a separate cancelUrl","Adyen's hosted checkout returns to one URL, with the outcome in its query string");if(request.allowPromotionCodes)throw new PaymentUnsupportedError("adyen","promotion codes","Adyen has no coupons; discount the line amounts instead");if(request.automaticTax)throw new PaymentUnsupportedError("adyen","automatic tax","Adyen does not calculate tax; price each line including it");if(!request.currency)throw new TypeError("An Adyen checkout needs a currency.");const allowedPaymentMethods=request.paymentMethods?.map((method)=>{const adyen=ADYEN_PAYMENT_METHODS[method];if(!adyen)throw new PaymentUnsupportedError("adyen",`the ${method} payment method`,"name it in Adyen's own terms through the Customer Area, or offer card and sepa_debit");return adyen});this.assertReturnUrl(request.successUrl,"successUrl");const lines=request.lines.map((line)=>{if("price"in line)throw new PaymentUnsupportedError("adyen","catalog prices","Adyen has no product catalog; price each line with name and unitAmount");return line});const total=lines.reduce((sum,line)=>sum+line.unitAmount*line.quantity,0);const setup=request.mode==="setup";const session=await this.request("POST","/sessions",{body:{merchantAccount:this.config.merchantAccount,amount:this.amount({amount:setup?0:total,currency:request.currency}),reference:request.reference??randomUUID(),returnUrl:request.successUrl,mode:"hosted",shopperReference:this.shopperReference(payer),...payer.email?{shopperEmail:payer.email}:{},...setup?{storePaymentMethodMode:"enabled",recurringProcessingModel:"UnscheduledCardOnFile"}:{},...setup?{}:{lineItems:lines.map((line)=>({description:line.name,quantity:line.quantity,amountIncludingTax:line.unitAmount}))},...request.metadata?{metadata:request.metadata}:{},...allowedPaymentMethods?.length?{allowedPaymentMethods}:{}}});if(!session.url)throw new PaymentProviderError("adyen",200,"the hosted session came back without a url");return{id:session.id,url:session.url,expiresAt:session.expiresAt?new Date(session.expiresAt):null,raw:session}}async paymentMethods(payer){const response=await this.request("GET","/storedPaymentMethods",{query:{merchantAccount:this.config.merchantAccount,shopperReference:this.shopperReference(payer)}});return(response?.storedPaymentMethods??[]).map((method)=>({id:String(method.id),type:String(method.type??"scheme"),brand:method.brand??null,last4:method.lastFour??null,expMonth:method.expiryMonth?Number(method.expiryMonth):null,expYear:method.expiryYear?Number(String(method.expiryYear).length===2?`20${method.expiryYear}`:method.expiryYear):null,isDefault:false,raw:method}))}async removePaymentMethod(payer,paymentMethodId){await this.request("DELETE",`/storedPaymentMethods/${encodeURIComponent(paymentMethodId)}`,{query:{merchantAccount:this.config.merchantAccount,shopperReference:this.shopperReference(payer)}})}async subscribe(){throw new PaymentUnsupportedError("adyen","subscriptions","charge a stored card on your own schedule with charge()")}async cancelSubscription(){throw new PaymentUnsupportedError("adyen","subscriptions")}async subscriptions(){throw new PaymentUnsupportedError("adyen","subscriptions")}async verifyWebhook(request){if(!this.config.hmacKey)throw new WebhookNotConfiguredError("adyen","Adyen webhooks cannot be verified without the HMAC key: set ADYEN_HMAC_KEY or payment.adyen.hmacKey.");let body;try{body=JSON.parse(request.payload)}catch{throw new WebhookSignatureError("adyen","the body is not JSON")}const items=(body.notificationItems??[]).map((entry)=>entry.NotificationRequestItem).filter((item)=>Boolean(item));if(items.length===0)throw new WebhookSignatureError("adyen","the delivery holds no notification items");return items.map((item)=>{const given=item.additionalData?.hmacSignature;if(!given)throw new WebhookSignatureError("adyen",`item ${item.pspReference??"?"} has no hmacSignature`);const expected=Buffer.from(adyenSignature(item,this.config.hmacKey));const actual=Buffer.from(given);if(expected.length!==actual.length||!timingSafeEqual(expected,actual))throw new WebhookSignatureError("adyen",`item ${item.pspReference??"?"} is signed with another key`);const success=String(item.success)==="true";const pair=EVENT_TYPES[item.eventCode??""];return{provider:this.name,id:`${item.eventCode}:${item.pspReference}:${success}`,type:pair?pair[success?0:1]:"unknown",providerType:item.eventCode??"",reference:item.originalReference||item.pspReference||null,reason:item.reason||null,merchantReference:item.merchantReference??null,amount:item.amount?.value!==undefined&&item.amount.currency?{amount:Number(item.amount.value),currency:item.amount.currency.toLowerCase()}:null,raw:item}})}acknowledgeWebhook(){return new Response("[accepted]",{status:202,headers:{"Content-Type":"text/plain"}})}}
|
|
1
|
+
import{createHmac,randomUUID,timingSafeEqual}from"node:crypto";import{assertMoney,PaymentProviderError,PaymentUnsupportedError,WebhookNotConfiguredError,WebhookSignatureError}from"./types";export const ADYEN_API_VERSION="v72";const CAPABILITIES=new Set(["customers","charge","createPayment","refund","checkout","paymentMethods","webhooks"]);export function adyenStatus(resultCode){switch(resultCode){case"Authorised":return"succeeded";case"Refused":case"Error":return"failed";case"Cancelled":return"canceled";case"RedirectShopper":case"ChallengeShopper":case"IdentifyShopper":case"PresentToShopper":return"requires_action";default:return"processing"}}const ADYEN_PAYMENT_METHODS={card:"scheme",sepa_debit:"sepadirectdebit"};const EVENT_TYPES={AUTHORISATION:["payment.succeeded","payment.failed"],CANCELLATION:["payment.canceled","unknown"],REFUND:["refund.succeeded","refund.failed"],REFUND_FAILED:["refund.failed","refund.failed"],CANCEL_OR_REFUND:["refund.succeeded","refund.failed"]};export function adyenSigningPayload(item){return[item.pspReference??"",item.originalReference??"",item.merchantAccountCode??"",item.merchantReference??"",item.amount?.value??"",item.amount?.currency??"",item.eventCode??"",String(item.success??"")].join(":")}export function adyenSignature(item,hmacKey){return createHmac("sha256",Buffer.from(hmacKey,"hex")).update(adyenSigningPayload(item),"utf8").digest("base64")}export class AdyenDriver{name="adyen";capabilities=CAPABILITIES;config;fetch;constructor(config,options={}){if(!config.apiKey)throw new Error("The Adyen payment driver needs an API key: set ADYEN_API_KEY or payment.adyen.apiKey.");if(!config.merchantAccount)throw new Error("The Adyen payment driver needs a merchant account: set ADYEN_MERCHANT_ACCOUNT or payment.adyen.merchantAccount.");if(config.environment==="live"&&!config.liveUrlPrefix)throw new Error("Adyen live requests go to your account's own endpoint: set ADYEN_LIVE_URL_PREFIX or payment.adyen.liveUrlPrefix.");this.config=config;this.fetch=options.fetch??fetch}get baseUrl(){return this.config.environment==="live"?`https://${this.config.liveUrlPrefix}-checkout-live.adyenpayments.com/checkout/${ADYEN_API_VERSION}`:`https://checkout-test.adyen.com/${ADYEN_API_VERSION}`}shopperReference(payer){return`${this.config.shopperReferencePrefix??"user-"}${payer.id}`}async request(method,path,options={}){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(options.query??{}))url.searchParams.set(key,value);const headers={"X-API-Key":this.config.apiKey,Accept:"application/json"};if(options.body!==undefined)headers["Content-Type"]="application/json";if(options.idempotencyKey)headers["Idempotency-Key"]=options.idempotencyKey;const response=await this.fetch(url,{method,headers,body:options.body===undefined?undefined:JSON.stringify(options.body)});if(response.status===204)return;const text=await response.text();const body=text?JSON.parse(text):undefined;if(!response.ok){const error=body;throw new PaymentProviderError("adyen",response.status,error?.message??response.statusText,error?.errorCode??null)}return body}assertReturnUrl(url,label){let target;try{target=new URL(url)}catch{throw new TypeError(`${label} is not a valid URL: ${url}`)}if(!this.config.appUrl)return;const app=new URL(/^https?:\/\//.test(this.config.appUrl)?this.config.appUrl:`https://${this.config.appUrl}`);if(target.origin!==app.origin)throw new TypeError(`${label} (${target.origin}) is not on the application's origin (${app.origin})`)}amount(money){assertMoney(money);return{value:money.amount,currency:money.currency.toUpperCase()}}async customer(payer){return{id:this.shopperReference(payer),email:payer.email??null,name:payer.name??null}}async charge(payer,amount,paymentMethod,options={}){const response=await this.request("POST","/payments",{body:{merchantAccount:this.config.merchantAccount,amount:this.amount(amount),reference:options.reference??randomUUID(),paymentMethod:{type:"scheme",storedPaymentMethodId:paymentMethod},shopperReference:this.shopperReference(payer),shopperInteraction:"ContAuth",recurringProcessingModel:"UnscheduledCardOnFile",...options.metadata?{metadata:options.metadata}:{}},idempotencyKey:options.idempotencyKey});return{id:response.pspReference,status:adyenStatus(response.resultCode),amount:{amount:amount.amount,currency:amount.currency.toLowerCase()},...response.action?.url?{redirectUrl:response.action.url}:{},...response.refusalReason?{failureReason:response.refusalReason}:{},raw:response}}async createPayment(payer,amount,options={}){if(!options.returnUrl)throw new TypeError("An Adyen payment session needs a returnUrl: where the payer comes back after authenticating.");this.assertReturnUrl(options.returnUrl,"returnUrl");const session=await this.request("POST","/sessions",{body:{merchantAccount:this.config.merchantAccount,amount:this.amount(amount),reference:options.reference??randomUUID(),returnUrl:options.returnUrl,mode:"embedded",shopperReference:this.shopperReference(payer),...options.metadata?{metadata:options.metadata}:{}},idempotencyKey:options.idempotencyKey});return{id:session.id,status:"requires_payment_method",amount:{amount:amount.amount,currency:amount.currency.toLowerCase()},clientConfirmation:{provider:"adyen",sessionId:session.id,sessionData:session.sessionData},raw:session}}async refund(paymentId,options={}){const reference=randomUUID();const response=options.amount?await this.request("POST",`/payments/${encodeURIComponent(paymentId)}/refunds`,{body:{merchantAccount:this.config.merchantAccount,amount:this.amount(options.amount),reference},idempotencyKey:options.idempotencyKey}):await this.request("POST",`/payments/${encodeURIComponent(paymentId)}/reversals`,{body:{merchantAccount:this.config.merchantAccount,reference},idempotencyKey:options.idempotencyKey});return{id:response.pspReference,paymentId,status:"pending",amount:options.amount?{amount:options.amount.amount,currency:options.amount.currency.toLowerCase()}:null,raw:response}}async checkout(payer,request){if(request.idempotencyKey!==undefined)throw new PaymentUnsupportedError("adyen","a checkout idempotency key");if(request.trialDays&&request.mode!=="subscription")throw new TypeError("trialDays applies to a subscription checkout.");if(request.mode==="subscription")throw new PaymentUnsupportedError("adyen","subscription checkout",'Adyen has no subscriptions; store a card with mode "setup" and charge it on your schedule');if(request.cancelUrl&&request.cancelUrl!==request.successUrl)throw new PaymentUnsupportedError("adyen","a separate cancelUrl","Adyen's hosted checkout returns to one URL, with the outcome in its query string");if(request.allowPromotionCodes)throw new PaymentUnsupportedError("adyen","promotion codes","Adyen has no coupons; discount the line amounts instead");if(request.automaticTax)throw new PaymentUnsupportedError("adyen","automatic tax","Adyen does not calculate tax; price each line including it");if(!request.currency)throw new TypeError("An Adyen checkout needs a currency.");const allowedPaymentMethods=request.paymentMethods?.map((method)=>{const adyen=ADYEN_PAYMENT_METHODS[method];if(!adyen)throw new PaymentUnsupportedError("adyen",`the ${method} payment method`,"name it in Adyen's own terms through the Customer Area, or offer card and sepa_debit");return adyen});this.assertReturnUrl(request.successUrl,"successUrl");const lines=request.lines.map((line)=>{if("price"in line)throw new PaymentUnsupportedError("adyen","catalog prices","Adyen has no product catalog; price each line with name and unitAmount");return line});const total=lines.reduce((sum,line)=>sum+line.unitAmount*line.quantity,0);const setup=request.mode==="setup";const session=await this.request("POST","/sessions",{body:{merchantAccount:this.config.merchantAccount,amount:this.amount({amount:setup?0:total,currency:request.currency}),reference:request.reference??randomUUID(),returnUrl:request.successUrl,mode:"hosted",shopperReference:this.shopperReference(payer),...payer.email?{shopperEmail:payer.email}:{},...setup?{storePaymentMethodMode:"enabled",recurringProcessingModel:"UnscheduledCardOnFile"}:{},...setup?{}:{lineItems:lines.map((line)=>({description:line.name,quantity:line.quantity,amountIncludingTax:line.unitAmount}))},...request.metadata?{metadata:request.metadata}:{},...allowedPaymentMethods?.length?{allowedPaymentMethods}:{}}});if(!session.url)throw new PaymentProviderError("adyen",200,"the hosted session came back without a url");return{id:session.id,url:session.url,expiresAt:session.expiresAt?new Date(session.expiresAt):null,raw:session}}async paymentMethods(payer){const response=await this.request("GET","/storedPaymentMethods",{query:{merchantAccount:this.config.merchantAccount,shopperReference:this.shopperReference(payer)}});return(response?.storedPaymentMethods??[]).map((method)=>({id:String(method.id),type:String(method.type??"scheme"),brand:method.brand??null,last4:method.lastFour??null,expMonth:method.expiryMonth?Number(method.expiryMonth):null,expYear:method.expiryYear?Number(String(method.expiryYear).length===2?`20${method.expiryYear}`:method.expiryYear):null,isDefault:false,raw:method}))}async removePaymentMethod(payer,paymentMethodId){await this.request("DELETE",`/storedPaymentMethods/${encodeURIComponent(paymentMethodId)}`,{query:{merchantAccount:this.config.merchantAccount,shopperReference:this.shopperReference(payer)}})}async subscribe(){throw new PaymentUnsupportedError("adyen","subscriptions","charge a stored card on your own schedule with charge()")}async cancelSubscription(){throw new PaymentUnsupportedError("adyen","subscriptions")}async subscriptions(){throw new PaymentUnsupportedError("adyen","subscriptions")}async verifyWebhook(request){if(!this.config.hmacKey)throw new WebhookNotConfiguredError("adyen","Adyen webhooks cannot be verified without the HMAC key: set ADYEN_HMAC_KEY or payment.adyen.hmacKey.");let body;try{body=JSON.parse(request.payload)}catch{throw new WebhookSignatureError("adyen","the body is not JSON")}const items=(body.notificationItems??[]).map((entry)=>entry.NotificationRequestItem).filter((item)=>Boolean(item));if(items.length===0)throw new WebhookSignatureError("adyen","the delivery holds no notification items");return items.map((item)=>{const given=item.additionalData?.hmacSignature;if(!given)throw new WebhookSignatureError("adyen",`item ${item.pspReference??"?"} has no hmacSignature`);const expected=Buffer.from(adyenSignature(item,this.config.hmacKey));const actual=Buffer.from(given);if(expected.length!==actual.length||!timingSafeEqual(expected,actual))throw new WebhookSignatureError("adyen",`item ${item.pspReference??"?"} is signed with another key`);const success=String(item.success)==="true";const pair=EVENT_TYPES[item.eventCode??""];return{provider:this.name,id:`${item.eventCode}:${item.pspReference}:${success}`,type:pair?pair[success?0:1]:"unknown",providerType:item.eventCode??"",reference:item.originalReference||item.pspReference||null,reason:item.reason||null,merchantReference:item.merchantReference??null,amount:item.amount?.value!==undefined&&item.amount.currency?{amount:Number(item.amount.value),currency:item.amount.currency.toLowerCase()}:null,raw:item}})}acknowledgeWebhook(){return new Response("[accepted]",{status:202,headers:{"Content-Type":"text/plain"}})}}
|
package/dist/driver/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{config,services}from"@stacksjs/config";import{manageCharge}from"../billable/charge";import{manageCheckout}from"../billable/checkout";import{manageCustomer}from"../billable/customer";import{managePaymentMethod}from"../billable/payment-method";import{manageSubscription}from"../billable/subscription";import{constructEvent}from"../billable/webhook";import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";import{AdyenDriver}from"./adyen";import{LemonSqueezyDriver}from"./lemonsqueezy";import{PaddleDriver}from"./paddle";import{PaymentUnsupportedError}from"./types";import{StripeDriver}from"./stripe";export*from"./adyen";export*from"./lemonsqueezy";export*from"./paddle";export*from"./paddle-checkout";export*from"./stripe";export*from"./types";export const defaultStripeOperations={customer:(payer)=>manageCustomer.createOrGetStripeUser(payer,{}),createIntent:(payer,params,idempotencyKey)=>stripe.paymentIntents.create(params,{idempotencyKey:idempotencyKey??freshIdempotencyKey("payment_intent.create",payer.id,params.amount)}),refund:(paymentIntentId,params)=>manageCharge.refund(paymentIntentId,params),createCheckout:(payer,params)=>manageCheckout.create(payer,params),listPaymentMethods:async(customerId)=>(await stripe.paymentMethods.list({customer:customerId,limit:100})).data,deletePaymentMethod:(payer,paymentMethodId)=>managePaymentMethod.deletePaymentMethod(payer,paymentMethodId),subscribe:(payer,type,lookupKey)=>manageSubscription.create(payer,type,lookupKey,{}),cancelSubscription:(subscriptionId,atPeriodEnd)=>atPeriodEnd?manageSubscription.cancelAtPeriodEnd(subscriptionId):manageSubscription.cancel(subscriptionId),listSubscriptions:async(customerId)=>(await stripe.subscriptions.list({customer:customerId,status:"all",limit:100})).data,constructEvent:(payload,signature,secret,tolerance)=>constructEvent(payload,signature,secret,tolerance)};const BUILT_IN_DRIVERS=["stripe","adyen","paddle","lemonsqueezy"];const custom=new Map;export function registerPaymentDriver(name,factory){if(BUILT_IN_DRIVERS.includes(name))throw new Error(`"${name}" is a built-in payment driver and cannot be replaced.`);custom.set(name,factory)}export function adyenConfig(settings={},env=process.env){const environment=settings.environment??(env.ADYEN_ENVIRONMENT==="live"?"live":"test");return{apiKey:settings.apiKey||env.ADYEN_API_KEY||"",merchantAccount:settings.merchantAccount||env.ADYEN_MERCHANT_ACCOUNT||"",environment,liveUrlPrefix:settings.liveUrlPrefix||env.ADYEN_LIVE_URL_PREFIX||undefined,hmacKey:settings.hmacKey||env.ADYEN_HMAC_KEY||undefined,shopperReferencePrefix:settings.shopperReferencePrefix}}export function paddleConfig(settings={},env=process.env){const environment=settings.environment??(env.PADDLE_ENVIRONMENT==="live"?"live":"sandbox");return{apiKey:settings.apiKey||env.PADDLE_API_KEY||"",environment,webhookSecret:settings.webhookSecret||env.PADDLE_WEBHOOK_SECRET||undefined,clientToken:settings.clientToken||env.PADDLE_CLIENT_TOKEN||undefined,taxCategory:settings.taxCategory||env.PADDLE_TAX_CATEGORY||undefined,webhookTolerance:settings.webhookTolerance}}export function lemonSqueezyConfig(settings={},env=process.env){return{apiKey:settings.apiKey||env.LEMONSQUEEZY_API_KEY||"",storeId:settings.storeId||env.LEMONSQUEEZY_STORE_ID||"",webhookSecret:settings.webhookSecret||env.LEMONSQUEEZY_WEBHOOK_SECRET||undefined,customPriceVariantId:settings.customPriceVariantId||env.LEMONSQUEEZY_VARIANT_ID||undefined,testMode:settings.testMode??env.LEMONSQUEEZY_TEST_MODE==="true"}}export function configuredPaymentDriver(){return(config.payment??{}).driver??"stripe"}export function assertStripeDriver(operation){const configured=configuredPaymentDriver();if(configured!=="stripe")throw new PaymentUnsupportedError(configured,operation,"it is a Stripe-only operation")}export function paymentDriver(name){const settings=config.payment??{};const chosen=name??configuredPaymentDriver();if(chosen==="stripe"){return new StripeDriver({operations:defaultStripeOperations,webhookSecret:settings.stripe?.webhookSecret||services?.stripe?.webhookSecret||process.env.STRIPE_WEBHOOK_SECRET||undefined,webhookTolerance:settings.stripe?.webhookTolerance??settings.webhook?.tolerance})}if(chosen==="adyen"){const appUrl=config.app?.url;return new AdyenDriver({...adyenConfig(settings.adyen),...appUrl?{appUrl}:{}})}if(chosen==="paddle"){const appUrl=config.app?.url;return new PaddleDriver({...paddleConfig(settings.paddle),...appUrl?{appUrl}:{}})}if(chosen==="lemonsqueezy"){const appUrl=config.app?.url;return new LemonSqueezyDriver({...lemonSqueezyConfig(settings.lemonsqueezy),...appUrl?{appUrl}:{}})}const factory=custom.get(chosen);if(!factory)throw new Error(`No payment driver named "${chosen}". Built in: ${BUILT_IN_DRIVERS.join(", ")}${custom.size?`; registered: ${[...custom.keys()].join(", ")}`:""}.`);return factory()}
|
|
1
|
+
import process from"node:process";import{config,services}from"@stacksjs/config";import{manageCharge}from"../billable/charge";import{manageCheckout}from"../billable/checkout";import{manageCustomer}from"../billable/customer";import{managePaymentMethod}from"../billable/payment-method";import{manageSubscription}from"../billable/subscription";import{constructEvent}from"../billable/webhook";import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";import{AdyenDriver}from"./adyen";import{LemonSqueezyDriver}from"./lemonsqueezy";import{PaddleDriver}from"./paddle";import{PaymentUnsupportedError}from"./types";import{StripeDriver}from"./stripe";export*from"./adyen";export*from"./lemonsqueezy";export*from"./paddle";export*from"./paddle-checkout";export*from"./stripe";export*from"./types";export const defaultStripeOperations={customer:(payer)=>manageCustomer.createOrGetStripeUser(payer,{}),createIntent:(payer,params,idempotencyKey)=>stripe.paymentIntents.create(params,{idempotencyKey:idempotencyKey??freshIdempotencyKey("payment_intent.create",payer.id,params.amount)}),refund:(paymentIntentId,params)=>manageCharge.refund(paymentIntentId,params),createCheckout:(payer,params,idempotencyKey)=>manageCheckout.create(payer,params,{idempotencyKey}),listPaymentMethods:async(customerId)=>(await stripe.paymentMethods.list({customer:customerId,limit:100})).data,deletePaymentMethod:(payer,paymentMethodId)=>managePaymentMethod.deletePaymentMethod(payer,paymentMethodId),subscribe:(payer,type,lookupKey)=>manageSubscription.create(payer,type,lookupKey,{}),cancelSubscription:(subscriptionId,atPeriodEnd)=>atPeriodEnd?manageSubscription.cancelAtPeriodEnd(subscriptionId):manageSubscription.cancel(subscriptionId),listSubscriptions:async(customerId)=>(await stripe.subscriptions.list({customer:customerId,status:"all",limit:100})).data,constructEvent:(payload,signature,secret,tolerance)=>constructEvent(payload,signature,secret,tolerance)};const BUILT_IN_DRIVERS=["stripe","adyen","paddle","lemonsqueezy"];const custom=new Map;export function registerPaymentDriver(name,factory){if(BUILT_IN_DRIVERS.includes(name))throw new Error(`"${name}" is a built-in payment driver and cannot be replaced.`);custom.set(name,factory)}export function adyenConfig(settings={},env=process.env){const environment=settings.environment??(env.ADYEN_ENVIRONMENT==="live"?"live":"test");return{apiKey:settings.apiKey||env.ADYEN_API_KEY||"",merchantAccount:settings.merchantAccount||env.ADYEN_MERCHANT_ACCOUNT||"",environment,liveUrlPrefix:settings.liveUrlPrefix||env.ADYEN_LIVE_URL_PREFIX||undefined,hmacKey:settings.hmacKey||env.ADYEN_HMAC_KEY||undefined,shopperReferencePrefix:settings.shopperReferencePrefix}}export function paddleConfig(settings={},env=process.env){const environment=settings.environment??(env.PADDLE_ENVIRONMENT==="live"?"live":"sandbox");return{apiKey:settings.apiKey||env.PADDLE_API_KEY||"",environment,webhookSecret:settings.webhookSecret||env.PADDLE_WEBHOOK_SECRET||undefined,clientToken:settings.clientToken||env.PADDLE_CLIENT_TOKEN||undefined,taxCategory:settings.taxCategory||env.PADDLE_TAX_CATEGORY||undefined,webhookTolerance:settings.webhookTolerance}}export function lemonSqueezyConfig(settings={},env=process.env){return{apiKey:settings.apiKey||env.LEMONSQUEEZY_API_KEY||"",storeId:settings.storeId||env.LEMONSQUEEZY_STORE_ID||"",webhookSecret:settings.webhookSecret||env.LEMONSQUEEZY_WEBHOOK_SECRET||undefined,customPriceVariantId:settings.customPriceVariantId||env.LEMONSQUEEZY_VARIANT_ID||undefined,testMode:settings.testMode??env.LEMONSQUEEZY_TEST_MODE==="true"}}export function configuredPaymentDriver(){return(config.payment??{}).driver??"stripe"}export function assertStripeDriver(operation){const configured=configuredPaymentDriver();if(configured!=="stripe")throw new PaymentUnsupportedError(configured,operation,"it is a Stripe-only operation")}export function paymentDriver(name){const settings=config.payment??{};const chosen=name??configuredPaymentDriver();if(chosen==="stripe"){return new StripeDriver({operations:defaultStripeOperations,webhookSecret:settings.stripe?.webhookSecret||services?.stripe?.webhookSecret||process.env.STRIPE_WEBHOOK_SECRET||undefined,webhookTolerance:settings.stripe?.webhookTolerance??settings.webhook?.tolerance})}if(chosen==="adyen"){const appUrl=config.app?.url;return new AdyenDriver({...adyenConfig(settings.adyen),...appUrl?{appUrl}:{}})}if(chosen==="paddle"){const appUrl=config.app?.url;return new PaddleDriver({...paddleConfig(settings.paddle),...appUrl?{appUrl}:{}})}if(chosen==="lemonsqueezy"){const appUrl=config.app?.url;return new LemonSqueezyDriver({...lemonSqueezyConfig(settings.lemonsqueezy),...appUrl?{appUrl}:{}})}const factory=custom.get(chosen);if(!factory)throw new Error(`No payment driver named "${chosen}". Built in: ${BUILT_IN_DRIVERS.join(", ")}${custom.size?`; registered: ${[...custom.keys()].join(", ")}`:""}.`);return factory()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,createHmac,timingSafeEqual}from"node:crypto";import{assertMoney,headerOf,PaymentProviderError,PaymentUnsupportedError,WebhookNotConfiguredError,WebhookSignatureError}from"./types";export const LEMONSQUEEZY_API_URL="https://api.lemonsqueezy.com/v1";const CAPABILITIES=new Set(["customers","refund","checkout","subscriptions","webhooks"]);const SUBSCRIPTION_STATUSES={on_trial:"trialing",active:"active",paused:"paused",past_due:"past_due",unpaid:"unpaid",cancelled:"active",expired:"canceled"};export function summarizeLemonSqueezySubscription(subscription){const{attributes}=subscription;const cancelled=attributes.status==="cancelled"||attributes.cancelled===true;const periodEnd=cancelled?attributes.ends_at:attributes.renews_at;return{id:String(subscription.id),status:SUBSCRIPTION_STATUSES[attributes.status]??"unknown",price:attributes.variant_id!==undefined?{id:String(attributes.variant_id),name:attributes.variant_name??attributes.product_name??null,amount:null,interval:null}:null,currentPeriodEnd:periodEnd?new Date(periodEnd):null,cancelAtPeriodEnd:cancelled&&attributes.status!=="expired",raw:subscription}}export function lemonSqueezySignature(payload,secret){return createHmac("sha256",secret).update(payload,"utf8").digest("hex")}export class LemonSqueezyDriver{name="lemonsqueezy";capabilities=CAPABILITIES;config;fetch;storeCurrency;constructor(config,options={}){if(!config.apiKey)throw new Error("The Lemon Squeezy payment driver needs an API key: set LEMONSQUEEZY_API_KEY or payment.lemonsqueezy.apiKey.");if(!config.storeId)throw new Error("The Lemon Squeezy payment driver needs a store: set LEMONSQUEEZY_STORE_ID or payment.lemonsqueezy.storeId.");this.config=config;this.fetch=options.fetch??fetch}async request(method,path,options={}){const url=new URL(`${LEMONSQUEEZY_API_URL}${path}`);for(const[key,value]of Object.entries(options.query??{}))url.searchParams.set(key,value);const headers={Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/vnd.api+json"};if(options.body!==undefined)headers["Content-Type"]="application/vnd.api+json";const response=await this.fetch(url,{method,headers,body:options.body===undefined?undefined:JSON.stringify(options.body)});const text=await response.text();const body=text?JSON.parse(text):{};if(!response.ok){const error=body.errors?.[0];throw new PaymentProviderError("lemonsqueezy",response.status,error?.detail??error?.title??response.statusText,error?.code??null)}return body}async list(path,filters){const all=[];for(let page=1;;page++){const result=await this.request("GET",path,{query:{...filters,"page[number]":String(page),"page[size]":"100"}});all.push(...result.data??[]);if(page>=(result.meta?.page?.lastPage??1))return all}}store(){return{data:{type:"stores",id:String(this.config.storeId)}}}assertReturnUrl(url,label){let target;try{target=new URL(url)}catch{throw new TypeError(`${label} is not a valid URL: ${url}`)}if(!this.config.appUrl)return;const app=new URL(/^https?:\/\//.test(this.config.appUrl)?this.config.appUrl:`https://${this.config.appUrl}`);if(target.origin!==app.origin)throw new TypeError(`${label} (${target.origin}) is not on the application's origin (${app.origin})`)}currency(){this.storeCurrency??=this.request("GET",`/stores/${encodeURIComponent(this.config.storeId)}`).then((result)=>result.data.attributes.currency.toLowerCase());return this.storeCurrency}async customer(payer){if(!payer.email)throw new TypeError("A Lemon Squeezy customer is identified by email: the payer has none.");const found=await this.request("GET","/customers",{query:{"filter[store_id]":String(this.config.storeId),"filter[email]":payer.email}});const existing=found.data?.[0];if(existing)return{id:String(existing.id),email:existing.attributes.email,name:existing.attributes.name??null};const created=await this.request("POST","/customers",{body:{data:{type:"customers",attributes:{email:payer.email,name:payer.name||payer.email},relationships:{store:this.store()}}}});return{id:String(created.data.id),email:created.data.attributes.email,name:created.data.attributes.name??null}}async charge(){throw new PaymentUnsupportedError("lemonsqueezy","charge","Lemon Squeezy takes every payment on its hosted checkout: use checkout")}async createPayment(){throw new PaymentUnsupportedError("lemonsqueezy","createPayment","Lemon Squeezy takes every payment on its hosted checkout: use checkout")}async refund(paymentId,options={}){const attributes={};if(options.amount){assertMoney(options.amount,"refund amount");const order=await this.request("GET",`/orders/${encodeURIComponent(paymentId)}`);if(order.data.attributes.currency.toLowerCase()!==options.amount.currency.toLowerCase())throw new TypeError(`The refund is in ${options.amount.currency.toUpperCase()}, but the order is in ${order.data.attributes.currency.toUpperCase()}.`);attributes.amount=options.amount.amount}const result=await this.request("POST",`/orders/${encodeURIComponent(paymentId)}/refund`,{body:{data:{type:"orders",id:String(paymentId),...options.amount?{attributes}:{}}}});const order=result.data.attributes;return{id:`${paymentId}:refunded:${order.refunded_amount??0}`,paymentId,status:"succeeded",amount:options.amount?{amount:options.amount.amount,currency:options.amount.currency.toLowerCase()}:null,raw:result.data}}async checkout(payer,request){if(request.mode==="setup")throw new PaymentUnsupportedError("lemonsqueezy","setup checkout","Lemon Squeezy saves a payment method while taking a payment, never on its own");if(request.lines.length!==1)throw new PaymentUnsupportedError("lemonsqueezy",`a checkout with ${request.lines.length} lines`,"a Lemon Squeezy checkout sells one variant");if(request.paymentMethods?.length)throw new PaymentUnsupportedError("lemonsqueezy","choosing payment methods","Lemon Squeezy shows the methods its store settings allow");if(request.cancelUrl&&request.cancelUrl!==request.successUrl)throw new PaymentUnsupportedError("lemonsqueezy","a separate cancelUrl","the hosted checkout has no cancel page");if(request.trialDays)throw new PaymentUnsupportedError("lemonsqueezy","a checkout trial","a Lemon Squeezy trial is set on the subscription variant");this.assertReturnUrl(request.successUrl,"successUrl");const line=request.lines[0];if(!Number.isInteger(line.quantity)||line.quantity<1)throw new TypeError(`A checkout line's quantity must be a positive whole number, got ${line.quantity}`);let variantId;const attributes={};const productOptions={redirect_url:request.successUrl};if("price"in line){variantId=line.price}else{if(request.mode==="subscription")throw new TypeError("A Lemon Squeezy subscription checkout needs a subscription variant: a line priced here has no billing interval.");if(!this.config.customPriceVariantId)throw new TypeError("A checkout line priced here needs a variant to sell it as: set LEMONSQUEEZY_VARIANT_ID or payment.lemonsqueezy.customPriceVariantId.");const currency=await this.currency();if(request.currency&&request.currency.toLowerCase()!==currency)throw new TypeError(`The checkout is in ${request.currency.toUpperCase()}, but the Lemon Squeezy store sells in ${currency.toUpperCase()}.`);const total={amount:line.unitAmount*line.quantity,currency};assertMoney(total,"checkout amount");variantId=this.config.customPriceVariantId;attributes.custom_price=total.amount;productOptions.name=line.quantity===1?line.name:`${line.name} x ${line.quantity}`}const custom={...request.metadata,...request.reference?{reference:request.reference}:{},stacks_user_id:String(payer.id)};const checkoutData={custom};if(payer.email)checkoutData.email=payer.email;if(payer.name)checkoutData.name=payer.name;if("price"in line&&line.quantity>1)checkoutData.variant_quantities=[{variant_id:Number(variantId),quantity:line.quantity}];const result=await this.request("POST","/checkouts",{body:{data:{type:"checkouts",attributes:{...attributes,product_options:productOptions,checkout_options:{discount:request.allowPromotionCodes===true},checkout_data:checkoutData,...this.config.testMode?{test_mode:true}:{}},relationships:{store:this.store(),variant:{data:{type:"variants",id:String(variantId)}}}}}});return{id:String(result.data.id),url:result.data.attributes.url,expiresAt:result.data.attributes.expires_at?new Date(result.data.attributes.expires_at):null,raw:result.data}}async paymentMethods(){throw new PaymentUnsupportedError("lemonsqueezy","paymentMethods","Lemon Squeezy keeps the card on the subscription; send the payer to its update_payment_method URL")}async removePaymentMethod(){throw new PaymentUnsupportedError("lemonsqueezy","removePaymentMethod","Lemon Squeezy keeps the card on the subscription; send the payer to its update_payment_method URL")}async subscribe(){throw new PaymentUnsupportedError("lemonsqueezy","subscribe","a Lemon Squeezy subscription starts at checkout: use checkout with a subscription variant")}async cancelSubscription(subscriptionId,options={}){if(!options.atPeriodEnd)throw new PaymentUnsupportedError("lemonsqueezy","an immediate cancellation","Lemon Squeezy cancels at the end of the billing period: pass { atPeriodEnd: true }");const result=await this.request("DELETE",`/subscriptions/${encodeURIComponent(subscriptionId)}`);return summarizeLemonSqueezySubscription(result.data)}async subscriptions(payer){if(!payer.email)throw new TypeError("Lemon Squeezy finds a payer's subscriptions by email: the payer has none.");const subscriptions=await this.list("/subscriptions",{"filter[store_id]":String(this.config.storeId),"filter[user_email]":payer.email});return subscriptions.map(summarizeLemonSqueezySubscription)}async verifyWebhook(request){if(!this.config.webhookSecret)throw new WebhookNotConfiguredError("lemonsqueezy","Lemon Squeezy webhooks cannot be verified without the signing secret: set LEMONSQUEEZY_WEBHOOK_SECRET or payment.lemonsqueezy.webhookSecret.");const given=headerOf(request.headers,"x-signature");if(!given)throw new WebhookSignatureError("lemonsqueezy","there is no X-Signature header");const expected=Buffer.from(lemonSqueezySignature(request.payload,this.config.webhookSecret));const actual=Buffer.from(given.trim());if(actual.length!==expected.length||!timingSafeEqual(actual,expected))throw new WebhookSignatureError("lemonsqueezy","it is signed with another secret");let notification;try{notification=JSON.parse(request.payload)}catch{throw new WebhookSignatureError("lemonsqueezy","the body is not JSON")}const id=`${notification.meta?.event_name??"unknown"}:${createHash("sha256").update(request.payload,"utf8").digest("hex").slice(0,32)}`;return[this.translate(id,notification)]}translate(id,notification){const name=notification.meta?.event_name??"";const data=notification.data;const attributes=data?.attributes??{};const reference=typeof notification.meta?.custom_data?.reference==="string"?notification.meta.custom_data.reference:null;const money=(amount)=>typeof amount==="number"&&typeof attributes.currency==="string"?{amount,currency:attributes.currency.toLowerCase()}:null;const base={provider:this.name,id,providerType:name,reference:data?.id!==undefined?String(data.id):null,merchantReference:reference,raw:notification};if(name==="order_created"){const type=attributes.status==="paid"?"payment.succeeded":attributes.status==="failed"?"payment.failed":"unknown";return{...base,type,amount:money(attributes.total),reason:null}}if(name==="order_refunded"){const refundedTotal=money(attributes.refunded_amount);return{...base,type:"refund.succeeded",amount:null,...refundedTotal?{refundedTotal}:{},reason:null}}const types={subscription_created:"subscription.created",subscription_updated:"subscription.updated",subscription_cancelled:"subscription.updated",subscription_resumed:"subscription.updated",subscription_paused:"subscription.updated",subscription_unpaused:"subscription.updated",subscription_expired:"subscription.canceled",subscription_payment_success:"invoice.paid",subscription_payment_recovered:"invoice.paid",subscription_payment_failed:"invoice.payment_failed"};const type=types[name]??"unknown";return{...base,type,amount:type.startsWith("invoice.")?money(attributes.total):null,reason:null}}acknowledgeWebhook(){return new Response(null,{status:200})}}
|
|
1
|
+
import{createHash,createHmac,timingSafeEqual}from"node:crypto";import{assertMoney,headerOf,PaymentProviderError,PaymentUnsupportedError,WebhookNotConfiguredError,WebhookSignatureError}from"./types";export const LEMONSQUEEZY_API_URL="https://api.lemonsqueezy.com/v1";const CAPABILITIES=new Set(["customers","refund","checkout","subscriptions","webhooks"]);const SUBSCRIPTION_STATUSES={on_trial:"trialing",active:"active",paused:"paused",past_due:"past_due",unpaid:"unpaid",cancelled:"active",expired:"canceled"};export function summarizeLemonSqueezySubscription(subscription){const{attributes}=subscription;const cancelled=attributes.status==="cancelled"||attributes.cancelled===true;const periodEnd=cancelled?attributes.ends_at:attributes.renews_at;return{id:String(subscription.id),status:SUBSCRIPTION_STATUSES[attributes.status]??"unknown",price:attributes.variant_id!==undefined?{id:String(attributes.variant_id),name:attributes.variant_name??attributes.product_name??null,amount:null,interval:null}:null,currentPeriodEnd:periodEnd?new Date(periodEnd):null,cancelAtPeriodEnd:cancelled&&attributes.status!=="expired",raw:subscription}}export function lemonSqueezySignature(payload,secret){return createHmac("sha256",secret).update(payload,"utf8").digest("hex")}export class LemonSqueezyDriver{name="lemonsqueezy";capabilities=CAPABILITIES;config;fetch;storeCurrency;constructor(config,options={}){if(!config.apiKey)throw new Error("The Lemon Squeezy payment driver needs an API key: set LEMONSQUEEZY_API_KEY or payment.lemonsqueezy.apiKey.");if(!config.storeId)throw new Error("The Lemon Squeezy payment driver needs a store: set LEMONSQUEEZY_STORE_ID or payment.lemonsqueezy.storeId.");this.config=config;this.fetch=options.fetch??fetch}async request(method,path,options={}){const url=new URL(`${LEMONSQUEEZY_API_URL}${path}`);for(const[key,value]of Object.entries(options.query??{}))url.searchParams.set(key,value);const headers={Authorization:`Bearer ${this.config.apiKey}`,Accept:"application/vnd.api+json"};if(options.body!==undefined)headers["Content-Type"]="application/vnd.api+json";const response=await this.fetch(url,{method,headers,body:options.body===undefined?undefined:JSON.stringify(options.body)});const text=await response.text();const body=text?JSON.parse(text):{};if(!response.ok){const error=body.errors?.[0];throw new PaymentProviderError("lemonsqueezy",response.status,error?.detail??error?.title??response.statusText,error?.code??null)}return body}async list(path,filters){const all=[];for(let page=1;;page++){const result=await this.request("GET",path,{query:{...filters,"page[number]":String(page),"page[size]":"100"}});all.push(...result.data??[]);if(page>=(result.meta?.page?.lastPage??1))return all}}store(){return{data:{type:"stores",id:String(this.config.storeId)}}}assertReturnUrl(url,label){let target;try{target=new URL(url)}catch{throw new TypeError(`${label} is not a valid URL: ${url}`)}if(!this.config.appUrl)return;const app=new URL(/^https?:\/\//.test(this.config.appUrl)?this.config.appUrl:`https://${this.config.appUrl}`);if(target.origin!==app.origin)throw new TypeError(`${label} (${target.origin}) is not on the application's origin (${app.origin})`)}currency(){this.storeCurrency??=this.request("GET",`/stores/${encodeURIComponent(this.config.storeId)}`).then((result)=>result.data.attributes.currency.toLowerCase());return this.storeCurrency}async customer(payer){if(!payer.email)throw new TypeError("A Lemon Squeezy customer is identified by email: the payer has none.");const found=await this.request("GET","/customers",{query:{"filter[store_id]":String(this.config.storeId),"filter[email]":payer.email}});const existing=found.data?.[0];if(existing)return{id:String(existing.id),email:existing.attributes.email,name:existing.attributes.name??null};const created=await this.request("POST","/customers",{body:{data:{type:"customers",attributes:{email:payer.email,name:payer.name||payer.email},relationships:{store:this.store()}}}});return{id:String(created.data.id),email:created.data.attributes.email,name:created.data.attributes.name??null}}async charge(){throw new PaymentUnsupportedError("lemonsqueezy","charge","Lemon Squeezy takes every payment on its hosted checkout: use checkout")}async createPayment(){throw new PaymentUnsupportedError("lemonsqueezy","createPayment","Lemon Squeezy takes every payment on its hosted checkout: use checkout")}async refund(paymentId,options={}){const attributes={};if(options.amount){assertMoney(options.amount,"refund amount");const order=await this.request("GET",`/orders/${encodeURIComponent(paymentId)}`);if(order.data.attributes.currency.toLowerCase()!==options.amount.currency.toLowerCase())throw new TypeError(`The refund is in ${options.amount.currency.toUpperCase()}, but the order is in ${order.data.attributes.currency.toUpperCase()}.`);attributes.amount=options.amount.amount}const result=await this.request("POST",`/orders/${encodeURIComponent(paymentId)}/refund`,{body:{data:{type:"orders",id:String(paymentId),...options.amount?{attributes}:{}}}});const order=result.data.attributes;return{id:`${paymentId}:refunded:${order.refunded_amount??0}`,paymentId,status:"succeeded",amount:options.amount?{amount:options.amount.amount,currency:options.amount.currency.toLowerCase()}:null,raw:result.data}}async checkout(payer,request){if(request.idempotencyKey!==undefined)throw new PaymentUnsupportedError("lemonsqueezy","a checkout idempotency key");if(request.mode==="setup")throw new PaymentUnsupportedError("lemonsqueezy","setup checkout","Lemon Squeezy saves a payment method while taking a payment, never on its own");if(request.lines.length!==1)throw new PaymentUnsupportedError("lemonsqueezy",`a checkout with ${request.lines.length} lines`,"a Lemon Squeezy checkout sells one variant");if(request.paymentMethods?.length)throw new PaymentUnsupportedError("lemonsqueezy","choosing payment methods","Lemon Squeezy shows the methods its store settings allow");if(request.cancelUrl&&request.cancelUrl!==request.successUrl)throw new PaymentUnsupportedError("lemonsqueezy","a separate cancelUrl","the hosted checkout has no cancel page");if(request.trialDays)throw new PaymentUnsupportedError("lemonsqueezy","a checkout trial","a Lemon Squeezy trial is set on the subscription variant");this.assertReturnUrl(request.successUrl,"successUrl");const line=request.lines[0];if(!Number.isInteger(line.quantity)||line.quantity<1)throw new TypeError(`A checkout line's quantity must be a positive whole number, got ${line.quantity}`);let variantId;const attributes={};const productOptions={redirect_url:request.successUrl};if("price"in line){variantId=line.price}else{if(request.mode==="subscription")throw new TypeError("A Lemon Squeezy subscription checkout needs a subscription variant: a line priced here has no billing interval.");if(!this.config.customPriceVariantId)throw new TypeError("A checkout line priced here needs a variant to sell it as: set LEMONSQUEEZY_VARIANT_ID or payment.lemonsqueezy.customPriceVariantId.");const currency=await this.currency();if(request.currency&&request.currency.toLowerCase()!==currency)throw new TypeError(`The checkout is in ${request.currency.toUpperCase()}, but the Lemon Squeezy store sells in ${currency.toUpperCase()}.`);const total={amount:line.unitAmount*line.quantity,currency};assertMoney(total,"checkout amount");variantId=this.config.customPriceVariantId;attributes.custom_price=total.amount;productOptions.name=line.quantity===1?line.name:`${line.name} x ${line.quantity}`}const custom={...request.metadata,...request.reference?{reference:request.reference}:{},stacks_user_id:String(payer.id)};const checkoutData={custom};if(payer.email)checkoutData.email=payer.email;if(payer.name)checkoutData.name=payer.name;if("price"in line&&line.quantity>1)checkoutData.variant_quantities=[{variant_id:Number(variantId),quantity:line.quantity}];const result=await this.request("POST","/checkouts",{body:{data:{type:"checkouts",attributes:{...attributes,product_options:productOptions,checkout_options:{discount:request.allowPromotionCodes===true},checkout_data:checkoutData,...this.config.testMode?{test_mode:true}:{}},relationships:{store:this.store(),variant:{data:{type:"variants",id:String(variantId)}}}}}});return{id:String(result.data.id),url:result.data.attributes.url,expiresAt:result.data.attributes.expires_at?new Date(result.data.attributes.expires_at):null,raw:result.data}}async paymentMethods(){throw new PaymentUnsupportedError("lemonsqueezy","paymentMethods","Lemon Squeezy keeps the card on the subscription; send the payer to its update_payment_method URL")}async removePaymentMethod(){throw new PaymentUnsupportedError("lemonsqueezy","removePaymentMethod","Lemon Squeezy keeps the card on the subscription; send the payer to its update_payment_method URL")}async subscribe(){throw new PaymentUnsupportedError("lemonsqueezy","subscribe","a Lemon Squeezy subscription starts at checkout: use checkout with a subscription variant")}async cancelSubscription(subscriptionId,options={}){if(!options.atPeriodEnd)throw new PaymentUnsupportedError("lemonsqueezy","an immediate cancellation","Lemon Squeezy cancels at the end of the billing period: pass { atPeriodEnd: true }");const result=await this.request("DELETE",`/subscriptions/${encodeURIComponent(subscriptionId)}`);return summarizeLemonSqueezySubscription(result.data)}async subscriptions(payer){if(!payer.email)throw new TypeError("Lemon Squeezy finds a payer's subscriptions by email: the payer has none.");const subscriptions=await this.list("/subscriptions",{"filter[store_id]":String(this.config.storeId),"filter[user_email]":payer.email});return subscriptions.map(summarizeLemonSqueezySubscription)}async verifyWebhook(request){if(!this.config.webhookSecret)throw new WebhookNotConfiguredError("lemonsqueezy","Lemon Squeezy webhooks cannot be verified without the signing secret: set LEMONSQUEEZY_WEBHOOK_SECRET or payment.lemonsqueezy.webhookSecret.");const given=headerOf(request.headers,"x-signature");if(!given)throw new WebhookSignatureError("lemonsqueezy","there is no X-Signature header");const expected=Buffer.from(lemonSqueezySignature(request.payload,this.config.webhookSecret));const actual=Buffer.from(given.trim());if(actual.length!==expected.length||!timingSafeEqual(actual,expected))throw new WebhookSignatureError("lemonsqueezy","it is signed with another secret");let notification;try{notification=JSON.parse(request.payload)}catch{throw new WebhookSignatureError("lemonsqueezy","the body is not JSON")}const id=`${notification.meta?.event_name??"unknown"}:${createHash("sha256").update(request.payload,"utf8").digest("hex").slice(0,32)}`;return[this.translate(id,notification)]}translate(id,notification){const name=notification.meta?.event_name??"";const data=notification.data;const attributes=data?.attributes??{};const reference=typeof notification.meta?.custom_data?.reference==="string"?notification.meta.custom_data.reference:null;const money=(amount)=>typeof amount==="number"&&typeof attributes.currency==="string"?{amount,currency:attributes.currency.toLowerCase()}:null;const base={provider:this.name,id,providerType:name,reference:data?.id!==undefined?String(data.id):null,merchantReference:reference,raw:notification};if(name==="order_created"){const type=attributes.status==="paid"?"payment.succeeded":attributes.status==="failed"?"payment.failed":"unknown";return{...base,type,amount:money(attributes.total),reason:null}}if(name==="order_refunded"){const refundedTotal=money(attributes.refunded_amount);return{...base,type:"refund.succeeded",amount:null,...refundedTotal?{refundedTotal}:{},reason:null}}const types={subscription_created:"subscription.created",subscription_updated:"subscription.updated",subscription_cancelled:"subscription.updated",subscription_resumed:"subscription.updated",subscription_paused:"subscription.updated",subscription_unpaused:"subscription.updated",subscription_expired:"subscription.canceled",subscription_payment_success:"invoice.paid",subscription_payment_recovered:"invoice.paid",subscription_payment_failed:"invoice.payment_failed"};const type=types[name]??"unknown";return{...base,type,amount:type.startsWith("invoice.")?money(attributes.total):null,reason:null}}acknowledgeWebhook(){return new Response(null,{status:200})}}
|
package/dist/driver/paddle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHmac,timingSafeEqual}from"node:crypto";import{assertMoney,headerOf,PaymentProviderError,PaymentUnsupportedError,WebhookNotConfiguredError,WebhookSignatureError}from"./types";export const PADDLE_API_VERSION="1";const CAPABILITIES=new Set(["customers","createPayment","refund","checkout","paymentMethods","subscriptions","webhooks"]);export const PADDLE_SUCCESS_URL_KEY="stacks_success_url";const TRANSACTION_ID=/^txn_[a-z\d]{26}$/;const CUSTOMER_ID_IN_DETAIL=/ctm_[a-z\d]{26}/;export function paddleRefundStatus(status){switch(status){case"approved":return"succeeded";case"rejected":return"failed";case"reversed":return"canceled";default:return"pending"}}const SUBSCRIPTION_STATUSES=new Set(["active","trialing","past_due","paused","canceled"]);const INTERVALS=new Set(["day","week","month","year"]);export function summarizePaddleSubscription(subscription){const price=subscription.items?.[0]?.price;const interval=price?.billing_cycle?.interval;return{id:subscription.id,status:SUBSCRIPTION_STATUSES.has(subscription.status)?subscription.status:"unknown",price:price?{id:price.id,name:price.name??price.description??null,amount:price.unit_price?{amount:Number(price.unit_price.amount),currency:price.unit_price.currency_code.toLowerCase()}:null,interval:interval&&INTERVALS.has(interval)?interval:null}:null,currentPeriodEnd:subscription.current_billing_period?.ends_at?new Date(subscription.current_billing_period.ends_at):null,cancelAtPeriodEnd:subscription.scheduled_change?.action==="cancel",raw:subscription}}export function parsePaddleSignature(header){let timestamp=null;const signatures=[];for(const part of header.split(";")){const separator=part.indexOf("=");if(separator===-1)continue;const key=part.slice(0,separator).trim();const value=part.slice(separator+1).trim();if(key==="ts"&&/^\d+$/.test(value))timestamp=Number(value);else if(key==="h1"&&value)signatures.push(value)}return timestamp===null||signatures.length===0?null:{timestamp,signatures}}export function paddleSignature(timestamp,payload,secret){return createHmac("sha256",secret).update(`${timestamp}:${payload}`,"utf8").digest("hex")}export class PaddleDriver{name="paddle";capabilities=CAPABILITIES;config;fetch;now;constructor(config,options={}){if(!config.apiKey)throw new Error("The Paddle payment driver needs an API key: set PADDLE_API_KEY or payment.paddle.apiKey.");const keyEnvironment=config.apiKey.startsWith("pdl_live_")?"live":config.apiKey.startsWith("pdl_sdbx_")?"sandbox":null;if(keyEnvironment&&keyEnvironment!==config.environment)throw new Error(`The Paddle API key is a ${keyEnvironment} key, but payment.paddle.environment is ${config.environment}.`);this.config=config;this.fetch=options.fetch??fetch;this.now=options.now??Date.now}get environment(){return this.config.environment}get clientToken(){return this.config.clientToken||undefined}get baseUrl(){return this.config.environment==="live"?"https://api.paddle.com":"https://sandbox-api.paddle.com"}async request(method,path,options={}){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(options.query??{}))url.searchParams.set(key,value);const headers={Authorization:`Bearer ${this.config.apiKey}`,"Paddle-Version":PADDLE_API_VERSION,Accept:"application/json"};if(options.body!==undefined)headers["Content-Type"]="application/json";const response=await this.fetch(url,{method,headers,body:options.body===undefined?undefined:JSON.stringify(options.body)});if(response.status===204)return;const text=await response.text();const body=text?JSON.parse(text):undefined;if(!response.ok){const error=body?.error;throw new PaymentProviderError("paddle",response.status,error?.detail??response.statusText,error?.code??null)}return body.data}assertReturnUrl(url,label){let target;try{target=new URL(url)}catch{throw new TypeError(`${label} is not a valid URL: ${url}`)}if(!this.config.appUrl)return;const app=new URL(/^https?:\/\//.test(this.config.appUrl)?this.config.appUrl:`https://${this.config.appUrl}`);if(target.origin!==app.origin)throw new TypeError(`${label} (${target.origin}) is not on the application's origin (${app.origin})`)}pricedLine(name,amount,quantity){assertMoney(amount);return{quantity,price:{description:name.length>=2?name:`${name} `.padEnd(2," "),name,tax_mode:"internal",unit_price:{amount:String(amount.amount),currency_code:amount.currency.toUpperCase()},product:{name,tax_category:this.config.taxCategory??"standard"}}}}async customer(payer){if(!payer.email)throw new TypeError("A Paddle customer is identified by email: the payer has none.");const found=await this.request("GET","/customers",{query:{email:payer.email}});if(found?.[0])return{id:found[0].id,email:found[0].email,name:found[0].name??null};try{const created=await this.request("POST","/customers",{body:{email:payer.email,...payer.name?{name:payer.name}:{},custom_data:{stacks_user_id:String(payer.id)}}});return{id:created.id,email:created.email,name:created.name??null}}catch(error){const existing=error instanceof PaymentProviderError&&error.code==="customer_already_exists"?CUSTOMER_ID_IN_DETAIL.exec(error.message)?.[0]:undefined;if(!existing)throw error;const customer=await this.request("GET",`/customers/${existing}`);return{id:customer.id,email:customer.email,name:customer.name??null}}}async charge(){throw new PaymentUnsupportedError("paddle","charge","Paddle takes every payment through its checkout; open one with createPayment or checkout")}async createPayment(payer,amount,options={}){if(options.returnUrl)this.assertReturnUrl(options.returnUrl,"returnUrl");const customer=await this.customer(payer);const transaction=await this.request("POST","/transactions",{body:{items:[this.pricedLine(options.description??"Payment",amount,1)],customer_id:customer.id,currency_code:amount.currency.toUpperCase(),collection_mode:"automatic",custom_data:{...options.metadata,...options.reference?{reference:options.reference}:{}}}});return{id:transaction.id,status:"requires_payment_method",amount:{amount:amount.amount,currency:amount.currency.toLowerCase()},clientConfirmation:{provider:"paddle",transactionId:transaction.id,...options.returnUrl?{successUrl:options.returnUrl}:{}},raw:transaction}}async refund(paymentId,options={}){const reason=options.reason??"requested_by_customer";let body={action:"refund",transaction_id:paymentId,reason,type:"full"};if(options.amount){assertMoney(options.amount,"refund amount");const transaction=await this.request("GET",`/transactions/${encodeURIComponent(paymentId)}`);const currency=(transaction.details?.totals?.currency_code??transaction.currency_code??"").toLowerCase();if(currency&¤cy!==options.amount.currency.toLowerCase())throw new TypeError(`The refund is in ${options.amount.currency.toUpperCase()}, but the transaction is in ${currency.toUpperCase()}.`);const items=[];let left=options.amount.amount;for(const line of transaction.details?.line_items??[]){if(left<=0)break;const total=Number(line.totals?.total??0);if(total<=0)continue;const take=Math.min(left,total);items.push(take===total?{item_id:line.id,type:"full"}:{item_id:line.id,type:"partial",amount:String(take)});left-=take}if(left>0)throw new TypeError(`The refund of ${options.amount.amount} is more than the transaction's ${options.amount.amount-left}.`);body={action:"refund",transaction_id:paymentId,reason,type:"partial",tax_mode:"internal",items}}const adjustment=await this.request("POST","/adjustments",{body});const total=adjustment.totals?.total;const currency=adjustment.totals?.currency_code??adjustment.currency_code;return{id:adjustment.id,paymentId,status:paddleRefundStatus(adjustment.status),amount:total!==undefined&¤cy?{amount:Number(total),currency:currency.toLowerCase()}:null,raw:adjustment}}async checkout(payer,request){if(request.mode==="setup")throw new PaymentUnsupportedError("paddle","setup checkout","Paddle saves a payment method while taking a payment, never on its own");if(request.paymentMethods?.length)throw new PaymentUnsupportedError("paddle","choosing payment methods","Paddle shows the methods its checkout settings allow");if(request.cancelUrl&&request.cancelUrl!==request.successUrl)throw new PaymentUnsupportedError("paddle","a separate cancelUrl","Paddle checkout opens over your page, and closing it leaves the payer there");if(request.allowPromotionCodes)throw new PaymentUnsupportedError("paddle","promotion codes","whether the discount field shows is a Paddle checkout setting, not a per-checkout option");if(request.trialDays)throw new PaymentUnsupportedError("paddle","a checkout trial","a Paddle trial is part of the price: set its trial period on the price");this.assertReturnUrl(request.successUrl,"successUrl");const items=request.lines.map((line)=>{if("price"in line)return{price_id:line.price,quantity:line.quantity};if(request.mode==="subscription")throw new TypeError("A Paddle subscription checkout needs catalog prices (pri_...) with a billing cycle: a line priced here has none.");if(!request.currency)throw new TypeError("A checkout line priced with unitAmount needs the checkout's currency.");return this.pricedLine(line.name,{amount:line.unitAmount,currency:request.currency},line.quantity)});const customer=await this.customer(payer);const transaction=await this.request("POST","/transactions",{body:{items,customer_id:customer.id,...request.currency?{currency_code:request.currency.toUpperCase()}:{},collection_mode:"automatic",custom_data:{...request.metadata,...request.reference?{reference:request.reference}:{},[PADDLE_SUCCESS_URL_KEY]:request.successUrl},checkout:{url:null}}});if(!transaction.checkout?.url)throw new Error("Paddle returned no payment link: set a default payment link in Paddle (Checkout > Checkout settings), pointing at /payments/checkout.");return{id:transaction.id,url:transaction.checkout.url,expiresAt:null,raw:transaction}}async checkoutSuccessUrl(transactionId){if(!TRANSACTION_ID.test(transactionId))throw new TypeError("Not a Paddle transaction id.");const transaction=await this.request("GET",`/transactions/${transactionId}`);const successUrl=transaction.custom_data?.[PADDLE_SUCCESS_URL_KEY];if(typeof successUrl!=="string")return null;this.assertReturnUrl(successUrl,"successUrl");return successUrl}async paymentMethods(payer){const customer=await this.customer(payer);const methods=await this.request("GET",`/customers/${customer.id}/payment-methods`);return(methods??[]).map((method)=>({id:method.id,type:method.type,brand:method.card?.type??null,last4:method.card?.last4??null,expMonth:method.card?.expiry_month??null,expYear:method.card?.expiry_year??null,isDefault:false,raw:method}))}async removePaymentMethod(payer,paymentMethodId){const customer=await this.customer(payer);await this.request("DELETE",`/customers/${customer.id}/payment-methods/${encodeURIComponent(paymentMethodId)}`)}async subscribe(){throw new PaymentUnsupportedError("paddle","subscribe",'a Paddle subscription starts at checkout: use checkout with mode "subscription"')}async cancelSubscription(subscriptionId,options={}){const subscription=await this.request("POST",`/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`,{body:{effective_from:options.atPeriodEnd?"next_billing_period":"immediately"}});return summarizePaddleSubscription(subscription)}async subscriptions(payer){const customer=await this.customer(payer);const subscriptions=await this.request("GET","/subscriptions",{query:{customer_id:customer.id}});return(subscriptions??[]).map(summarizePaddleSubscription)}async verifyWebhook(request){if(!this.config.webhookSecret)throw new WebhookNotConfiguredError("paddle","Paddle webhooks cannot be verified without the endpoint secret key: set PADDLE_WEBHOOK_SECRET or payment.paddle.webhookSecret.");const header=headerOf(request.headers,"paddle-signature");if(!header)throw new WebhookSignatureError("paddle","there is no Paddle-Signature header");const signature=parsePaddleSignature(header);if(!signature)throw new WebhookSignatureError("paddle","the Paddle-Signature header is not ts=...;h1=...");const tolerance=this.config.webhookTolerance??5;if(Math.abs(this.now()/1000-signature.timestamp)>tolerance)throw new WebhookSignatureError("paddle",`the signature is more than ${tolerance} seconds from now`);const expected=Buffer.from(paddleSignature(signature.timestamp,request.payload,this.config.webhookSecret));const matches=signature.signatures.some((given)=>{const actual=Buffer.from(given);return actual.length===expected.length&&timingSafeEqual(actual,expected)});if(!matches)throw new WebhookSignatureError("paddle","it is signed with another key");let notification;try{notification=JSON.parse(request.payload)}catch{throw new WebhookSignatureError("paddle","the body is not JSON")}return[this.translate(notification)]}translate(notification){const data=notification.data??{};const base={provider:this.name,id:notification.event_id,providerType:notification.event_type,merchantReference:typeof data.custom_data?.reference==="string"?data.custom_data.reference:null,raw:notification};if(notification.event_type.startsWith("transaction.")){const totals=data.details?.totals;const amount=totals?.grand_total!==undefined&&(totals.currency_code??data.currency_code)?{amount:Number(totals.grand_total),currency:String(totals.currency_code??data.currency_code).toLowerCase()}:null;const type=notification.event_type==="transaction.completed"?"payment.succeeded":notification.event_type==="transaction.payment_failed"?"payment.failed":notification.event_type==="transaction.canceled"?"payment.canceled":"unknown";const lastAttempt=Array.isArray(data.payments)?data.payments.at(-1):undefined;return{...base,type,reference:typeof data.id==="string"?data.id:null,amount,reason:type==="payment.failed"?lastAttempt?.error_code??null:null}}if(notification.event_type==="adjustment.created"||notification.event_type==="adjustment.updated"){const adjustment=data;const settled=adjustment.action==="refund"&&(adjustment.status==="approved"||adjustment.status==="rejected");const currency=adjustment.totals?.currency_code??adjustment.currency_code;return{...base,id:settled?`adjustment:${adjustment.id}:${adjustment.status}`:notification.event_id,type:settled?adjustment.status==="approved"?"refund.succeeded":"refund.failed":"unknown",reference:adjustment.transaction_id??null,amount:adjustment.totals?.total!==undefined&¤cy?{amount:Number(adjustment.totals.total),currency:currency.toLowerCase()}:null,reason:adjustment.status==="rejected"?adjustment.reason??null:null}}const subscriptionTypes={"subscription.created":"subscription.created","subscription.canceled":"subscription.canceled","subscription.updated":"subscription.updated","subscription.activated":"subscription.updated","subscription.trialing":"subscription.updated","subscription.past_due":"subscription.updated","subscription.paused":"subscription.updated","subscription.resumed":"subscription.updated"};return{...base,type:subscriptionTypes[notification.event_type]??"unknown",reference:typeof data.id==="string"?data.id:null,amount:null,reason:null}}acknowledgeWebhook(){return new Response(null,{status:200})}}
|
|
1
|
+
import{createHmac,timingSafeEqual}from"node:crypto";import{assertMoney,headerOf,PaymentProviderError,PaymentUnsupportedError,WebhookNotConfiguredError,WebhookSignatureError}from"./types";export const PADDLE_API_VERSION="1";const CAPABILITIES=new Set(["customers","createPayment","refund","checkout","paymentMethods","subscriptions","webhooks"]);export const PADDLE_SUCCESS_URL_KEY="stacks_success_url";const TRANSACTION_ID=/^txn_[a-z\d]{26}$/;const CUSTOMER_ID_IN_DETAIL=/ctm_[a-z\d]{26}/;export function paddleRefundStatus(status){switch(status){case"approved":return"succeeded";case"rejected":return"failed";case"reversed":return"canceled";default:return"pending"}}const SUBSCRIPTION_STATUSES=new Set(["active","trialing","past_due","paused","canceled"]);const INTERVALS=new Set(["day","week","month","year"]);export function summarizePaddleSubscription(subscription){const price=subscription.items?.[0]?.price;const interval=price?.billing_cycle?.interval;return{id:subscription.id,status:SUBSCRIPTION_STATUSES.has(subscription.status)?subscription.status:"unknown",price:price?{id:price.id,name:price.name??price.description??null,amount:price.unit_price?{amount:Number(price.unit_price.amount),currency:price.unit_price.currency_code.toLowerCase()}:null,interval:interval&&INTERVALS.has(interval)?interval:null}:null,currentPeriodEnd:subscription.current_billing_period?.ends_at?new Date(subscription.current_billing_period.ends_at):null,cancelAtPeriodEnd:subscription.scheduled_change?.action==="cancel",raw:subscription}}export function parsePaddleSignature(header){let timestamp=null;const signatures=[];for(const part of header.split(";")){const separator=part.indexOf("=");if(separator===-1)continue;const key=part.slice(0,separator).trim();const value=part.slice(separator+1).trim();if(key==="ts"&&/^\d+$/.test(value))timestamp=Number(value);else if(key==="h1"&&value)signatures.push(value)}return timestamp===null||signatures.length===0?null:{timestamp,signatures}}export function paddleSignature(timestamp,payload,secret){return createHmac("sha256",secret).update(`${timestamp}:${payload}`,"utf8").digest("hex")}export class PaddleDriver{name="paddle";capabilities=CAPABILITIES;config;fetch;now;constructor(config,options={}){if(!config.apiKey)throw new Error("The Paddle payment driver needs an API key: set PADDLE_API_KEY or payment.paddle.apiKey.");const keyEnvironment=config.apiKey.startsWith("pdl_live_")?"live":config.apiKey.startsWith("pdl_sdbx_")?"sandbox":null;if(keyEnvironment&&keyEnvironment!==config.environment)throw new Error(`The Paddle API key is a ${keyEnvironment} key, but payment.paddle.environment is ${config.environment}.`);this.config=config;this.fetch=options.fetch??fetch;this.now=options.now??Date.now}get environment(){return this.config.environment}get clientToken(){return this.config.clientToken||undefined}get baseUrl(){return this.config.environment==="live"?"https://api.paddle.com":"https://sandbox-api.paddle.com"}async request(method,path,options={}){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(options.query??{}))url.searchParams.set(key,value);const headers={Authorization:`Bearer ${this.config.apiKey}`,"Paddle-Version":PADDLE_API_VERSION,Accept:"application/json"};if(options.body!==undefined)headers["Content-Type"]="application/json";const response=await this.fetch(url,{method,headers,body:options.body===undefined?undefined:JSON.stringify(options.body)});if(response.status===204)return;const text=await response.text();const body=text?JSON.parse(text):undefined;if(!response.ok){const error=body?.error;throw new PaymentProviderError("paddle",response.status,error?.detail??response.statusText,error?.code??null)}return body.data}assertReturnUrl(url,label){let target;try{target=new URL(url)}catch{throw new TypeError(`${label} is not a valid URL: ${url}`)}if(!this.config.appUrl)return;const app=new URL(/^https?:\/\//.test(this.config.appUrl)?this.config.appUrl:`https://${this.config.appUrl}`);if(target.origin!==app.origin)throw new TypeError(`${label} (${target.origin}) is not on the application's origin (${app.origin})`)}pricedLine(name,amount,quantity){assertMoney(amount);return{quantity,price:{description:name.length>=2?name:`${name} `.padEnd(2," "),name,tax_mode:"internal",unit_price:{amount:String(amount.amount),currency_code:amount.currency.toUpperCase()},product:{name,tax_category:this.config.taxCategory??"standard"}}}}async customer(payer){if(!payer.email)throw new TypeError("A Paddle customer is identified by email: the payer has none.");const found=await this.request("GET","/customers",{query:{email:payer.email}});if(found?.[0])return{id:found[0].id,email:found[0].email,name:found[0].name??null};try{const created=await this.request("POST","/customers",{body:{email:payer.email,...payer.name?{name:payer.name}:{},custom_data:{stacks_user_id:String(payer.id)}}});return{id:created.id,email:created.email,name:created.name??null}}catch(error){const existing=error instanceof PaymentProviderError&&error.code==="customer_already_exists"?CUSTOMER_ID_IN_DETAIL.exec(error.message)?.[0]:undefined;if(!existing)throw error;const customer=await this.request("GET",`/customers/${existing}`);return{id:customer.id,email:customer.email,name:customer.name??null}}}async charge(){throw new PaymentUnsupportedError("paddle","charge","Paddle takes every payment through its checkout; open one with createPayment or checkout")}async createPayment(payer,amount,options={}){if(options.returnUrl)this.assertReturnUrl(options.returnUrl,"returnUrl");const customer=await this.customer(payer);const transaction=await this.request("POST","/transactions",{body:{items:[this.pricedLine(options.description??"Payment",amount,1)],customer_id:customer.id,currency_code:amount.currency.toUpperCase(),collection_mode:"automatic",custom_data:{...options.metadata,...options.reference?{reference:options.reference}:{}}}});return{id:transaction.id,status:"requires_payment_method",amount:{amount:amount.amount,currency:amount.currency.toLowerCase()},clientConfirmation:{provider:"paddle",transactionId:transaction.id,...options.returnUrl?{successUrl:options.returnUrl}:{}},raw:transaction}}async refund(paymentId,options={}){const reason=options.reason??"requested_by_customer";let body={action:"refund",transaction_id:paymentId,reason,type:"full"};if(options.amount){assertMoney(options.amount,"refund amount");const transaction=await this.request("GET",`/transactions/${encodeURIComponent(paymentId)}`);const currency=(transaction.details?.totals?.currency_code??transaction.currency_code??"").toLowerCase();if(currency&¤cy!==options.amount.currency.toLowerCase())throw new TypeError(`The refund is in ${options.amount.currency.toUpperCase()}, but the transaction is in ${currency.toUpperCase()}.`);const items=[];let left=options.amount.amount;for(const line of transaction.details?.line_items??[]){if(left<=0)break;const total=Number(line.totals?.total??0);if(total<=0)continue;const take=Math.min(left,total);items.push(take===total?{item_id:line.id,type:"full"}:{item_id:line.id,type:"partial",amount:String(take)});left-=take}if(left>0)throw new TypeError(`The refund of ${options.amount.amount} is more than the transaction's ${options.amount.amount-left}.`);body={action:"refund",transaction_id:paymentId,reason,type:"partial",tax_mode:"internal",items}}const adjustment=await this.request("POST","/adjustments",{body});const total=adjustment.totals?.total;const currency=adjustment.totals?.currency_code??adjustment.currency_code;return{id:adjustment.id,paymentId,status:paddleRefundStatus(adjustment.status),amount:total!==undefined&¤cy?{amount:Number(total),currency:currency.toLowerCase()}:null,raw:adjustment}}async checkout(payer,request){if(request.idempotencyKey!==undefined)throw new PaymentUnsupportedError("paddle","a checkout idempotency key");if(request.mode==="setup")throw new PaymentUnsupportedError("paddle","setup checkout","Paddle saves a payment method while taking a payment, never on its own");if(request.paymentMethods?.length)throw new PaymentUnsupportedError("paddle","choosing payment methods","Paddle shows the methods its checkout settings allow");if(request.cancelUrl&&request.cancelUrl!==request.successUrl)throw new PaymentUnsupportedError("paddle","a separate cancelUrl","Paddle checkout opens over your page, and closing it leaves the payer there");if(request.allowPromotionCodes)throw new PaymentUnsupportedError("paddle","promotion codes","whether the discount field shows is a Paddle checkout setting, not a per-checkout option");if(request.trialDays)throw new PaymentUnsupportedError("paddle","a checkout trial","a Paddle trial is part of the price: set its trial period on the price");this.assertReturnUrl(request.successUrl,"successUrl");const items=request.lines.map((line)=>{if("price"in line)return{price_id:line.price,quantity:line.quantity};if(request.mode==="subscription")throw new TypeError("A Paddle subscription checkout needs catalog prices (pri_...) with a billing cycle: a line priced here has none.");if(!request.currency)throw new TypeError("A checkout line priced with unitAmount needs the checkout's currency.");return this.pricedLine(line.name,{amount:line.unitAmount,currency:request.currency},line.quantity)});const customer=await this.customer(payer);const transaction=await this.request("POST","/transactions",{body:{items,customer_id:customer.id,...request.currency?{currency_code:request.currency.toUpperCase()}:{},collection_mode:"automatic",custom_data:{...request.metadata,...request.reference?{reference:request.reference}:{},[PADDLE_SUCCESS_URL_KEY]:request.successUrl},checkout:{url:null}}});if(!transaction.checkout?.url)throw new Error("Paddle returned no payment link: set a default payment link in Paddle (Checkout > Checkout settings), pointing at /payments/checkout.");return{id:transaction.id,url:transaction.checkout.url,expiresAt:null,raw:transaction}}async checkoutSuccessUrl(transactionId){if(!TRANSACTION_ID.test(transactionId))throw new TypeError("Not a Paddle transaction id.");const transaction=await this.request("GET",`/transactions/${transactionId}`);const successUrl=transaction.custom_data?.[PADDLE_SUCCESS_URL_KEY];if(typeof successUrl!=="string")return null;this.assertReturnUrl(successUrl,"successUrl");return successUrl}async paymentMethods(payer){const customer=await this.customer(payer);const methods=await this.request("GET",`/customers/${customer.id}/payment-methods`);return(methods??[]).map((method)=>({id:method.id,type:method.type,brand:method.card?.type??null,last4:method.card?.last4??null,expMonth:method.card?.expiry_month??null,expYear:method.card?.expiry_year??null,isDefault:false,raw:method}))}async removePaymentMethod(payer,paymentMethodId){const customer=await this.customer(payer);await this.request("DELETE",`/customers/${customer.id}/payment-methods/${encodeURIComponent(paymentMethodId)}`)}async subscribe(){throw new PaymentUnsupportedError("paddle","subscribe",'a Paddle subscription starts at checkout: use checkout with mode "subscription"')}async cancelSubscription(subscriptionId,options={}){const subscription=await this.request("POST",`/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`,{body:{effective_from:options.atPeriodEnd?"next_billing_period":"immediately"}});return summarizePaddleSubscription(subscription)}async subscriptions(payer){const customer=await this.customer(payer);const subscriptions=await this.request("GET","/subscriptions",{query:{customer_id:customer.id}});return(subscriptions??[]).map(summarizePaddleSubscription)}async verifyWebhook(request){if(!this.config.webhookSecret)throw new WebhookNotConfiguredError("paddle","Paddle webhooks cannot be verified without the endpoint secret key: set PADDLE_WEBHOOK_SECRET or payment.paddle.webhookSecret.");const header=headerOf(request.headers,"paddle-signature");if(!header)throw new WebhookSignatureError("paddle","there is no Paddle-Signature header");const signature=parsePaddleSignature(header);if(!signature)throw new WebhookSignatureError("paddle","the Paddle-Signature header is not ts=...;h1=...");const tolerance=this.config.webhookTolerance??5;if(Math.abs(this.now()/1000-signature.timestamp)>tolerance)throw new WebhookSignatureError("paddle",`the signature is more than ${tolerance} seconds from now`);const expected=Buffer.from(paddleSignature(signature.timestamp,request.payload,this.config.webhookSecret));const matches=signature.signatures.some((given)=>{const actual=Buffer.from(given);return actual.length===expected.length&&timingSafeEqual(actual,expected)});if(!matches)throw new WebhookSignatureError("paddle","it is signed with another key");let notification;try{notification=JSON.parse(request.payload)}catch{throw new WebhookSignatureError("paddle","the body is not JSON")}return[this.translate(notification)]}translate(notification){const data=notification.data??{};const base={provider:this.name,id:notification.event_id,providerType:notification.event_type,merchantReference:typeof data.custom_data?.reference==="string"?data.custom_data.reference:null,raw:notification};if(notification.event_type.startsWith("transaction.")){const totals=data.details?.totals;const amount=totals?.grand_total!==undefined&&(totals.currency_code??data.currency_code)?{amount:Number(totals.grand_total),currency:String(totals.currency_code??data.currency_code).toLowerCase()}:null;const type=notification.event_type==="transaction.completed"?"payment.succeeded":notification.event_type==="transaction.payment_failed"?"payment.failed":notification.event_type==="transaction.canceled"?"payment.canceled":"unknown";const lastAttempt=Array.isArray(data.payments)?data.payments.at(-1):undefined;return{...base,type,reference:typeof data.id==="string"?data.id:null,amount,reason:type==="payment.failed"?lastAttempt?.error_code??null:null}}if(notification.event_type==="adjustment.created"||notification.event_type==="adjustment.updated"){const adjustment=data;const settled=adjustment.action==="refund"&&(adjustment.status==="approved"||adjustment.status==="rejected");const currency=adjustment.totals?.currency_code??adjustment.currency_code;return{...base,id:settled?`adjustment:${adjustment.id}:${adjustment.status}`:notification.event_id,type:settled?adjustment.status==="approved"?"refund.succeeded":"refund.failed":"unknown",reference:adjustment.transaction_id??null,amount:adjustment.totals?.total!==undefined&¤cy?{amount:Number(adjustment.totals.total),currency:currency.toLowerCase()}:null,reason:adjustment.status==="rejected"?adjustment.reason??null:null}}const subscriptionTypes={"subscription.created":"subscription.created","subscription.canceled":"subscription.canceled","subscription.updated":"subscription.updated","subscription.activated":"subscription.updated","subscription.trialing":"subscription.updated","subscription.past_due":"subscription.updated","subscription.paused":"subscription.updated","subscription.resumed":"subscription.updated"};return{...base,type:subscriptionTypes[notification.event_type]??"unknown",reference:typeof data.id==="string"?data.id:null,amount:null,reason:null}}acknowledgeWebhook(){return new Response(null,{status:200})}}
|
package/dist/driver/stripe.d.ts
CHANGED
|
@@ -35,7 +35,7 @@ export declare interface StripeOperations {
|
|
|
35
35
|
customer: (payer: Payer) => Promise<Stripe.Customer>
|
|
36
36
|
createIntent: (payer: Payer, params: Stripe.PaymentIntentCreateParams, idempotencyKey?: string) => Promise<Stripe.PaymentIntent>
|
|
37
37
|
refund: (paymentIntentId: string, params: Stripe.RefundCreateParams & { idempotencyKey?: string }) => Promise<Stripe.Refund>
|
|
38
|
-
createCheckout: (payer: Payer, params: Stripe.Checkout.SessionCreateParams) => Promise<Stripe.Checkout.Session>
|
|
38
|
+
createCheckout: (payer: Payer, params: Stripe.Checkout.SessionCreateParams, idempotencyKey?: string) => Promise<Stripe.Checkout.Session>
|
|
39
39
|
listPaymentMethods: (customerId: string) => Promise<Stripe.PaymentMethod[]>
|
|
40
40
|
deletePaymentMethod: (payer: Payer, paymentMethodId: string) => Promise<unknown>
|
|
41
41
|
subscribe: (payer: Payer, type: string, lookupKey: string) => Promise<Stripe.Subscription>
|
package/dist/driver/stripe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assertMoney,headerOf,WebhookNotConfiguredError,WebhookSignatureError}from"./types";const CAPABILITIES=new Set(["customers","charge","createPayment","refund","checkout","paymentMethods","subscriptions","webhooks"]);export function stripePaymentStatus(intent){switch(intent.status){case"succeeded":return"succeeded";case"canceled":return"canceled";case"requires_action":return"requires_action";case"processing":case"requires_capture":return"processing";default:return intent.last_payment_error?"failed":"requires_payment_method"}}const STRIPE_DECIMAL_SHIFT={isk:2,ugx:2,mga:-2};export function toStripeAmount(money){const shift=STRIPE_DECIMAL_SHIFT[money.currency.toLowerCase()]??0;if(shift>=0)return money.amount*10**shift;const divisor=10**-shift;if(money.amount%divisor!==0)throw new TypeError(`Stripe charges whole ${money.currency.toUpperCase()} only, and ${money.amount} minor units is ${money.amount/divisor} ${money.currency.toUpperCase()}.`);return money.amount/divisor}export function fromStripeAmount(amount,currency){const shift=STRIPE_DECIMAL_SHIFT[currency.toLowerCase()]??0;return{amount:shift>=0?Math.round(amount/10**shift):amount*10**-shift,currency}}export function refundedThisTime(charge,previous){if(typeof charge.amount_refunded!=="number")return;const before=typeof previous?.amount_refunded==="number"?previous.amount_refunded:0;return charge.amount_refunded-before}function refundStatus(status){if(status==="succeeded"||status==="failed"||status==="canceled")return status;return"pending"}const SUBSCRIPTION_STATUSES=new Set(["active","trialing","past_due","canceled","incomplete","unpaid","paused"]);function subscriptionStatus(status){if(status==="incomplete_expired")return"canceled";return SUBSCRIPTION_STATUSES.has(status)?status:"unknown"}const INTERVALS=new Set(["day","week","month","year"]);export function subscriptionPeriodEnd(subscription){const item=subscription.items?.data?.[0];const fromItem=item?.current_period_end;if(typeof fromItem==="number")return fromItem;const legacy=subscription.current_period_end;return typeof legacy==="number"?legacy:undefined}export function summarizeSubscription(subscription){const item=subscription.items?.data?.[0];const periodEnd=subscriptionPeriodEnd(subscription);const price=item?.price;const invoice=subscription.latest_invoice;const secret=invoice&&typeof invoice==="object"?invoice.confirmation_secret?.client_secret:undefined;return{id:subscription.id,status:subscriptionStatus(subscription.status),price:price?{id:price.id,name:price.nickname??price.lookup_key??null,amount:typeof price.unit_amount==="number"?fromStripeAmount(price.unit_amount,price.currency):null,interval:INTERVALS.has(price.recurring?.interval??"")?price.recurring.interval:null}:null,currentPeriodEnd:periodEnd?new Date(periodEnd*1000):null,cancelAtPeriodEnd:Boolean(subscription.cancel_at_period_end),...secret&&subscription.status==="incomplete"?{clientConfirmation:{provider:"stripe",clientSecret:secret}}:{},raw:subscription}}const EVENT_TYPES={"payment_intent.succeeded":"payment.succeeded","payment_intent.payment_failed":"payment.failed","payment_intent.canceled":"payment.canceled","charge.refunded":"refund.succeeded","refund.failed":"refund.failed","checkout.session.completed":"checkout.completed","customer.subscription.created":"subscription.created","customer.subscription.updated":"subscription.updated","customer.subscription.deleted":"subscription.canceled","invoice.paid":"invoice.paid","invoice.payment_failed":"invoice.payment_failed"};export function toStoredPaymentMethod(method,defaultId=null){return{id:method.id,type:method.type,brand:method.card?.brand??null,last4:method.card?.last4??null,expMonth:method.card?.exp_month??null,expYear:method.card?.exp_year??null,isDefault:method.id===defaultId,raw:method}}function toPayment(intent){const status=stripePaymentStatus(intent);return{id:intent.id,status,amount:fromStripeAmount(intent.amount,intent.currency),...intent.client_secret&&(status==="requires_payment_method"||status==="requires_action")?{clientConfirmation:{provider:"stripe",clientSecret:intent.client_secret}}:{},...intent.next_action?.redirect_to_url?.url?{redirectUrl:intent.next_action.redirect_to_url.url}:{},...intent.last_payment_error?.message?{failureReason:intent.last_payment_error.message}:{},raw:intent}}export class StripeDriver{name="stripe";capabilities=CAPABILITIES;ops;webhookSecret;webhookTolerance;constructor(options){this.ops=options.operations;this.webhookSecret=options.webhookSecret;this.webhookTolerance=options.webhookTolerance}async customer(payer){const customer=await this.ops.customer(payer);return{id:customer.id,email:customer.email??null,name:customer.name??null}}async charge(payer,amount,paymentMethod,options={}){assertMoney(amount);const customer=await this.ops.customer(payer);const intent=await this.ops.createIntent(payer,{amount:toStripeAmount(amount),currency:amount.currency.toLowerCase(),customer:customer.id,payment_method:paymentMethod,confirm:true,automatic_payment_methods:{enabled:true,allow_redirects:"never"},off_session:true,...options.description?{description:options.description}:{},metadata:{...options.metadata,...options.reference?{reference:options.reference}:{}}},options.idempotencyKey);return toPayment(intent)}async createPayment(payer,amount,options={}){assertMoney(amount);const customer=await this.ops.customer(payer);const intent=await this.ops.createIntent(payer,{amount:toStripeAmount(amount),currency:amount.currency.toLowerCase(),customer:customer.id,automatic_payment_methods:{enabled:true},...options.description?{description:options.description}:{},metadata:{...options.metadata,...options.reference?{reference:options.reference}:{}}},options.idempotencyKey);return toPayment(intent)}async refund(paymentId,options={}){if(options.amount)assertMoney(options.amount,"refund amount");const refund=await this.ops.refund(paymentId,{...options.amount?{amount:toStripeAmount(options.amount)}:{},...options.reason?{reason:options.reason}:{},...options.idempotencyKey?{idempotencyKey:options.idempotencyKey}:{}});return{id:refund.id,paymentId,status:refundStatus(refund.status),amount:fromStripeAmount(refund.amount,refund.currency),raw:refund}}async checkout(payer,request){if(request.trialDays!==undefined&&(!Number.isSafeInteger(request.trialDays)||request.trialDays<1))throw new TypeError("trialDays is a whole number of days, at least 1.");if(request.trialDays&&request.mode!=="subscription")throw new TypeError("trialDays applies to a subscription checkout.");const customer=await this.ops.customer(payer);const lineItems=request.lines.map((line)=>{if("price"in line)return{price:line.price,quantity:line.quantity};if(!request.currency)throw new TypeError("A checkout line priced with unitAmount needs the checkout's currency.");return{quantity:line.quantity,price_data:{currency:request.currency.toLowerCase(),unit_amount:toStripeAmount({amount:line.unitAmount,currency:request.currency}),product_data:{name:line.name}}}});const carried={...request.metadata,...request.reference?{reference:request.reference}:{}};const hasCarried=Object.keys(carried).length>0;const session=await this.ops.createCheckout(payer,{customer:customer.id,mode:request.mode,success_url:request.successUrl,...request.cancelUrl?{cancel_url:request.cancelUrl}:{},...request.mode==="setup"?{currency:request.currency?.toLowerCase()}:{line_items:lineItems},...request.reference?{client_reference_id:request.reference}:{},...request.metadata?{metadata:request.metadata}:{},...hasCarried&&request.mode==="payment"?{payment_intent_data:{metadata:carried}}:{},...request.mode==="subscription"&&(hasCarried||request.trialDays)?{subscription_data:{...hasCarried?{metadata:carried}:{},...request.trialDays?{trial_period_days:request.trialDays}:{}}}:{},...hasCarried&&request.mode==="setup"?{setup_intent_data:{metadata:carried}}:{},...request.allowPromotionCodes?{allow_promotion_codes:true}:{},...request.automaticTax?{automatic_tax:{enabled:true}}:{},...request.paymentMethods?.length?{allowed_payment_method_types:[...request.paymentMethods]}:{}});if(!session.url)throw new Error("Stripe returned a checkout session without a url.");return{id:session.id,url:session.url,expiresAt:session.expires_at?new Date(session.expires_at*1000):null,raw:session}}async paymentMethods(payer){const customer=await this.ops.customer(payer);const defaultId=typeof customer.invoice_settings?.default_payment_method==="string"?customer.invoice_settings.default_payment_method:customer.invoice_settings?.default_payment_method?.id??null;const methods=await this.ops.listPaymentMethods(customer.id);return methods.map((method)=>toStoredPaymentMethod(method,defaultId))}async removePaymentMethod(payer,paymentMethodId){await this.ops.deletePaymentMethod(payer,paymentMethodId)}async subscribe(payer,price,options={}){return summarizeSubscription(await this.ops.subscribe(payer,options.type??"default",price))}async cancelSubscription(subscriptionId,options={}){return summarizeSubscription(await this.ops.cancelSubscription(subscriptionId,options.atPeriodEnd??false))}async subscriptions(payer){const customer=await this.ops.customer(payer);return(await this.ops.listSubscriptions(customer.id)).map(summarizeSubscription)}async verifyWebhook(request){if(!this.webhookSecret)throw new WebhookNotConfiguredError("stripe","Stripe webhooks cannot be verified without the signing secret: set STRIPE_WEBHOOK_SECRET or payment.stripe.webhookSecret.");const signature=headerOf(request.headers,"stripe-signature");if(!signature)throw new WebhookSignatureError("stripe","there is no Stripe-Signature header");let event;try{event=await this.ops.constructEvent(request.payload,signature,this.webhookSecret,this.webhookTolerance)}catch(error){throw new WebhookSignatureError("stripe",error.message)}const object=event.data.object;const isRefund=event.type==="charge.refunded"||event.type==="refund.failed";const reference=isRefund?object.payment_intent??object.id:object.id;const minor=event.type==="charge.refunded"?refundedThisTime(object,event.data.previous_attributes):object.amount??object.amount_total;const amount=typeof minor==="number"&&object.currency?fromStripeAmount(minor,String(object.currency)):null;const reason=object.last_payment_error?.message??object.failure_reason??null;return[{provider:this.name,id:event.id,type:EVENT_TYPES[event.type]??"unknown",providerType:event.type,reference:typeof reference==="string"?reference:null,merchantReference:object.client_reference_id??object.metadata?.reference??null,amount,reason,raw:event}]}acknowledgeWebhook(){return Response.json({received:true})}}
|
|
1
|
+
import{assertMoney,headerOf,WebhookNotConfiguredError,WebhookSignatureError}from"./types";const CAPABILITIES=new Set(["customers","charge","createPayment","refund","checkout","paymentMethods","subscriptions","webhooks"]);export function stripePaymentStatus(intent){switch(intent.status){case"succeeded":return"succeeded";case"canceled":return"canceled";case"requires_action":return"requires_action";case"processing":case"requires_capture":return"processing";default:return intent.last_payment_error?"failed":"requires_payment_method"}}const STRIPE_DECIMAL_SHIFT={isk:2,ugx:2,mga:-2};export function toStripeAmount(money){const shift=STRIPE_DECIMAL_SHIFT[money.currency.toLowerCase()]??0;if(shift>=0)return money.amount*10**shift;const divisor=10**-shift;if(money.amount%divisor!==0)throw new TypeError(`Stripe charges whole ${money.currency.toUpperCase()} only, and ${money.amount} minor units is ${money.amount/divisor} ${money.currency.toUpperCase()}.`);return money.amount/divisor}export function fromStripeAmount(amount,currency){const shift=STRIPE_DECIMAL_SHIFT[currency.toLowerCase()]??0;return{amount:shift>=0?Math.round(amount/10**shift):amount*10**-shift,currency}}export function refundedThisTime(charge,previous){if(typeof charge.amount_refunded!=="number")return;const before=typeof previous?.amount_refunded==="number"?previous.amount_refunded:0;return charge.amount_refunded-before}function refundStatus(status){if(status==="succeeded"||status==="failed"||status==="canceled")return status;return"pending"}const SUBSCRIPTION_STATUSES=new Set(["active","trialing","past_due","canceled","incomplete","unpaid","paused"]);function subscriptionStatus(status){if(status==="incomplete_expired")return"canceled";return SUBSCRIPTION_STATUSES.has(status)?status:"unknown"}const INTERVALS=new Set(["day","week","month","year"]);export function subscriptionPeriodEnd(subscription){const item=subscription.items?.data?.[0];const fromItem=item?.current_period_end;if(typeof fromItem==="number")return fromItem;const legacy=subscription.current_period_end;return typeof legacy==="number"?legacy:undefined}export function summarizeSubscription(subscription){const item=subscription.items?.data?.[0];const periodEnd=subscriptionPeriodEnd(subscription);const price=item?.price;const invoice=subscription.latest_invoice;const secret=invoice&&typeof invoice==="object"?invoice.confirmation_secret?.client_secret:undefined;return{id:subscription.id,status:subscriptionStatus(subscription.status),price:price?{id:price.id,name:price.nickname??price.lookup_key??null,amount:typeof price.unit_amount==="number"?fromStripeAmount(price.unit_amount,price.currency):null,interval:INTERVALS.has(price.recurring?.interval??"")?price.recurring.interval:null}:null,currentPeriodEnd:periodEnd?new Date(periodEnd*1000):null,cancelAtPeriodEnd:Boolean(subscription.cancel_at_period_end),...secret&&subscription.status==="incomplete"?{clientConfirmation:{provider:"stripe",clientSecret:secret}}:{},raw:subscription}}const EVENT_TYPES={"payment_intent.succeeded":"payment.succeeded","payment_intent.payment_failed":"payment.failed","payment_intent.canceled":"payment.canceled","charge.refunded":"refund.succeeded","refund.failed":"refund.failed","checkout.session.completed":"checkout.completed","customer.subscription.created":"subscription.created","customer.subscription.updated":"subscription.updated","customer.subscription.deleted":"subscription.canceled","invoice.paid":"invoice.paid","invoice.payment_failed":"invoice.payment_failed"};export function toStoredPaymentMethod(method,defaultId=null){return{id:method.id,type:method.type,brand:method.card?.brand??null,last4:method.card?.last4??null,expMonth:method.card?.exp_month??null,expYear:method.card?.exp_year??null,isDefault:method.id===defaultId,raw:method}}function toPayment(intent){const status=stripePaymentStatus(intent);return{id:intent.id,status,amount:fromStripeAmount(intent.amount,intent.currency),...intent.client_secret&&(status==="requires_payment_method"||status==="requires_action")?{clientConfirmation:{provider:"stripe",clientSecret:intent.client_secret}}:{},...intent.next_action?.redirect_to_url?.url?{redirectUrl:intent.next_action.redirect_to_url.url}:{},...intent.last_payment_error?.message?{failureReason:intent.last_payment_error.message}:{},raw:intent}}export class StripeDriver{name="stripe";capabilities=CAPABILITIES;ops;webhookSecret;webhookTolerance;constructor(options){this.ops=options.operations;this.webhookSecret=options.webhookSecret;this.webhookTolerance=options.webhookTolerance}async customer(payer){const customer=await this.ops.customer(payer);return{id:customer.id,email:customer.email??null,name:customer.name??null}}async charge(payer,amount,paymentMethod,options={}){assertMoney(amount);const customer=await this.ops.customer(payer);const intent=await this.ops.createIntent(payer,{amount:toStripeAmount(amount),currency:amount.currency.toLowerCase(),customer:customer.id,payment_method:paymentMethod,confirm:true,automatic_payment_methods:{enabled:true,allow_redirects:"never"},off_session:true,...options.description?{description:options.description}:{},metadata:{...options.metadata,...options.reference?{reference:options.reference}:{}}},options.idempotencyKey);return toPayment(intent)}async createPayment(payer,amount,options={}){assertMoney(amount);const customer=await this.ops.customer(payer);const intent=await this.ops.createIntent(payer,{amount:toStripeAmount(amount),currency:amount.currency.toLowerCase(),customer:customer.id,automatic_payment_methods:{enabled:true},...options.description?{description:options.description}:{},metadata:{...options.metadata,...options.reference?{reference:options.reference}:{}}},options.idempotencyKey);return toPayment(intent)}async refund(paymentId,options={}){if(options.amount)assertMoney(options.amount,"refund amount");const refund=await this.ops.refund(paymentId,{...options.amount?{amount:toStripeAmount(options.amount)}:{},...options.reason?{reason:options.reason}:{},...options.idempotencyKey?{idempotencyKey:options.idempotencyKey}:{}});return{id:refund.id,paymentId,status:refundStatus(refund.status),amount:fromStripeAmount(refund.amount,refund.currency),raw:refund}}async checkout(payer,request){if(request.trialDays!==undefined&&(!Number.isSafeInteger(request.trialDays)||request.trialDays<1))throw new TypeError("trialDays is a whole number of days, at least 1.");if(request.trialDays&&request.mode!=="subscription")throw new TypeError("trialDays applies to a subscription checkout.");const customer=await this.ops.customer(payer);const lineItems=request.lines.map((line)=>{if("price"in line)return{price:line.price,quantity:line.quantity};if(!request.currency)throw new TypeError("A checkout line priced with unitAmount needs the checkout's currency.");return{quantity:line.quantity,price_data:{currency:request.currency.toLowerCase(),unit_amount:toStripeAmount({amount:line.unitAmount,currency:request.currency}),product_data:{name:line.name}}}});const carried={...request.metadata,...request.reference?{reference:request.reference}:{}};const hasCarried=Object.keys(carried).length>0;const session=await this.ops.createCheckout(payer,{customer:customer.id,mode:request.mode,success_url:request.successUrl,...request.cancelUrl?{cancel_url:request.cancelUrl}:{},...request.mode==="setup"?{currency:request.currency?.toLowerCase()}:{line_items:lineItems},...request.reference?{client_reference_id:request.reference}:{},...request.metadata?{metadata:request.metadata}:{},...hasCarried&&request.mode==="payment"?{payment_intent_data:{metadata:carried}}:{},...request.mode==="subscription"&&(hasCarried||request.trialDays)?{subscription_data:{...hasCarried?{metadata:carried}:{},...request.trialDays?{trial_period_days:request.trialDays}:{}}}:{},...hasCarried&&request.mode==="setup"?{setup_intent_data:{metadata:carried}}:{},...request.allowPromotionCodes?{allow_promotion_codes:true}:{},...request.automaticTax?{automatic_tax:{enabled:true}}:{},...request.paymentMethods?.length?{allowed_payment_method_types:[...request.paymentMethods]}:{}},request.idempotencyKey);if(!session.url)throw new Error("Stripe returned a checkout session without a url.");return{id:session.id,url:session.url,expiresAt:session.expires_at?new Date(session.expires_at*1000):null,raw:session}}async paymentMethods(payer){const customer=await this.ops.customer(payer);const defaultId=typeof customer.invoice_settings?.default_payment_method==="string"?customer.invoice_settings.default_payment_method:customer.invoice_settings?.default_payment_method?.id??null;const methods=await this.ops.listPaymentMethods(customer.id);return methods.map((method)=>toStoredPaymentMethod(method,defaultId))}async removePaymentMethod(payer,paymentMethodId){await this.ops.deletePaymentMethod(payer,paymentMethodId)}async subscribe(payer,price,options={}){return summarizeSubscription(await this.ops.subscribe(payer,options.type??"default",price))}async cancelSubscription(subscriptionId,options={}){return summarizeSubscription(await this.ops.cancelSubscription(subscriptionId,options.atPeriodEnd??false))}async subscriptions(payer){const customer=await this.ops.customer(payer);return(await this.ops.listSubscriptions(customer.id)).map(summarizeSubscription)}async verifyWebhook(request){if(!this.webhookSecret)throw new WebhookNotConfiguredError("stripe","Stripe webhooks cannot be verified without the signing secret: set STRIPE_WEBHOOK_SECRET or payment.stripe.webhookSecret.");const signature=headerOf(request.headers,"stripe-signature");if(!signature)throw new WebhookSignatureError("stripe","there is no Stripe-Signature header");let event;try{event=await this.ops.constructEvent(request.payload,signature,this.webhookSecret,this.webhookTolerance)}catch(error){throw new WebhookSignatureError("stripe",error.message)}const object=event.data.object;const isRefund=event.type==="charge.refunded"||event.type==="refund.failed";const reference=isRefund?object.payment_intent??object.id:object.id;const minor=event.type==="charge.refunded"?refundedThisTime(object,event.data.previous_attributes):object.amount??object.amount_total;const amount=typeof minor==="number"&&object.currency?fromStripeAmount(minor,String(object.currency)):null;const reason=object.last_payment_error?.message??object.failure_reason??null;return[{provider:this.name,id:event.id,type:EVENT_TYPES[event.type]??"unknown",providerType:event.type,reference:typeof reference==="string"?reference:null,merchantReference:object.client_reference_id??object.metadata?.reference??null,amount,reason,raw:event}]}acknowledgeWebhook(){return Response.json({received:true})}}
|
package/dist/driver/types.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/payments",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.667",
|
|
6
6
|
"description": "The Stacks payments package. Currently supporting Stripe.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -60,12 +60,12 @@
|
|
|
60
60
|
"prepublishOnly": "bun run build"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@stacksjs/config": "0.75.
|
|
64
|
-
"@stacksjs/database": "0.75.
|
|
65
|
-
"@stacksjs/error-handling": "0.75.
|
|
66
|
-
"@stacksjs/logging": "0.75.
|
|
67
|
-
"@stacksjs/orm": "0.75.
|
|
68
|
-
"@stacksjs/types": "0.75.
|
|
63
|
+
"@stacksjs/config": "0.75.667",
|
|
64
|
+
"@stacksjs/database": "0.75.667",
|
|
65
|
+
"@stacksjs/error-handling": "0.75.667",
|
|
66
|
+
"@stacksjs/logging": "0.75.667",
|
|
67
|
+
"@stacksjs/orm": "0.75.667",
|
|
68
|
+
"@stacksjs/types": "0.75.667",
|
|
69
69
|
"stripe": "23.0.0"
|
|
70
70
|
},
|
|
71
71
|
"peerDependencies": {
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
}
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
|
-
"@stacksjs/utils": "0.75.
|
|
80
|
+
"@stacksjs/utils": "0.75.667",
|
|
81
81
|
"@stripe/stripe-js": "^10.0.0",
|
|
82
82
|
"better-dx": "^0.2.39"
|
|
83
83
|
}
|