@windrun-huaiin/backend-core 14.0.0 → 14.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -85,7 +85,7 @@ exports.createCheckoutSession = stripeConfig.createCheckoutSession;
85
85
  exports.createCustomerPortalSession = stripeConfig.createCustomerPortalSession;
86
86
  exports.createOrGetCustomer = stripeConfig.createOrGetCustomer;
87
87
  exports.fetchPaymentId = stripeConfig.fetchPaymentId;
88
- exports.stripe = stripeConfig.stripe;
88
+ exports.getStripe = stripeConfig.getStripe;
89
89
  exports.updateSubscription = stripeConfig.updateSubscription;
90
90
  exports.validateStripeWebhook = stripeConfig.validateStripeWebhook;
91
91
  exports.ApiAuthUtils = authUtils.ApiAuthUtils;
package/dist/index.mjs CHANGED
@@ -16,7 +16,7 @@ export { getActiveProviderConfig, getCreditsFromPriceId, getPriceConfig, moneyPr
16
16
  export { getMoneyPriceInitUserContext } from './lib/money-price-helper.mjs';
17
17
  export { fingerprintConfig } from './lib/fingerprint-config.mjs';
18
18
  export { creditsConfig, freeAmount, freeExpiredDays, freeRegisterAmount, oneTimeExpiredDays } from './lib/credit-init.mjs';
19
- export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, stripe, updateSubscription, validateStripeWebhook } from './lib/stripe-config.mjs';
19
+ export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, getStripe, updateSubscription, validateStripeWebhook } from './lib/stripe-config.mjs';
20
20
  export { ApiAuthUtils, getAuthenticatedUser, requireAuth, requireAuthWithUser } from './lib/auth-utils.mjs';
21
21
  export { getQstash, getRedis, withQstash, withRedis } from './lib/upstash-config.mjs';
22
22
  export { acquireLock, releaseLock, withLock } from './lib/upstash/redis-lock.mjs';
package/dist/lib/index.js CHANGED
@@ -33,7 +33,7 @@ exports.createCheckoutSession = stripeConfig.createCheckoutSession;
33
33
  exports.createCustomerPortalSession = stripeConfig.createCustomerPortalSession;
34
34
  exports.createOrGetCustomer = stripeConfig.createOrGetCustomer;
35
35
  exports.fetchPaymentId = stripeConfig.fetchPaymentId;
36
- exports.stripe = stripeConfig.stripe;
36
+ exports.getStripe = stripeConfig.getStripe;
37
37
  exports.updateSubscription = stripeConfig.updateSubscription;
38
38
  exports.validateStripeWebhook = stripeConfig.validateStripeWebhook;
39
39
  exports.ApiAuthUtils = authUtils.ApiAuthUtils;
@@ -2,7 +2,7 @@ export { getActiveProviderConfig, getCreditsFromPriceId, getPriceConfig, moneyPr
2
2
  export { getMoneyPriceInitUserContext } from './money-price-helper.mjs';
3
3
  export { fingerprintConfig } from './fingerprint-config.mjs';
4
4
  export { creditsConfig, freeAmount, freeExpiredDays, freeRegisterAmount, oneTimeExpiredDays } from './credit-init.mjs';
5
- export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, stripe, updateSubscription, validateStripeWebhook } from './stripe-config.mjs';
5
+ export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, getStripe, updateSubscription, validateStripeWebhook } from './stripe-config.mjs';
6
6
  export { ApiAuthUtils, getAuthenticatedUser, requireAuth, requireAuthWithUser } from './auth-utils.mjs';
7
7
  export { getQstash, getRedis, withQstash, withRedis } from './upstash-config.mjs';
8
8
  export { acquireLock, releaseLock, withLock } from './upstash/redis-lock.mjs';
@@ -1,5 +1,5 @@
1
1
  import Stripe from 'stripe';
2
- export declare const stripe: Stripe;
2
+ export declare const getStripe: () => Stripe;
3
3
  export declare const validateStripeWebhook: (payload: string | Buffer, signature: string, secret: string) => Stripe.Event;
