@stacksjs/payments 0.75.515 → 0.75.518
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/billable/charge.js +1 -1
- package/dist/billable/checkout.js +1 -1
- package/dist/billable/customer.js +1 -1
- package/dist/billable/intent.js +1 -1
- package/dist/billable/invoice.js +1 -1
- package/dist/billable/payment-method.js +1 -1
- package/dist/billable/portal.js +1 -1
- package/dist/billable/price.js +1 -1
- package/dist/billable/product.js +1 -1
- package/dist/billable/setup-products.js +1 -1
- package/dist/billable/subscription.js +1 -1
- package/dist/billable/transaction.js +1 -1
- package/dist/billable/webhook-events.js +1 -1
- package/dist/billable/webhook.js +1 -1
- package/dist/connect/account.js +1 -1
- package/dist/connect/charge.js +1 -1
- package/dist/connect/destination.js +1 -1
- package/dist/connect/direct.js +1 -1
- package/dist/connect/financials.js +1 -1
- package/dist/connect/invoice-collection.js +1 -1
- package/dist/connect/invoice-credit.js +1 -1
- package/dist/connect/invoice-fee.js +1 -1
- package/dist/connect/invoice-price.js +1 -1
- package/dist/connect/invoice-purchase.js +1 -1
- package/dist/connect/invoice-tax.js +1 -1
- package/dist/connect/pagination.js +1 -1
- package/dist/connect/payout.js +1 -1
- package/dist/connect/refund.js +1 -1
- package/dist/connect/subscription.js +1 -1
- package/dist/connect/tax.js +1 -1
- package/dist/connect/transfer.js +1 -1
- package/dist/direct-debit.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-checkout.js +1 -1
- package/dist/driver/paddle.js +1 -1
- package/dist/driver/stripe.js +1 -1
- package/dist/driver/types.js +1 -1
- package/dist/drivers/stripe.js +1 -1
- package/dist/idempotency.js +1 -1
- package/dist/payment.js +1 -1
- package/dist/subscription-state.js +1 -1
- package/dist/terminal.js +1 -1
- package/package.json +8 -8
package/dist/connect/payout.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stripe}from"../drivers/stripe";import{requireAccountId}from"./account";export const managePayout=(()=>{async function listPayouts(accountId,params={}){requireAccountId(accountId,"listPayouts");return await stripe.payouts.list(params,{stripeAccount:accountId})}async function retrievePayout(accountId,payoutId){requireAccountId(accountId,"retrievePayout");if(!payoutId||typeof payoutId!=="string")throw Error("[payments/connect] retrievePayout requires a payout id");return await stripe.payouts.retrieve(payoutId,{},{stripeAccount:accountId})}async function accountBalance(accountId){requireAccountId(accountId,"accountBalance");return await stripe.balance.retrieve({},{stripeAccount:accountId})}return{listPayouts,retrievePayout,accountBalance}})();
|
|
1
|
+
import{stripe}from"../drivers/stripe";import{requireAccountId}from"./account";export const managePayout=(()=>{async function listPayouts(accountId,params={}){requireAccountId(accountId,"listPayouts");return await stripe.payouts.list(params,{stripeAccount:accountId})}async function retrievePayout(accountId,payoutId){requireAccountId(accountId,"retrievePayout");if(!payoutId||typeof payoutId!=="string")throw new Error("[payments/connect] retrievePayout requires a payout id");return await stripe.payouts.retrieve(payoutId,{},{stripeAccount:accountId})}async function accountBalance(accountId){requireAccountId(accountId,"accountBalance");return await stripe.balance.retrieve({},{stripeAccount:accountId})}return{listPayouts,retrievePayout,accountBalance}})();
|
package/dist/connect/refund.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";function expandedCharge(source){return source.latest_charge&&typeof source.latest_charge==="object"?source.latest_charge:null}export function isDestinationCharge(source){if(!source)return
|
|
1
|
+
import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";function expandedCharge(source){return source.latest_charge&&typeof source.latest_charge==="object"?source.latest_charge:null}export function isDestinationCharge(source){if(!source)return false;const charge=expandedCharge(source);return Boolean(source.transfer_data?.destination||source.transfer||charge?.transfer_data?.destination||charge?.transfer)}export function tookApplicationFee(source){if(!source)return false;const charge=expandedCharge(source);return Boolean((source.application_fee_amount??0)>0||source.application_fee||(charge?.application_fee_amount??0)>0||charge?.application_fee)}export function connectRefundParams(source,options={}){if(!source?.id||typeof source.id!=="string")throw new Error("[payments/connect] connectRefundParams needs the PaymentIntent or Charge to refund");if(options.amount!=null&&(!Number.isSafeInteger(options.amount)||options.amount<=0))throw new Error(`[payments/connect] a refund amount is a positive whole number of minor units, got ${options.amount}`);const isIntent=source.object==="payment_intent"||source.id.startsWith("pi_");const destination=isDestinationCharge(source);const reverse=destination&&(options.reverseTransfer??true);const refundFee=(destination||Boolean(options.account))&&tookApplicationFee(source)&&(options.refundApplicationFee??true);return{...isIntent?{payment_intent:source.id}:{charge:source.id},...options.amount!=null?{amount:options.amount}:{},...options.reason?{reason:options.reason}:{},...options.metadata?{metadata:options.metadata}:{},...reverse?{reverse_transfer:true}:{},...refundFee?{refund_application_fee:true}:{}}}export async function connectRefund(paymentId,options={}){if(!paymentId||typeof paymentId!=="string")throw new Error("[payments/connect] connectRefund needs a PaymentIntent or Charge id");const{idempotencyKey,client=stripe,...refundOptions}=options;const onAccount=refundOptions.account?{stripeAccount:refundOptions.account}:{};const source=paymentId.startsWith("pi_")?await client.paymentIntents.retrieve(paymentId,{expand:["latest_charge"]},onAccount):await client.charges.retrieve(paymentId,{},onAccount);return await client.refunds.create(connectRefundParams(source,refundOptions),{...onAccount,idempotencyKey:idempotencyKey??freshIdempotencyKey("connect.refund",paymentId,refundOptions.amount??"full")})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"@stacksjs/config";import{manageCheckout}from"../billable/checkout";import{manageCustomer}from"../billable/customer";import{requireAccountId}from"./account";const INTERVALS=["day","week","month","year"];function configuredFeePercent(){
|
|
1
|
+
import{config}from"@stacksjs/config";import{manageCheckout}from"../billable/checkout";import{manageCustomer}from"../billable/customer";import{requireAccountId}from"./account";const INTERVALS=["day","week","month","year"];function configuredFeePercent(){const cfg=config||{};return cfg.payment?.connect?.platformFeePercent}export const manageDestinationSubscription=(()=>{function feePercentFor(options={}){const percent=options.platformFeePercent??configuredFeePercent();if(percent==null)return;if(!Number.isFinite(percent)||percent<0||percent>100)throw new Error(`[payments/connect] platformFeePercent must be between 0 and 100, got ${percent}`);if(Math.round(percent*100)!==percent*100)throw new Error(`[payments/connect] platformFeePercent takes at most two decimal places, got ${percent}`);return percent>0?percent:undefined}function subscriptionData(destination,options={}){requireAccountId(destination,"destinationSubscription");if(options.trialDays!=null&&(!Number.isInteger(options.trialDays)||options.trialDays<1||options.trialDays>730))throw new Error(`[payments/connect] trialDays must be a whole number from 1 to 730, got ${options.trialDays}`);const fee=feePercentFor({platformFeePercent:options.platformFeePercent});return{transfer_data:{destination},...fee!=null?{application_fee_percent:fee}:{},...options.onBehalfOf?{on_behalf_of:destination}:{},...options.trialDays?{trial_period_days:options.trialDays}:{},...options.metadata?{metadata:options.metadata}:{}}}function lineItem(price,quantity=1){if(!Number.isInteger(quantity)||quantity<1)throw new Error(`[payments/connect] quantity must be a positive whole number, got ${quantity}`);if(typeof price==="string"){if(!price.startsWith("price_"))throw new Error(`[payments/connect] a catalog price id starts with "price_", got "${price}"`);return{price,quantity}}if(!Number.isInteger(price.amount)||price.amount<=0)throw new Error("[payments/connect] a recurring price needs a positive amount in minor units");if(!INTERVALS.includes(price.interval))throw new Error(`[payments/connect] interval must be one of ${INTERVALS.join(", ")}, got ${price.interval}`);const intervalCount=price.intervalCount??1;if(!Number.isInteger(intervalCount)||intervalCount<1)throw new Error(`[payments/connect] intervalCount must be a positive whole number, got ${intervalCount}`);if(!price.productName?.trim())throw new Error("[payments/connect] a recurring price needs a productName");if(price.taxBehavior!=null&&price.taxBehavior!=="inclusive"&&price.taxBehavior!=="exclusive")throw new Error("[payments/connect] taxBehavior must be inclusive or exclusive");if(price.taxCode!=null&&!/^txcd_\d{8}$/.test(price.taxCode))throw new Error("[payments/connect] taxCode must be a Stripe tax classification (txcd_ followed by eight digits)");return{quantity,price_data:{currency:price.currency.toLowerCase(),unit_amount:price.amount,...price.taxBehavior?{tax_behavior:price.taxBehavior}:{},recurring:{interval:price.interval,...intervalCount!==1?{interval_count:intervalCount}:{}},product_data:{name:price.productName.slice(0,250),...price.productDescription?{description:price.productDescription.slice(0,500)}:{},...price.taxCode?{tax_code:price.taxCode}:{}}}}}async function checkout(user,options){const customer=options.customer??(await manageCustomer.createOrGetStripeUser(user,{})).id;return await manageCheckout.create(user,{mode:"subscription",customer,line_items:[lineItem(options.price,options.quantity)],subscription_data:subscriptionData(options.destination,options),success_url:options.successUrl,cancel_url:options.cancelUrl,...options.clientReferenceId?{client_reference_id:options.clientReferenceId}:{},...options.metadata?{metadata:options.metadata}:{},...options.sessionParams})}function destinationOf(subscription){const destination=subscription.transfer_data?.destination;if(!destination)return null;const id=typeof destination==="string"?destination:destination.id;return id||null}return{feePercentFor,subscriptionData,lineItem,checkout,destinationOf}})();
|
package/dist/connect/tax.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function invoiceTaxAmounts(value){const
|
|
1
|
+
export function invoiceTaxAmounts(value){const gross=value.total;const net=value.total_excluding_tax;if(!Number.isSafeInteger(gross)||gross<0||net==null||!Number.isSafeInteger(net)||net<0||net>gross)throw new Error("[payments/connect] Provider has no valid tax-exclusive amount");const tax=gross-net;if(!Array.isArray(value.total_taxes)||value.total_taxes.some((row)=>!Number.isSafeInteger(row.amount)||row.amount<0)||value.total_taxes.reduce((sum,row)=>sum+row.amount,0)!==tax)throw new Error("[payments/connect] Provider tax amounts do not balance");if(value.automatic_tax?.enabled&&value.automatic_tax.status!=="complete")throw new Error("[payments/connect] Provider tax calculation is not complete");return{gross,net,tax}}
|
package/dist/connect/transfer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";import{requireAccountId}from"./account";function defaultCurrency(){const cfg=config||{};
|
|
1
|
+
import{config}from"@stacksjs/config";import{stripe}from"../drivers/stripe";import{freshIdempotencyKey}from"../idempotency";import{requireAccountId}from"./account";function defaultCurrency(){const cfg=config||{};const fromConfig=cfg.payment?.currency||cfg.billing?.currency;return(fromConfig||process.env.STRIPE_CURRENCY||"usd").toLowerCase()}export const manageTransfer=(()=>{async function createTransfer(options){requireAccountId(options?.destination,"createTransfer");if(!Number.isFinite(options.amount)||options.amount<=0)throw new Error("[payments/connect] createTransfer requires a positive amount in minor units");const params={amount:Math.floor(options.amount),currency:(options.currency??defaultCurrency()).toLowerCase(),destination:options.destination,...options.transferGroup?{transfer_group:options.transferGroup}:{},...options.sourceTransaction?{source_transaction:options.sourceTransaction}:{},...options.description?{description:options.description}:{},...options.metadata?{metadata:options.metadata}:{}};return await stripe.transfers.create(params,{idempotencyKey:options.idempotencyKey??freshIdempotencyKey("connect.transfer.create",options.destination,options.amount)})}async function reverseTransfer(transferId,amount,options={}){if(!transferId||typeof transferId!=="string")throw new Error("[payments/connect] reverseTransfer requires a transfer id");if(amount!=null&&(!Number.isFinite(amount)||amount<=0))throw new Error("[payments/connect] reverseTransfer amount must be a positive number of minor units");const params=amount==null?{}:{amount:Math.floor(amount)};return await stripe.transfers.createReversal(transferId,params,{idempotencyKey:options.idempotencyKey??`stacks:connect.transfer.reverse:${transferId}:${amount??"full"}:v1`})}async function listTransfers(params={}){return await stripe.transfers.list(params)}async function retrieveTransfer(transferId){if(!transferId||typeof transferId!=="string")throw new Error("[payments/connect] retrieveTransfer requires a transfer id");return await stripe.transfers.retrieve(transferId)}return{createTransfer,reverseTransfer,listTransfers,retrieveTransfer}})();
|
package/dist/direct-debit.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const PAYMENT_METHODS={card:{currencies:null,delayed
|
|
1
|
+
export const PAYMENT_METHODS={card:{currencies:null,delayed:false,mandate:false,noticeDays:null},sepa_debit:{currencies:["eur"],delayed:true,mandate:true,noticeDays:2},bacs_debit:{currencies:["gbp"],delayed:true,mandate:true,noticeDays:null},us_bank_account:{currencies:["usd"],delayed:true,mandate:true,noticeDays:null},au_becs_debit:{currencies:["aud"],delayed:true,mandate:true,noticeDays:null}};export function isPaymentMethodType(value){return typeof value==="string"&&Object.prototype.hasOwnProperty.call(PAYMENT_METHODS,value)}export function isDelayedPaymentMethod(type){return isPaymentMethodType(type)&&PAYMENT_METHODS[type].delayed}export function parsePaymentMethods(value){const items=Array.isArray(value)?value:typeof value==="string"?value.split(","):[];const types=[];for(const item of items){const type=typeof item==="string"?item.trim().toLowerCase():item;if(isPaymentMethodType(type)&&!types.includes(type))types.push(type)}return types.length?types:["card"]}export function methodSupportsCurrency(type,currency){const currencies=PAYMENT_METHODS[type].currencies;return currencies===null||currencies.includes(String(currency||"").toLowerCase())}export function paymentMethodsFor(allowed,currency){const usable=parsePaymentMethods(allowed).filter((type)=>methodSupportsCurrency(type,currency));return usable.length?usable:["card"]}export const EURO_COUNTRIES=["AT","BE","BG","CY","DE","EE","ES","FI","FR","GR","HR","IE","IT","LT","LU","LV","MT","NL","PT","SI","SK","AD","MC","SM","VA","ME","XK"];export const SEPA_COUNTRIES=["AT","BE","BG","CY","CZ","DE","DK","EE","ES","FI","FR","GR","HR","HU","IE","IT","LT","LU","LV","MT","NL","PL","PT","RO","SE","SI","SK","IS","LI","NO","CH","GB","AD","MC","SM","VA","GI"];const COUNTRY_CURRENCIES={US:"usd",GB:"gbp",CH:"chf",LI:"chf",AU:"aud",CA:"cad",NZ:"nzd",SE:"sek",DK:"dkk",NO:"nok",PL:"pln",CZ:"czk",JP:"jpy"};export function regionOfLocale(tag){if(typeof tag!=="string")return null;const parts=tag.trim().replace(/_/g,"-").split("-");for(const part of parts.slice(1)){if(/^[a-z]{2}$/i.test(part))return part.toUpperCase();if(/^\d{3}$/.test(part))return null}return null}export function currencyForCountry(country,supported,fallback){const code=typeof country==="string"?country.trim().toUpperCase():"";const currency=EURO_COUNTRIES.includes(code)?"eur":COUNTRY_CURRENCIES[code];const offered=supported.map((value)=>value.toLowerCase());return currency&&offered.includes(currency)?currency:fallback.toLowerCase()}function ymdOf(value){if(typeof value==="number"&&Number.isFinite(value)&&value>0)return new Date(value*1000).toISOString().slice(0,10);if(typeof value==="string"&&/^\d{4}-\d{2}-\d{2}/.test(value))return value.slice(0,10);return null}export function debitDetailsOf(source){const details=source?.payment_method_details??source;const type=details?.type;if(!isDelayedPaymentMethod(type))return null;const block=details[type]??{};const str=(value)=>typeof value==="string"&&value?value:null;return{type,mandateId:str(typeof block.mandate==="object"?block.mandate?.id:block.mandate),last4:str(block.last4),bankCode:str(block.bank_code??block.sort_code??block.routing_number??block.bsb_number),country:str(block.country),expectedDebitDate:ymdOf(block.expected_debit_date)}}export function mandateReferenceOf(mandate){if(!mandate?.id)return null;const type=mandate.payment_method_details?.type??null;const block=type?mandate.payment_method_details?.[type]??{}:{};return{id:String(mandate.id),reference:block.reference?String(block.reference):null,url:block.url?String(block.url):null,status:String(mandate.status||"active"),type:type?String(type):null}}export async function retrieveDebitMandate(stripe,mandateId){if(!mandateId)return null;return mandateReferenceOf(await stripe.mandates.retrieve(mandateId))}const idOf=(value)=>value?String(typeof value==="object"?value.id:value):null;export function debitEventOf(event){const type=String(event?.type||"");const object=event?.data?.object??{};const base=(outcome,extra={})=>({outcome,method:null,paymentIntentId:null,chargeId:null,checkoutSessionId:null,mandateId:null,amount:null,currency:null,failureCode:null,failureMessage:null,details:null,metadata:object?.metadata&&typeof object.metadata==="object"?{...object.metadata}:{},...extra});if(type.startsWith("checkout.session.")){const session={checkoutSessionId:idOf(object.id),paymentIntentId:idOf(object.payment_intent),amount:Number.isFinite(object.amount_total)?Number(object.amount_total):null,currency:object.currency?String(object.currency).toLowerCase():null};if(type==="checkout.session.completed"&&object.payment_status==="unpaid")return base("processing",session);if(type==="checkout.session.async_payment_succeeded")return base("succeeded",session);if(type==="checkout.session.async_payment_failed")return base("failed",session);return null}if(type==="charge.pending"||type==="charge.succeeded"||type==="charge.failed"){const details=debitDetailsOf(object);if(!details)return null;const outcome=type==="charge.pending"?"processing":type==="charge.succeeded"?"succeeded":"failed";return base(outcome,{method:details.type,paymentIntentId:idOf(object.payment_intent),chargeId:idOf(object.id),mandateId:details.mandateId,amount:Number.isFinite(object.amount)?Number(object.amount):null,currency:object.currency?String(object.currency).toLowerCase():null,failureCode:outcome==="failed"&&object.failure_code?String(object.failure_code):null,failureMessage:outcome==="failed"&&object.failure_message?String(object.failure_message):null,details})}if(type==="charge.dispute.created"){const method=object.payment_method_details?.type;if(method==="card")return null;return base("returned",{method:isDelayedPaymentMethod(method)?method:null,paymentIntentId:idOf(object.payment_intent),chargeId:idOf(object.charge),amount:Number.isFinite(object.amount)?Number(object.amount):null,currency:object.currency?String(object.currency).toLowerCase():null,failureCode:object.reason?String(object.reason):null})}if(type==="mandate.updated"){if(object.status!=="inactive")return null;const method=object.payment_method_details?.type;return base("mandate_inactive",{method:isDelayedPaymentMethod(method)?method:null,mandateId:idOf(object.id)})}return null}export function debitFailureNextStep(code){switch(code){case"insufficient_funds":return"retry";case"account_closed":case"authorization_revoked":case"debit_not_authorized":case"debit_authorization_not_match":case"incorrect_account_holder_name":case"invalid_account_number":case"branch_does_not_exist":case"bank_account_restricted":return"update";default:return"contact"}}function addDays(ymd,days){const date=new Date(`${ymd}T00:00:00Z`);date.setUTCDate(date.getUTCDate()+days);return date.toISOString().slice(0,10)}export function isDebitNoticeDue(input){const debit=ymdOf(input.debitDate);const today=ymdOf(input.today);if(!debit||!today)return false;const minimum=input.method?PAYMENT_METHODS[input.method].noticeDays??0:0;const opens=addDays(debit,-Math.max(minimum,Math.floor(input.leadDays)));return today>=opens&&today<debit}export function isDebitNoticeTimely(input){const sent=ymdOf(input.sentOn);const debit=ymdOf(input.debitDate);if(!sent||!debit)return false;return sent<=addDays(debit,-(PAYMENT_METHODS[input.method].noticeDays??0))}
|
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"},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 Error("The Adyen payment driver needs an API key: set ADYEN_API_KEY or payment.adyen.apiKey.");if(!config.merchantAccount)throw Error("The Adyen payment driver needs a merchant account: set ADYEN_MERCHANT_ACCOUNT or payment.adyen.merchantAccount.");if(config.environment==="live"&&!config.liveUrlPrefix)throw 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!==void 0)headers["Content-Type"]="application/json";if(options.idempotencyKey)headers["Idempotency-Key"]=options.idempotencyKey;const response=await this.fetch(url,{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body)});if(response.status===204)return;const text=await response.text(),body=text?JSON.parse(text):void 0;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 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 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 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(),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 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 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}),total=lines.reduce((sum,line)=>sum+line.unitAmount*line.quantity,0),setup=request.mode==="setup",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){return((await this.request("GET","/storedPaymentMethods",{query:{merchantAccount:this.config.merchantAccount,shopperReference:this.shopperReference(payer)}}))?.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:!1,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)),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",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!==void 0&&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.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"]
|
|
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 +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"]),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,cancelled=attributes.status==="cancelled"||attributes.cancelled===!0,periodEnd=cancelled?attributes.ends_at:attributes.renews_at;return{id:String(subscription.id),status:SUBSCRIPTION_STATUSES[attributes.status]??"unknown",price:attributes.variant_id!==void 0?{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 Error("The Lemon Squeezy payment driver needs an API key: set LEMONSQUEEZY_API_KEY or payment.lemonsqueezy.apiKey.");if(!config.storeId)throw 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!==void 0)headers["Content-Type"]="application/vnd.api+json";const response=await this.fetch(url,{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body)}),text=await response.text(),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 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 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 TypeError("A Lemon Squeezy customer is identified by email: the payer has none.");const existing=(await this.request("GET","/customers",{query:{"filter[store_id]":String(this.config.storeId),"filter[email]":payer.email}})).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 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}:{}}}}),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 TypeError(`A checkout line's quantity must be a positive whole number, got ${line.quantity}`);let variantId;const attributes={},productOptions={redirect_url:request.successUrl};if("price"in line)variantId=line.price;else{if(request.mode==="subscription")throw TypeError("A Lemon Squeezy subscription checkout needs a subscription variant: a line priced here has no billing interval.");if(!this.config.customPriceVariantId)throw 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 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 checkoutData={custom:{...request.metadata,...request.reference?{reference:request.reference}:{},stacks_user_id:String(payer.id)}};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===!0},checkout_data:checkoutData,...this.config.testMode?{test_mode:!0}:{}},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 TypeError("Lemon Squeezy finds a payer's subscriptions by email: the payer has none.");return(await this.list("/subscriptions",{"filter[store_id]":String(this.config.storeId),"filter[user_email]":payer.email})).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)),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??"",data=notification.data,attributes=data?.attributes??{},reference=typeof notification.meta?.custom_data?.reference==="string"?notification.meta.custom_data.reference:null,money=(amount)=>typeof amount==="number"&&typeof attributes.currency==="string"?{amount,currency:attributes.currency.toLowerCase()}:null,base={provider:this.name,id,providerType:name,reference:data?.id!==void 0?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 type={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"}[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.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,4 +1,4 @@
|
|
|
1
|
-
import{PaddleDriver}from"./paddle";import{PaymentProviderError}from"./types";export const PADDLE_JS_URL="https://cdn.paddle.com/paddle/v2/paddle.js"
|
|
1
|
+
import{PaddleDriver}from"./paddle";import{PaymentProviderError}from"./types";export const PADDLE_JS_URL="https://cdn.paddle.com/paddle/v2/paddle.js";export const PADDLE_CHECKOUT_SCRIPT_PATH="/payments/checkout.js";const TRANSACTION_ID=/^txn_[a-z\d]{26}$/;export const PADDLE_CHECKOUT_SCRIPT=`(function () {
|
|
2
2
|
var block = document.getElementById('stacks-paddle-checkout')
|
|
3
3
|
if (!block || !window.Paddle) return
|
|
4
4
|
var settings = JSON.parse(block.textContent || '{}')
|
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}$/,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"]),INTERVALS=new Set(["day","week","month","year"]);export function summarizePaddleSubscription(subscription){const price=subscription.items?.[0]?.price,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(),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 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 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||void 0}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!==void 0)headers["Content-Type"]="application/json";const response=await this.fetch(url,{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body)});if(response.status===204)return;const text=await response.text(),body=text?JSON.parse(text):void 0;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 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 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 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]:void 0;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),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)}`),currency=(transaction.details?.totals?.currency_code??transaction.currency_code??"").toLowerCase();if(currency&¤cy!==options.amount.currency.toLowerCase())throw 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 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}),total=adjustment.totals?.total,currency=adjustment.totals?.currency_code??adjustment.currency_code;return{id:adjustment.id,paymentId,status:paddleRefundStatus(adjustment.status),amount:total!==void 0&¤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 TypeError("A Paddle subscription checkout needs catalog prices (pri_...) with a billing cycle: a line priced here has none.");if(!request.currency)throw 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)}),customer=await this.customer(payer),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 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 TypeError("Not a Paddle transaction id.");const successUrl=(await this.request("GET",`/transactions/${transactionId}`)).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);return(await this.request("GET",`/customers/${customer.id}/payment-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:!1,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);return(await this.request("GET","/subscriptions",{query:{customer_id:customer.id}})??[]).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));if(!signature.signatures.some((given)=>{const actual=Buffer.from(given);return actual.length===expected.length&&timingSafeEqual(actual,expected)}))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??{},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,amount=totals?.grand_total!==void 0&&(totals.currency_code??data.currency_code)?{amount:Number(totals.grand_total),currency:String(totals.currency_code??data.currency_code).toLowerCase()}:null,type=notification.event_type==="transaction.completed"?"payment.succeeded":notification.event_type==="transaction.payment_failed"?"payment.failed":notification.event_type==="transaction.canceled"?"payment.canceled":"unknown",lastAttempt=Array.isArray(data.payments)?data.payments.at(-1):void 0;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,settled=adjustment.action==="refund"&&(adjustment.status==="approved"||adjustment.status==="rejected"),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!==void 0&¤cy?{amount:Number(adjustment.totals.total),currency:currency.toLowerCase()}:null,reason:adjustment.status==="rejected"?adjustment.reason??null:null}}return{...base,type:{"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"}[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.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.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 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 fromItem=subscription.items?.data?.[0]?.current_period_end;if(typeof fromItem==="number")return fromItem;const legacy=subscription.current_period_end;return typeof legacy==="number"?legacy:void 0}export function summarizeSubscription(subscription){const item=subscription.items?.data?.[0],periodEnd=subscriptionPeriodEnd(subscription),price=item?.price,invoice=subscription.latest_invoice,secret=invoice&&typeof invoice==="object"?invoice.confirmation_secret?.client_secret:void 0;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),intent=await this.ops.createIntent(payer,{amount:toStripeAmount(amount),currency:amount.currency.toLowerCase(),customer:customer.id,payment_method:paymentMethod,confirm:!0,automatic_payment_methods:{enabled:!0,allow_redirects:"never"},off_session:!0,...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),intent=await this.ops.createIntent(payer,{amount:toStripeAmount(amount),currency:amount.currency.toLowerCase(),customer:customer.id,automatic_payment_methods:{enabled:!0},...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!==void 0&&(!Number.isSafeInteger(request.trialDays)||request.trialDays<1))throw TypeError("trialDays is a whole number of days, at least 1.");if(request.trialDays&&request.mode!=="subscription")throw TypeError("trialDays applies to a subscription checkout.");const customer=await this.ops.customer(payer),lineItems=request.lines.map((line)=>{if("price"in line)return{price:line.price,quantity:line.quantity};if(!request.currency)throw 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}}}}),carried={...request.metadata,...request.reference?{reference:request.reference}:{}},hasCarried=Object.keys(carried).length>0,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:!0}:{},...request.automaticTax?{automatic_tax:{enabled:!0}}:{},...request.paymentMethods?.length?{allowed_payment_method_types:[...request.paymentMethods]}:{}});if(!session.url)throw 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),defaultId=typeof customer.invoice_settings?.default_payment_method==="string"?customer.invoice_settings.default_payment_method:customer.invoice_settings?.default_payment_method?.id??null;return(await this.ops.listPaymentMethods(customer.id)).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??!1))}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,reference=event.type==="charge.refunded"||event.type==="refund.failed"?object.payment_intent??object.id:object.id,minor=event.type==="charge.refunded"?refundedThisTime(object,event.data.previous_attributes):object.amount??object.amount_total,amount=typeof minor==="number"&&object.currency?fromStripeAmount(minor,String(object.currency)):null,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:!0})}}
|
|
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})}}
|
package/dist/driver/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class PaymentUnsupportedError extends Error{driver;operation;constructor(driver,operation,detail){super(`The ${driver} payment driver does not support ${operation}${detail?`: ${detail}`:"."}`);this.name="PaymentUnsupportedError";this.driver=driver;this.operation=operation}}export class PaymentProviderError extends Error{driver;status;code;constructor(driver,status,message,code=null){super(`${driver} rejected the request (${status}${code?` ${code}`:""}): ${message}`);this.name="PaymentProviderError";this.driver=driver;this.status=status;this.code=code}}export class WebhookNotConfiguredError extends Error{driver;constructor(driver,detail){super(detail);this.name="WebhookNotConfiguredError";this.driver=driver}}export class WebhookSignatureError extends Error{constructor(driver,detail){super(`The ${driver} webhook signature does not verify: ${detail}`);this.name="WebhookSignatureError"}}export function headerOf(headers,name){if(typeof headers.get==="function")return headers.get(name);const wanted=name.toLowerCase();for(const[key,value]of Object.entries(headers))if(key.toLowerCase()===wanted)return value??null
|
|
1
|
+
export class PaymentUnsupportedError extends Error{driver;operation;constructor(driver,operation,detail){super(`The ${driver} payment driver does not support ${operation}${detail?`: ${detail}`:"."}`);this.name="PaymentUnsupportedError";this.driver=driver;this.operation=operation}}export class PaymentProviderError extends Error{driver;status;code;constructor(driver,status,message,code=null){super(`${driver} rejected the request (${status}${code?` ${code}`:""}): ${message}`);this.name="PaymentProviderError";this.driver=driver;this.status=status;this.code=code}}export class WebhookNotConfiguredError extends Error{driver;constructor(driver,detail){super(detail);this.name="WebhookNotConfiguredError";this.driver=driver}}export class WebhookSignatureError extends Error{constructor(driver,detail){super(`The ${driver} webhook signature does not verify: ${detail}`);this.name="WebhookSignatureError"}}export function headerOf(headers,name){if(typeof headers.get==="function")return headers.get(name);const wanted=name.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===wanted)return value??null}return null}export function assertMoney(money,label="amount"){if(!Number.isInteger(money.amount)||money.amount<0)throw new TypeError(`${label} must be a whole number of minor units (cents), got ${money.amount}`);if(!/^[a-z]{3}$/i.test(money.currency))throw new TypeError(`${label} currency must be an ISO 4217 code, got "${money.currency}"`)}
|
package/dist/drivers/stripe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{services}from"@stacksjs/config";const require=createRequire(import.meta.url);function StripeCtor(){try{return require("stripe")}catch{throw Error(describeStripeAvailability({key
|
|
1
|
+
import{createRequire}from"node:module";import{services}from"@stacksjs/config";const require=createRequire(import.meta.url);function StripeCtor(){try{return require("stripe")}catch{throw new Error(describeStripeAvailability({key:true,sdk:false}))}}let _stripe=null;export function stripeAvailability(){return{key:Boolean(String(services?.stripe?.secretKey||"").trim()),sdk:isStripeSdkInstalled()}}function isStripeSdkInstalled(){try{require.resolve("stripe");return true}catch{return false}}export function isStripeConfigured(){const{key,sdk}=stripeAvailability();return key&&sdk}export function describeStripeAvailability(available){if(available.key&&available.sdk)return null;const reasons=[];if(!available.sdk){reasons.push("the `stripe` package is not installed (it is an optional peer, which Bun does not install for you - "+"run `bun add stripe` in your app, pinned to an exact version)")}if(!available.key)reasons.push("no Stripe secret key is configured (set STRIPE_SECRET_KEY in your .env)");return`Stripe is being used but is not usable here: ${reasons.join("; and ")}.`}export function reportStripeAvailability(options={}){const available=options.available??stripeAvailability();if(!available.key||available.sdk)return null;const message=describeStripeAvailability(available);(options.warn??console.warn)(`[stacks] ${message}`);return message}export const stripe=new Proxy({},{get(_target,prop){if(!_stripe){const unusable=describeStripeAvailability(stripeAvailability());if(unusable)throw new Error(unusable);const apiKey=String(services?.stripe?.secretKey||"").trim();const Stripe=StripeCtor();const apiVersion=Stripe.API_VERSION;const configuredVersion=services?.stripe?.apiVersion;if(configuredVersion&&configuredVersion!==apiVersion)throw new Error(`Stripe API version ${configuredVersion} does not match the installed SDK version ${apiVersion}`);_stripe=new Stripe(apiKey,{apiVersion})}return _stripe[prop]}});
|
package/dist/idempotency.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";const KEY_PREFIX="stacks"
|
|
1
|
+
import{createHash}from"node:crypto";const KEY_PREFIX="stacks";const KEY_VERSION="v1";const MAX_KEY_LENGTH=255;export function stacksIdempotencyKey(scope,...parts){const tail=parts.filter((p)=>p!==null&&p!==undefined&&p!=="").map((p)=>String(p)).join(":");const raw=tail?`${KEY_PREFIX}:${scope}:${tail}:${KEY_VERSION}`:`${KEY_PREFIX}:${scope}:${KEY_VERSION}`;if(raw.length<=MAX_KEY_LENGTH)return raw;const hashed=createHash("sha256").update(tail).digest("hex").slice(0,32);return`${KEY_PREFIX}:${scope}:${hashed}:${KEY_VERSION}`}export function freshIdempotencyKey(scope,...parts){const random=createHash("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,16);return stacksIdempotencyKey(scope,...parts,random)}export function idempotencyFingerprint(value){return createHash("sha256").update(stableJson(value)).digest("hex").slice(0,24)}function stableJson(value){if(value===null||typeof value!=="object")return JSON.stringify(value)??"null";if(Array.isArray(value))return`[${value.map((item)=>stableJson(item===undefined?null:item)).join(",")}]`;const entries=Object.keys(value).filter((key)=>value[key]!==undefined).sort().map((key)=>`${JSON.stringify(key)}:${stableJson(value[key])}`);return`{${entries.join(",")}}`}
|
package/dist/payment.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stripe}from"./drivers/stripe";import{manageCustomer}from"./billable/customer";import{manageInvoice}from"./billable/invoice";import{managePaymentMethod}from"./billable/payment-method";import{managePrice}from"./billable/price";import{manageBillingPortal}from"./billable/portal";import{manageCoupon,managePriceExtended,manageProduct}from"./billable/product";import{manageSubscription}from"./billable/subscription";import{manageSetupIntent}from"./billable/intent";import{manageWebhook,onCharge,onCheckout,onInvoice,onPaymentIntent,onSubscription,processWebhook}from"./billable/webhook";import{connect}from"./connect";import{assertStripeDriver,configuredPaymentDriver,paymentDriver}from"./driver";export async function charge(payer,amount,paymentMethod,options={}){return paymentDriver().charge(payer,amount,paymentMethod,options)}export async function createPayment(payer,amount,options={}){return paymentDriver().createPayment(payer,amount,options)}export async function refund(paymentId,options={}){return paymentDriver().refund(paymentId,options)}export async function checkout(payer,request){return paymentDriver().checkout(payer,request)}export async function subscriptionCheckout(payer,price,options){const{quantity=1,...request}=options;return paymentDriver().checkout(payer,{...request,mode:"subscription",lines:[{price,quantity}]})}export async function subscribe(payer,price,options={}){return paymentDriver().subscribe(payer,price,options)}export async function cancelSubscription(subscriptionId,options={}){return paymentDriver().cancelSubscription(subscriptionId,options)}export async function subscriptions(payer){return paymentDriver().subscriptions(payer)}export async function hasActiveSubscription(user,type="default"){return manageSubscription.isValid(user,type)}export async function changeSubscription(user,newLookupKey,type="default"){assertStripeDriver("changeSubscription");return manageSubscription.update(user,type,newLookupKey,{})}export async function getOrCreateCustomer(payer){return paymentDriver().customer(payer)}export async function updateCustomer(user,options){assertStripeDriver("updateCustomer");return manageCustomer.updateStripeCustomer(user,options)}export async function deleteCustomer(user){assertStripeDriver("deleteCustomer");return manageCustomer.deleteStripeUser(user)}export async function paymentMethods(payer){return paymentDriver().paymentMethods(payer)}export async function removePaymentMethod(payer,paymentMethodId){return paymentDriver().removePaymentMethod(payer,paymentMethodId)}export async function addPaymentMethod(user,paymentMethodId){assertStripeDriver("addPaymentMethod");return managePaymentMethod.addPaymentMethod(user,paymentMethodId)}export async function setDefaultPaymentMethod(user,paymentMethodId){assertStripeDriver("setDefaultPaymentMethod");return managePaymentMethod.setUserDefaultPayment(user,paymentMethodId)}export async function createSetupIntent(user,options={}){assertStripeDriver("createSetupIntent");return manageSetupIntent.create(user,options)}export async function getInvoices(user){assertStripeDriver("getInvoices");return manageInvoice.list(user)}export async function createInvoice(customerId,options={}){assertStripeDriver("createInvoice");return stripe.invoices.create({customer:customerId,...options})}export async function payInvoice(invoiceId){assertStripeDriver("payInvoice");return stripe.invoices.pay(invoiceId)}export async function createProduct(name,price,options={}){assertStripeDriver("createProduct");const{currency="usd",interval,description,metadata}=options
|
|
1
|
+
import{stripe}from"./drivers/stripe";import{manageCustomer}from"./billable/customer";import{manageInvoice}from"./billable/invoice";import{managePaymentMethod}from"./billable/payment-method";import{managePrice}from"./billable/price";import{manageBillingPortal}from"./billable/portal";import{manageCoupon,managePriceExtended,manageProduct}from"./billable/product";import{manageSubscription}from"./billable/subscription";import{manageSetupIntent}from"./billable/intent";import{manageWebhook,onCharge,onCheckout,onInvoice,onPaymentIntent,onSubscription,processWebhook}from"./billable/webhook";import{connect}from"./connect";import{assertStripeDriver,configuredPaymentDriver,paymentDriver}from"./driver";export async function charge(payer,amount,paymentMethod,options={}){return paymentDriver().charge(payer,amount,paymentMethod,options)}export async function createPayment(payer,amount,options={}){return paymentDriver().createPayment(payer,amount,options)}export async function refund(paymentId,options={}){return paymentDriver().refund(paymentId,options)}export async function checkout(payer,request){return paymentDriver().checkout(payer,request)}export async function subscriptionCheckout(payer,price,options){const{quantity=1,...request}=options;return paymentDriver().checkout(payer,{...request,mode:"subscription",lines:[{price,quantity}]})}export async function subscribe(payer,price,options={}){return paymentDriver().subscribe(payer,price,options)}export async function cancelSubscription(subscriptionId,options={}){return paymentDriver().cancelSubscription(subscriptionId,options)}export async function subscriptions(payer){return paymentDriver().subscriptions(payer)}export async function hasActiveSubscription(user,type="default"){return manageSubscription.isValid(user,type)}export async function changeSubscription(user,newLookupKey,type="default"){assertStripeDriver("changeSubscription");return manageSubscription.update(user,type,newLookupKey,{})}export async function getOrCreateCustomer(payer){return paymentDriver().customer(payer)}export async function updateCustomer(user,options){assertStripeDriver("updateCustomer");return manageCustomer.updateStripeCustomer(user,options)}export async function deleteCustomer(user){assertStripeDriver("deleteCustomer");return manageCustomer.deleteStripeUser(user)}export async function paymentMethods(payer){return paymentDriver().paymentMethods(payer)}export async function removePaymentMethod(payer,paymentMethodId){return paymentDriver().removePaymentMethod(payer,paymentMethodId)}export async function addPaymentMethod(user,paymentMethodId){assertStripeDriver("addPaymentMethod");return managePaymentMethod.addPaymentMethod(user,paymentMethodId)}export async function setDefaultPaymentMethod(user,paymentMethodId){assertStripeDriver("setDefaultPaymentMethod");return managePaymentMethod.setUserDefaultPayment(user,paymentMethodId)}export async function createSetupIntent(user,options={}){assertStripeDriver("createSetupIntent");return manageSetupIntent.create(user,options)}export async function getInvoices(user){assertStripeDriver("getInvoices");return manageInvoice.list(user)}export async function createInvoice(customerId,options={}){assertStripeDriver("createInvoice");return stripe.invoices.create({customer:customerId,...options})}export async function payInvoice(invoiceId){assertStripeDriver("payInvoice");return stripe.invoices.pay(invoiceId)}export async function createProduct(name,price,options={}){assertStripeDriver("createProduct");const{currency="usd",interval,description,metadata}=options;const priceParams={unit_amount:price,currency};if(interval){priceParams.recurring={interval}}return manageProduct.createWithPrice({name,description,metadata},priceParams)}export async function getPrice(lookupKey){assertStripeDriver("getPrice");return managePrice.retrieveByLookupKey(lookupKey)}export async function listProducts(options={}){assertStripeDriver("listProducts");return manageProduct.list(options)}export async function createCoupon(options){assertStripeDriver("createCoupon");const params={duration:options.duration||"once"};if(options.percentOff){params.percent_off=options.percentOff}else if(options.amountOff){params.amount_off=options.amountOff;params.currency=options.currency||"usd"}if(options.name)params.name=options.name;if(options.durationInMonths)params.duration_in_months=options.durationInMonths;if(options.maxRedemptions)params.max_redemptions=options.maxRedemptions;return manageCoupon.create(params)}export async function createPromoCode(couponId,code,options={}){assertStripeDriver("createPromoCode");return manageCoupon.createPromotionCode({promotion:{type:"coupon",coupon:couponId},code,...options})}export async function validatePromoCode(code){assertStripeDriver("validatePromoCode");return manageCoupon.retrievePromotionCode(code)}const STRIPE_ZERO_DECIMAL=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);export function minorUnitExponent(currency,driver=configuredPaymentDriver()){const code=currency.trim().toLowerCase();if(driver==="stripe")return STRIPE_ZERO_DECIMAL.has(code)?0:2;try{return new Intl.NumberFormat("en",{style:"currency",currency:code.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}export function formatAmount(amount,currency){const cfg=globalThis.config||{};const ccy=(currency||cfg.payment?.currency||cfg.billing?.currency||process.env.STRIPE_CURRENCY||"usd").toLowerCase();const locale=cfg.app?.locale||"en-US";return new Intl.NumberFormat(locale,{style:"currency",currency:ccy.toUpperCase()}).format(amount/10**minorUnitExponent(ccy))}export function toCents(dollars){return Math.round(dollars*100)}export function toDollars(cents){return cents/100}export async function billingPortal(customer,options={}){assertStripeDriver("billingPortal");const customerId=typeof customer==="string"?customer:customer.stripe_id;if(!customerId)throw new Error("billingPortal needs a Stripe customer: this user has no stripe_id yet.");return manageBillingPortal.createSession(customerId,options)}export const Payment={driver:paymentDriver,charge,createPayment,refund,checkout,subscriptionCheckout,subscribe,cancelSubscription,subscriptions,hasActiveSubscription,changeSubscription,getOrCreateCustomer,updateCustomer,deleteCustomer,paymentMethods,addPaymentMethod,setDefaultPaymentMethod,removePaymentMethod,createSetupIntent,getInvoices,createInvoice,payInvoice,createProduct,getPrice,listProducts,billingPortal,createCoupon,createPromoCode,validatePromoCode,formatAmount,minorUnitExponent,toCents,toDollars,webhook:manageWebhook,onPaymentIntent,onSubscription,onInvoice,onCheckout,onCharge,processWebhook,connect,stripe,customer:manageCustomer,subscription:manageSubscription,invoice:manageInvoice,paymentMethod:managePaymentMethod,product:manageProduct,price:managePriceExtended,coupon:manageCoupon};export default Payment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function subscriptionGrantsAccess(status){return status==="active"||status==="trialing"}export function subscriptionPeriod(subscription){const item=subscription.items?.data?.[0]
|
|
1
|
+
export function subscriptionGrantsAccess(status){return status==="active"||status==="trialing"}export function subscriptionPeriod(subscription){const item=subscription.items?.data?.[0];const iso=(value)=>value&&Number.isFinite(value)&&value>0?new Date(value*1000).toISOString():null;return{start:iso(subscription.current_period_start??item?.current_period_start),end:iso(subscription.current_period_end??item?.current_period_end)}}
|
package/dist/terminal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class StripeApiError extends Error{status;type;code;declineCode;param;constructor(message,status,error={}){super(message);this.status=status;this.name="StripeApiError";this.type=error.type||(status===0?"api_connection_error":"api_error");this.code=error.code??null;this.declineCode=error.decline_code??null;this.param=error.param??null}get definitive(){return["invalid_request_error","card_error","authentication_error","permission_error"].includes(this.type)}}export const STRIPE_TERMINAL_API_VERSION="2026-09-30.endive";export function stripeFormEncode(params){const pairs=[]
|
|
1
|
+
export class StripeApiError extends Error{status;type;code;declineCode;param;constructor(message,status,error={}){super(message);this.status=status;this.name="StripeApiError";this.type=error.type||(status===0?"api_connection_error":"api_error");this.code=error.code??null;this.declineCode=error.decline_code??null;this.param=error.param??null}get definitive(){return["invalid_request_error","card_error","authentication_error","permission_error"].includes(this.type)}}export const STRIPE_TERMINAL_API_VERSION="2026-09-30.endive";export function stripeFormEncode(params){const pairs=[];const add=(key,value)=>{if(value===null||value===undefined)return;if(Array.isArray(value)){value.forEach((item,index)=>add(`${key}[${index}]`,item));return}if(typeof value==="object"){for(const[child,inner]of Object.entries(value))add(`${key}[${child}]`,inner);return}pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)};for(const[key,value]of Object.entries(params))add(key,value);return pairs.join("&")}export function stripeRest(options){const base=(options.apiBase||"https://api.stripe.com").replace(/\/$/,"");const doFetch=options.fetch??fetch;return{async request(method,path,params={},requestOptions={}){const body=stripeFormEncode(params);const url=method==="POST"||!body?`${base}${path}`:`${base}${path}?${body}`;const headers={Authorization:`Bearer ${options.secretKey}`,Accept:"application/json"};if(method==="POST")headers["Content-Type"]="application/x-www-form-urlencoded";const version=options.apiVersion===undefined?STRIPE_TERMINAL_API_VERSION:options.apiVersion;if(version)headers["Stripe-Version"]=version;if(options.stripeAccount)headers["Stripe-Account"]=options.stripeAccount;if(requestOptions.idempotencyKey)headers["Idempotency-Key"]=requestOptions.idempotencyKey;let res;try{res=await doFetch(url,{method,headers,body:method==="POST"?body:undefined,signal:AbortSignal.timeout(options.timeoutMs??30000)})}catch(error){throw new StripeApiError(`Could not reach Stripe: ${error instanceof Error?error.message:String(error)}`,0)}const text=await res.text();let json=null;try{json=text?JSON.parse(text):null}catch{json=null}if(!res.ok){const error=json?.error&&typeof json.error==="object"?json.error:{};throw new StripeApiError(typeof error.message==="string"&&error.message?error.message:`Stripe answered ${res.status}`,res.status,error)}return json}}}const path=(value)=>encodeURIComponent(value);export function stripeTerminal(options){const api=stripeRest(options);return{connectionToken:(location)=>api.request("POST","/v1/terminal/connection_tokens",{location}),createLocation:(input,idempotencyKey)=>api.request("POST","/v1/terminal/locations",{display_name:input.displayName,address:{...input.address},metadata:input.metadata},{idempotencyKey}),retrieveLocation:(id)=>api.request("GET",`/v1/terminal/locations/${path(id)}`),registerReader:(input)=>api.request("POST","/v1/terminal/readers",{registration_code:input.registrationCode,label:input.label,location:input.location,metadata:input.metadata}),retrieveReader:(id)=>api.request("GET",`/v1/terminal/readers/${path(id)}`),async listReaders(filter={}){const page=await api.request("GET","/v1/terminal/readers",{location:filter.location,limit:filter.limit??100});return Array.isArray(page?.data)?page.data:[]},deleteReader:(id)=>api.request("DELETE",`/v1/terminal/readers/${path(id)}`),createPaymentIntent:(input,idempotencyKey)=>api.request("POST","/v1/payment_intents",{amount:input.amount,currency:input.currency.toLowerCase(),allowed_payment_method_types:["card_present"],capture_method:input.captureMethod??"automatic",description:input.description,metadata:input.metadata,on_behalf_of:input.onBehalfOf,transfer_data:input.transferDestination?{destination:input.transferDestination}:undefined,application_fee_amount:input.applicationFeeAmount&&input.applicationFeeAmount>0?input.applicationFeeAmount:undefined,statement_descriptor_suffix:input.statementDescriptorSuffix},{idempotencyKey}),retrievePaymentIntent:(id)=>api.request("GET",`/v1/payment_intents/${path(id)}`,{expand:["latest_charge"]}),cancelPaymentIntent:(id)=>api.request("POST",`/v1/payment_intents/${path(id)}/cancel`),processPaymentIntent:(readerId,paymentIntentId,idempotencyKey)=>api.request("POST",`/v1/terminal/readers/${path(readerId)}/process_payment_intent`,{payment_intent:paymentIntentId},{idempotencyKey}),cancelReaderAction:(readerId)=>api.request("POST",`/v1/terminal/readers/${path(readerId)}/cancel_action`),presentPaymentMethod:(readerId,card={})=>api.request("POST",`/v1/test_helpers/terminal/readers/${path(readerId)}/present_payment_method`,{type:card.type,card_present:card.number?{number:card.number}:undefined}),refund:(input,idempotencyKey)=>api.request("POST","/v1/refunds",{payment_intent:input.paymentIntent,amount:input.amount,reverse_transfer:input.reverseTransfer,refund_application_fee:input.refundApplicationFee,reason:input.reason,metadata:input.metadata},{idempotencyKey})}}export function terminalChargeState(paymentIntent,reader){const status=paymentIntent?.status;if(status==="succeeded"||status==="requires_capture")return{state:"succeeded",failureCode:null,failureMessage:null};if(status==="canceled")return{state:"canceled",failureCode:null,failureMessage:null};const action=reader?.action;const forThis=!!action&&action.type==="process_payment_intent"&&(!paymentIntent?.id||action.process_payment_intent?.payment_intent===paymentIntent.id);if(forThis&&action.status==="failed")return{state:"failed",failureCode:action.failure_code||"reader_action_failed",failureMessage:action.failure_message||null};if(forThis&&action.status==="in_progress")return{state:"waiting",failureCode:null,failureMessage:null};const error=paymentIntent?.last_payment_error;if(status==="requires_payment_method"&&error)return{state:"failed",failureCode:error.decline_code||error.code||"card_declined",failureMessage:error.message||null};return{state:"waiting",failureCode:null,failureMessage:null}}export function cardPresentDetails(chargeOrIntent){const charge=chargeOrIntent?.object==="payment_intent"?typeof chargeOrIntent.latest_charge==="object"&&chargeOrIntent.latest_charge?chargeOrIntent.latest_charge:chargeOrIntent.charges?.data?.[0]:chargeOrIntent;const card=charge?.payment_method_details?.card_present??charge?.payment_method_details?.interac_present;if(!card)return null;const receipt=card.receipt??{};const text=(value)=>typeof value==="string"&&value?value:null;return{brand:text(card.brand),last4:text(card.last4),funding:text(card.funding),readMethod:text(card.read_method),applicationName:text(receipt.application_preferred_name),applicationId:text(receipt.dedicated_file_name),authorizationCode:text(charge.authorization_code??receipt.authorization_code),authorizationResponseCode:text(receipt.authorization_response_code),accountType:text(receipt.account_type),cardholderVerification:text(receipt.cardholder_verification_method)}}export function latestChargeId(paymentIntent){const charge=paymentIntent?.latest_charge;if(typeof charge==="string"&&charge)return charge;if(charge&&typeof charge.id==="string")return charge.id;const legacy=paymentIntent?.charges?.data?.[0]?.id;return typeof legacy==="string"?legacy:null}export const SIMULATED_READER_CODES=["simulated-wpe","simulated-s700","simulated-s710","simulated-v660p","simulated-wp3"];export function isTestKey(secretKey){return typeof secretKey==="string"&&/^(sk|rk)_test_/.test(secretKey)}
|
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.518",
|
|
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.518",
|
|
64
|
+
"@stacksjs/database": "0.75.518",
|
|
65
|
+
"@stacksjs/error-handling": "0.75.518",
|
|
66
|
+
"@stacksjs/logging": "0.75.518",
|
|
67
|
+
"@stacksjs/orm": "0.75.518",
|
|
68
|
+
"@stacksjs/types": "0.75.518"
|
|
69
69
|
},
|
|
70
70
|
"peerDependencies": {
|
|
71
71
|
"@stripe/stripe-js": "^10.0.0",
|
|
@@ -80,7 +80,7 @@
|
|
|
80
80
|
}
|
|
81
81
|
},
|
|
82
82
|
"devDependencies": {
|
|
83
|
-
"@stacksjs/utils": "0.75.
|
|
83
|
+
"@stacksjs/utils": "0.75.518",
|
|
84
84
|
"@stripe/stripe-js": "^10.0.0",
|
|
85
85
|
"better-dx": "^0.2.24",
|
|
86
86
|
"stripe": "23.0.0"
|