4
4
  export interface BasicCheckoutSessionParams {
5
5
  priceId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"stripe-config.d.ts","sourceRoot":"","sources":["../../src/lib/stripe-config.ts"],"names":[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AAE,MAAM,CAAC;IAChB,iBAAiB,CAAC,EAAE,mBAAmB,GAAG,MAAM,GAAG,gBAAgB,CAAC;CACrE,KAAG,OAAO,CAAC,MAAM,CAAC,YAAY,CAiC9B,CAAC;AAEF,eAAO,MAAM,2BAA2B,GAAU,QAAQ;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,KAAG,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,OAAO,CAqBvC,CAAC;AAGF,eAAO,MAAM,kBAAkB,GAC7B,gBAAgB,MAAM,EACtB,oBAAmB,OAAc,KAChC,OAAO,CAAC,MAAM,CAAC,YAAY,CAiC7B,CAAC;AAEF,qBAAa,6BAA8B,SAAQ,KAAK;;CAKvD"}
@@ -9,13 +9,22 @@ require('@prisma/client');
9
9
  require('../prisma/prisma.js');
10
10
  var apilog_service = require('../services/database/apilog.service.js');
11
11
 
12
- // Stripe Configuration
13
- const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
14
- apiVersion: '2025-11-17.clover',
15
- });
12
+ let stripeInstance = null;
13
+ const getStripe = () => {
14
+ const apiKey = process.env.STRIPE_SECRET_KEY;
15
+ if (!apiKey) {
16
+ throw new Error('STRIPE_SECRET_KEY is not configured');
17
+ }
18
+ if (!stripeInstance) {
19
+ stripeInstance = new Stripe(apiKey, {
20
+ apiVersion: '2025-11-17.clover',
21
+ });
22
+ }
23
+ return stripeInstance;
24
+ };
16
25
  // Helper function to validate webhook signature
17
26
  const validateStripeWebhook = (payload, signature, secret) => {
18
- return stripe.webhooks.constructEvent(payload, signature, secret);
27
+ return getStripe().webhooks.constructEvent(payload, signature, secret);
19
28
  };
20
29
  // Helper function to create checkout session
21
30
  const createCheckoutSession = (params, subscriptionData) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
@@ -64,7 +73,7 @@ const createCheckoutSession = (params, subscriptionData) => tslib_es6.__awaiter(
64
73
  // Create log record with request
65
74
  const logId = yield apilog_service.Apilogger.logStripeOutgoing('createCheckoutSession', params);
66
75
  try {
67
- const session = yield stripe.checkout.sessions.create(sessionParams);
76
+ const session = yield getStripe().checkout.sessions.create(sessionParams);
68
77
  // Update log record with response
69
78
  apilog_service.Apilogger.updateResponse(logId, {
70
79
  session_id: session.id,
@@ -84,7 +93,7 @@ const createCheckoutSession = (params, subscriptionData) => tslib_es6.__awaiter(
84
93
  // 根据发票ID去查支付ID
85
94
  const fetchPaymentId = (invoiceId) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
86
95
  var _a, _b;
87
- const fullInvoice = yield stripe.invoices.retrieve(invoiceId, {
96
+ const fullInvoice = yield getStripe().invoices.retrieve(invoiceId, {
88
97
  expand: ['payments']
89
98
  });
90
99
  const payment = (_a = fullInvoice.payments) === null || _a === void 0 ? void 0 : _a.data[0];
@@ -109,7 +118,7 @@ const createOrGetCustomer = (params) => tslib_es6.__awaiter(void 0, void 0, void
109
118
  });
110
119
  if (user.stripeCusId) {
111
120
  try {
112
- const customer = yield stripe.customers.retrieve(user.stripeCusId);
121
+ const customer = yield getStripe().customers.retrieve(user.stripeCusId);
113
122
  if ('deleted' in customer) {
114
123
  yield setStripeCustomerId(null);
115
124
  }
@@ -127,7 +136,7 @@ const createOrGetCustomer = (params) => tslib_es6.__awaiter(void 0, void 0, void
127
136
  }
128
137
  }
129
138
  if (user.email) {
130
- const existingCustomers = yield stripe.customers.list({
139
+ const existingCustomers = yield getStripe().customers.list({
131
140
  email: user.email,
132
141
  limit: 1,
133
142
  });
@@ -159,7 +168,7 @@ const createOrGetCustomer = (params) => tslib_es6.__awaiter(void 0, void 0, void
159
168
  name: customerParams.name,
160
169
  });
161
170
  try {
162
- const customer = yield stripe.customers.create(customerParams);
171
+ const customer = yield getStripe().customers.create(customerParams);
163
172
  yield setStripeCustomerId(customer.id);
164
173
  // Update log record with response
165
174
  apilog_service.Apilogger.updateResponse(logId, {
@@ -179,11 +188,11 @@ const createOrGetCustomer = (params) => tslib_es6.__awaiter(void 0, void 0, void
179
188
  // Helper function to update subscription
180
189
  const updateSubscription = (params) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
181
190
  const { subscriptionId, priceId, prorationBehavior = 'create_prorations' } = params;
182
- const subscription = yield stripe.subscriptions.retrieve(subscriptionId);
191
+ const subscription = yield getStripe().subscriptions.retrieve(subscriptionId);
183
192
  // Create log record with request
184
193
  const logId = yield apilog_service.Apilogger.logStripeOutgoing('updateSubscription', params);
185
194
  try {
186
- const updatedSubscription = yield stripe.subscriptions.update(subscriptionId, {
195
+ const updatedSubscription = yield getStripe().subscriptions.update(subscriptionId, {
187
196
  items: [
188
197
  {
189
198
  id: subscription.items.data[0].id,
@@ -210,7 +219,7 @@ const updateSubscription = (params) => tslib_es6.__awaiter(void 0, void 0, void
210
219
  const createCustomerPortalSession = (params) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
211
220
  const logId = yield apilog_service.Apilogger.logStripeOutgoing('createCustomerPortalSession', params);
212
221
  try {
213
- const session = yield stripe.billingPortal.sessions.create({
222
+ const session = yield getStripe().billingPortal.sessions.create({
214
223
  customer: params.customerId,
215
224
  return_url: params.returnUrl,
216
225
  });
@@ -237,12 +246,12 @@ const cancelSubscription = (subscriptionId_1, ...args_1) => tslib_es6.__awaiter(
237
246
  try {
238
247
  let result;
239
248
  if (cancelAtPeriodEnd) {
240
- result = yield stripe.subscriptions.update(subscriptionId, {
249
+ result = yield getStripe().subscriptions.update(subscriptionId, {
241
250
  cancel_at_period_end: true,
242
251
  });
243
252
  }
244
253
  else {
245
- result = yield stripe.subscriptions.cancel(subscriptionId);
254
+ result = yield getStripe().subscriptions.cancel(subscriptionId);
246
255
  }
247
256
  // Update log record with response
248
257
  apilog_service.Apilogger.updateResponse(logId, {
@@ -273,6 +282,6 @@ exports.createCheckoutSession = createCheckoutSession;
273
282
  exports.createCustomerPortalSession = createCustomerPortalSession;
274
283
  exports.createOrGetCustomer = createOrGetCustomer;
275
284
  exports.fetchPaymentId = fetchPaymentId;
276
- exports.stripe = stripe;
285
+ exports.getStripe = getStripe;
277
286
  exports.updateSubscription = updateSubscription;
278
287
  exports.validateStripeWebhook = validateStripeWebhook;
@@ -7,13 +7,22 @@ import '@prisma/client';
7
7
  import '../prisma/prisma.mjs';
8
8
  import { Apilogger } from '../services/database/apilog.service.mjs';
9
9
 
10
- // Stripe Configuration
11
- const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
12
- apiVersion: '2025-11-17.clover',
13
- });
10
+ let stripeInstance = null;
11
+ const getStripe = () => {
12
+ const apiKey = process.env.STRIPE_SECRET_KEY;
13
+ if (!apiKey) {
14
+ throw new Error('STRIPE_SECRET_KEY is not configured');
15
+ }
16
+ if (!stripeInstance) {
17
+ stripeInstance = new Stripe(apiKey, {
18
+ apiVersion: '2025-11-17.clover',
19
+ });
20
+ }
21
+ return stripeInstance;
22
+ };
14
23
  // Helper function to validate webhook signature
15
24
  const validateStripeWebhook = (payload, signature, secret) => {
16
- return stripe.webhooks.constructEvent(payload, signature, secret);
25
+ return getStripe().webhooks.constructEvent(payload, signature, secret);
17
26
  };
18
27
  // Helper function to create checkout session
19
28
  const createCheckoutSession = (params, subscriptionData) => __awaiter(void 0, void 0, void 0, function* () {
@@ -62,7 +71,7 @@ const createCheckoutSession = (params, subscriptionData) => __awaiter(void 0, vo
62
71
  // Create log record with request
63
72
  const logId = yield Apilogger.logStripeOutgoing('createCheckoutSession', params);
64
73
  try {
65
- const session = yield stripe.checkout.sessions.create(sessionParams);
74
+ const session = yield getStripe().checkout.sessions.create(sessionParams);
66
75
  // Update log record with response
67
76
  Apilogger.updateResponse(logId, {
68
77
  session_id: session.id,
@@ -82,7 +91,7 @@ const createCheckoutSession = (params, subscriptionData) => __awaiter(void 0, vo
82
91
  // 根据发票ID去查支付ID
83
92
  const fetchPaymentId = (invoiceId) => __awaiter(void 0, void 0, void 0, function* () {
84
93
  var _a, _b;
85
- const fullInvoice = yield stripe.invoices.retrieve(invoiceId, {
94
+ const fullInvoice = yield getStripe().invoices.retrieve(invoiceId, {
86
95
  expand: ['payments']
87
96
  });
88
97
  const payment = (_a = fullInvoice.payments) === null || _a === void 0 ? void 0 : _a.data[0];
@@ -107,7 +116,7 @@ const createOrGetCustomer = (params) => __awaiter(void 0, void 0, void 0, functi
107
116
  });
108
117
  if (user.stripeCusId) {
109
118
  try {
110
- const customer = yield stripe.customers.retrieve(user.stripeCusId);
119
+ const customer = yield getStripe().customers.retrieve(user.stripeCusId);
111
120
  if ('deleted' in customer) {
112
121
  yield setStripeCustomerId(null);
113
122
  }
@@ -125,7 +134,7 @@ const createOrGetCustomer = (params) => __awaiter(void 0, void 0, void 0, functi
125
134
  }
126
135
  }
127
136
  if (user.email) {
128
- const existingCustomers = yield stripe.customers.list({
137
+ const existingCustomers = yield getStripe().customers.list({
129
138
  email: user.email,
130
139
  limit: 1,
131
140
  });
@@ -157,7 +166,7 @@ const createOrGetCustomer = (params) => __awaiter(void 0, void 0, void 0, functi
157
166
  name: customerParams.name,
158
167
  });
159
168
  try {
160
- const customer = yield stripe.customers.create(customerParams);
169
+ const customer = yield getStripe().customers.create(customerParams);
161
170
  yield setStripeCustomerId(customer.id);
162
171
  // Update log record with response
163
172
  Apilogger.updateResponse(logId, {
@@ -177,11 +186,11 @@ const createOrGetCustomer = (params) => __awaiter(void 0, void 0, void 0, functi
177
186
  // Helper function to update subscription
178
187
  const updateSubscription = (params) => __awaiter(void 0, void 0, void 0, function* () {
179
188
  const { subscriptionId, priceId, prorationBehavior = 'create_prorations' } = params;
180
- const subscription = yield stripe.subscriptions.retrieve(subscriptionId);
189
+ const subscription = yield getStripe().subscriptions.retrieve(subscriptionId);
181
190
  // Create log record with request
182
191
  const logId = yield Apilogger.logStripeOutgoing('updateSubscription', params);
183
192
  try {
184
- const updatedSubscription = yield stripe.subscriptions.update(subscriptionId, {
193
+ const updatedSubscription = yield getStripe().subscriptions.update(subscriptionId, {
185
194
  items: [
186
195
  {
187
196
  id: subscription.items.data[0].id,
@@ -208,7 +217,7 @@ const updateSubscription = (params) => __awaiter(void 0, void 0, void 0, functio
208
217
  const createCustomerPortalSession = (params) => __awaiter(void 0, void 0, void 0, function* () {
209
218
  const logId = yield Apilogger.logStripeOutgoing('createCustomerPortalSession', params);
210
219
  try {
211
- const session = yield stripe.billingPortal.sessions.create({
220
+ const session = yield getStripe().billingPortal.sessions.create({
212
221
  customer: params.customerId,
213
222
  return_url: params.returnUrl,
214
223
  });
@@ -235,12 +244,12 @@ const cancelSubscription = (subscriptionId_1, ...args_1) => __awaiter(void 0, [s
235
244
  try {
236
245
  let result;
237
246
  if (cancelAtPeriodEnd) {
238
- result = yield stripe.subscriptions.update(subscriptionId, {
247
+ result = yield getStripe().subscriptions.update(subscriptionId, {
239
248
  cancel_at_period_end: true,
240
249
  });
241
250
  }
242
251
  else {
243
- result = yield stripe.subscriptions.cancel(subscriptionId);
252
+ result = yield getStripe().subscriptions.cancel(subscriptionId);
244
253
  }
245
254
  // Update log record with response
246
255
  Apilogger.updateResponse(logId, {
@@ -265,4 +274,4 @@ class ActiveSubscriptionExistsError extends Error {
265
274
  }
266
275
  }
267
276
 
268
- export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, stripe, updateSubscription, validateStripeWebhook };
277
+ export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, getStripe, updateSubscription, validateStripeWebhook };
@@ -1,4 +1,4 @@
1
1
  import { PrismaClient, Prisma } from '@prisma/client';
2
- export declare const prisma: any;
2
+ export declare const prisma: PrismaClient<Prisma.PrismaClientOptions, never, import("@prisma/client/runtime/library").DefaultArgs>;
3
3
  export declare function checkAndFallbackWithNonTCClient(tx?: Prisma.TransactionClient): Prisma.TransactionClient | PrismaClient;
4
4
  //# sourceMappingURL=prisma.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prisma.d.ts","sourceRoot":"","sources":["../../src/prisma/prisma.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAgCtD,eAAO,MAAM,MAAM,KAIf,CAAC;AAmFL,wBAAgB,+BAA+B,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,iBAAiB,GAAG,MAAM,CAAC,iBAAiB,GAAG,YAAY,CAEtH"}
1
+ {"version":3,"file":"prisma.d.ts","sourceRoot":"","sources":["../../src/prisma/prisma.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAgCtD,eAAO,MAAM,MAAM,uGAIf,CAAC;AAmFL,wBAAgB,+BAA+B,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,iBAAiB,GAAG,MAAM,CAAC,iBAAiB,GAAG,YAAY,CAEtH"}
@@ -122,9 +122,10 @@ function handleSubscriptionCheckoutInit(session, transaction) {
122
122
  throw new Error('No subscription ID in checkout session');
123
123
  }
124
124
  const subscriptionId = session.subscription;
125
+ const stripe = stripeConfig.getStripe();
125
126
  // ===== STEP 1: FETCH EXTERNAL API DATA (BEFORE TRANSACTION) =====
126
127
  // 2. Get COMPLETE Stripe subscription details including billing period
127
- const stripeSubscription = yield stripeConfig.stripe.subscriptions.retrieve(subscriptionId);
128
+ const stripeSubscription = yield stripe.subscriptions.retrieve(subscriptionId);
128
129
  // Extract billing period from subscription items (NOT from top-level subscription object)
129
130
  // The current_period_start/end are on SubscriptionItem, not on Subscription
130
131
  const subscriptionItem = (_b = (_a = stripeSubscription.items) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[0];
@@ -343,8 +344,9 @@ function handleSubscriptionDeleted(stripeSubscription) {
343
344
  function handleAsyncPaymentSucceeded(session) {
344
345
  return tslib_es6.__awaiter(this, void 0, void 0, function* () {
345
346
  console.log(`Async payment succeeded: ${session.id}`);
347
+ const stripe = stripeConfig.getStripe();
346
348
  // Retrieve the latest session state to ensure payment_status is up to date
347
- const latestSession = yield stripeConfig.stripe.checkout.sessions.retrieve(session.id);
349
+ const latestSession = yield stripe.checkout.sessions.retrieve(session.id);
348
350
  return yield handleCheckoutCompleted(latestSession);
349
351
  });
350
352
  }
@@ -9,7 +9,7 @@ import '@prisma/client';
9
9
  import { Apilogger } from '../database/apilog.service.mjs';
10
10
  import { oneTimeExpiredDays } from '../../lib/credit-init.mjs';
11
11
  import { getCreditsFromPriceId } from '../../lib/money-price-config.mjs';
12
- import { stripe, fetchPaymentId } from '../../lib/stripe-config.mjs';
12
+ import { getStripe, fetchPaymentId } from '../../lib/stripe-config.mjs';
13
13
  import { viewLocalTime } from '@windrun-huaiin/lib/utils';
14
14
 
15
15
  /* eslint-disable @typescript-eslint/no-explicit-any */
@@ -120,6 +120,7 @@ function handleSubscriptionCheckoutInit(session, transaction) {
120
120
  throw new Error('No subscription ID in checkout session');
121
121
  }
122
122
  const subscriptionId = session.subscription;
123
+ const stripe = getStripe();
123
124
  // ===== STEP 1: FETCH EXTERNAL API DATA (BEFORE TRANSACTION) =====
124
125
  // 2. Get COMPLETE Stripe subscription details including billing period
125
126
  const stripeSubscription = yield stripe.subscriptions.retrieve(subscriptionId);
@@ -341,6 +342,7 @@ function handleSubscriptionDeleted(stripeSubscription) {
341
342
  function handleAsyncPaymentSucceeded(session) {
342
343
  return __awaiter(this, void 0, void 0, function* () {
343
344
  console.log(`Async payment succeeded: ${session.id}`);
345
+ const stripe = getStripe();
344
346
  // Retrieve the latest session state to ensure payment_status is up to date
345
347
  const latestSession = yield stripe.checkout.sessions.retrieve(session.id);
346
348
  return yield handleCheckoutCompleted(latestSession);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windrun-huaiin/backend-core",
3
- "version": "14.0.0",
3
+ "version": "14.1.0",
4
4
  "description": "Shared backend primitives: Prisma schema/client, database services, routing helpers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,10 +1,22 @@
1
1
  import Stripe from 'stripe';
2
2
  import { Apilogger, userService, subscriptionService } from '../services/database/index';
3
3
 
4
- // Stripe Configuration
5
- export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
6
- apiVersion: '2025-11-17.clover',
7
- });
4
+ let stripeInstance: Stripe | null = null;
5
+
6
+ export const getStripe = (): Stripe => {
7
+ const apiKey = process.env.STRIPE_SECRET_KEY;
8
+ if (!apiKey) {
9
+ throw new Error('STRIPE_SECRET_KEY is not configured');
10
+ }
11
+
12
+ if (!stripeInstance) {
13
+ stripeInstance = new Stripe(apiKey, {
14
+ apiVersion: '2025-11-17.clover',
15
+ });
16
+ }
17
+
18
+ return stripeInstance;
19
+ };
8
20
 
9
21
  // Helper function to validate webhook signature
10
22
  export const validateStripeWebhook = (
@@ -12,7 +24,7 @@ export const validateStripeWebhook = (
12
24
  signature: string,
13
25
  secret: string
14
26
  ): Stripe.Event => {
15
- return stripe.webhooks.constructEvent(payload, signature, secret);
27
+ return getStripe().webhooks.constructEvent(payload, signature, secret);
16
28
  };
17
29
 
18
30
  export interface BasicCheckoutSessionParams {
@@ -95,7 +107,7 @@ export const createCheckoutSession = async (
95
107
  const logId = await Apilogger.logStripeOutgoing('createCheckoutSession', params);
96
108
 
97
109
  try {
98
- const session = await stripe.checkout.sessions.create(sessionParams);
110
+ const session = await getStripe().checkout.sessions.create(sessionParams);
99
111
 
100
112
  // Update log record with response
101
113
  Apilogger.updateResponse(logId, {
@@ -116,7 +128,7 @@ export const createCheckoutSession = async (
116
128
 
117
129
  // 根据发票ID去查支付ID
118
130
  export const fetchPaymentId = async (invoiceId: string ): Promise<string> => {
119
- const fullInvoice = await stripe.invoices.retrieve(invoiceId, {
131
+ const fullInvoice = await getStripe().invoices.retrieve(invoiceId, {
120
132
  expand: ['payments']
121
133
  });
122
134
  const payment = fullInvoice.payments?.data[0];
@@ -147,7 +159,7 @@ export const createOrGetCustomer = async (params: {
147
159
 
148
160
  if (user.stripeCusId) {
149
161
  try {
150
- const customer = await stripe.customers.retrieve(user.stripeCusId);
162
+ const customer = await getStripe().customers.retrieve(user.stripeCusId);
151
163
  if ('deleted' in customer) {
152
164
  await setStripeCustomerId(null);
153
165
  } else {
@@ -164,7 +176,7 @@ export const createOrGetCustomer = async (params: {
164
176
  }
165
177
 
166
178
  if (user.email) {
167
- const existingCustomers = await stripe.customers.list({
179
+ const existingCustomers = await getStripe().customers.list({
168
180
  email: user.email,
169
181
  limit: 1,
170
182
  });
@@ -201,7 +213,7 @@ export const createOrGetCustomer = async (params: {
201
213
  });
202
214
 
203
215
  try {
204
- const customer = await stripe.customers.create(customerParams);
216
+ const customer = await getStripe().customers.create(customerParams);
205
217
  await setStripeCustomerId(customer.id);
206
218
 
207
219
  // Update log record with response
@@ -228,13 +240,13 @@ export const updateSubscription = async (params: {
228
240
  }): Promise<Stripe.Subscription> => {
229
241
  const { subscriptionId, priceId, prorationBehavior = 'create_prorations' } = params;
230
242
 
231
- const subscription = await stripe.subscriptions.retrieve(subscriptionId);
243
+ const subscription = await getStripe().subscriptions.retrieve(subscriptionId);
232
244
 
233
245
  // Create log record with request
234
246
  const logId = await Apilogger.logStripeOutgoing('updateSubscription', params);
235
247
 
236
248
  try {
237
- const updatedSubscription = await stripe.subscriptions.update(subscriptionId, {
249
+ const updatedSubscription = await getStripe().subscriptions.update(subscriptionId, {
238
250
  items: [
239
251
  {
240
252
  id: subscription.items.data[0].id,
@@ -267,7 +279,7 @@ export const createCustomerPortalSession = async (params: {
267
279
  const logId = await Apilogger.logStripeOutgoing('createCustomerPortalSession', params);
268
280
 
269
281
  try {
270
- const session = await stripe.billingPortal.sessions.create({
282
+ const session = await getStripe().billingPortal.sessions.create({
271
283
  customer: params.customerId,
272
284
  return_url: params.returnUrl,
273
285
  });
@@ -301,11 +313,11 @@ export const cancelSubscription = async (
301
313
  let result: Stripe.Subscription;
302
314
 
303
315
  if (cancelAtPeriodEnd) {
304
- result = await stripe.subscriptions.update(subscriptionId, {
316
+ result = await getStripe().subscriptions.update(subscriptionId, {
305
317
  cancel_at_period_end: true,
306
318
  });
307
319
  } else {
308
- result = await stripe.subscriptions.cancel(subscriptionId);
320
+ result = await getStripe().subscriptions.cancel(subscriptionId);
309
321
  }
310
322
 
311
323
  // Update log record with response
@@ -13,7 +13,7 @@ import {
13
13
  import { Transaction } from '@/db/prisma-model-type';
14
14
  import { oneTimeExpiredDays } from '@/lib/credit-init';
15
15
  import { getCreditsFromPriceId } from '@/lib/money-price-config';
16
- import { fetchPaymentId, stripe } from '@/lib/stripe-config';
16
+ import { fetchPaymentId, getStripe } from '@/lib/stripe-config';
17
17
  import Stripe from 'stripe';
18
18
  import { viewLocalTime } from '@windrun-huaiin/lib/utils';
19
19
 
@@ -150,6 +150,7 @@ async function handleSubscriptionCheckoutInit(
150
150
  }
151
151
 
152
152
  const subscriptionId = session.subscription as string;
153
+ const stripe = getStripe();
153
154
 
154
155
  // ===== STEP 1: FETCH EXTERNAL API DATA (BEFORE TRANSACTION) =====
155
156
  // 2. Get COMPLETE Stripe subscription details including billing period
@@ -416,6 +417,7 @@ async function handleSubscriptionDeleted(stripeSubscription: Stripe.Subscription
416
417
 
417
418
  async function handleAsyncPaymentSucceeded(session: Stripe.Checkout.Session) {
418
419
  console.log(`Async payment succeeded: ${session.id}`);
420
+ const stripe = getStripe();
419
421
 
420
422
  // Retrieve the latest session state to ensure payment_status is up to date
421
423
  const latestSession = await stripe.checkout.sessions.retrieve(session.id);