(params: {
userId: string
amountToTopUp: number
stripeCustomerId: string
paymentMethod: Stripe.PaymentMethod
logger: Logger
})
| 140 | } |
| 141 | |
| 142 | async function processAutoTopupPayment(params: { |
| 143 | userId: string |
| 144 | amountToTopUp: number |
| 145 | stripeCustomerId: string |
| 146 | paymentMethod: Stripe.PaymentMethod |
| 147 | logger: Logger |
| 148 | }): Promise<void> { |
| 149 | const { userId, amountToTopUp, stripeCustomerId, paymentMethod, logger } = |
| 150 | params |
| 151 | const logContext = { userId, amountToTopUp } |
| 152 | |
| 153 | // Generate a deterministic operation ID based on userId and current time to minute precision |
| 154 | const timestamp = generateOperationIdTimestamp(new Date()) |
| 155 | const idempotencyKey = `auto-topup-${userId}-${timestamp}` |
| 156 | const operationId = idempotencyKey // Use same ID for both Stripe and our DB |
| 157 | |
| 158 | const centsPerCredit = 1 |
| 159 | const amountInCents = convertCreditsToUsdCents(amountToTopUp, centsPerCredit) |
| 160 | |
| 161 | if (amountInCents <= 0) { |
| 162 | throw new AutoTopupPaymentError('Invalid payment amount calculated') |
| 163 | } |
| 164 | |
| 165 | const paymentIntent = await stripeServer.paymentIntents.create( |
| 166 | { |
| 167 | amount: amountInCents, |
| 168 | currency: 'usd', |
| 169 | customer: stripeCustomerId, |
| 170 | payment_method: paymentMethod.id, |
| 171 | off_session: true, |
| 172 | confirm: true, |
| 173 | description: `Auto top-up: ${amountToTopUp.toLocaleString()} credits`, |
| 174 | metadata: { |
| 175 | userId, |
| 176 | credits: amountToTopUp.toString(), |
| 177 | operationId, |
| 178 | grantType: 'purchase', |
| 179 | type: 'auto-topup', |
| 180 | }, |
| 181 | }, |
| 182 | { |
| 183 | idempotencyKey, // Add Stripe idempotency key |
| 184 | }, |
| 185 | ) |
| 186 | |
| 187 | if (paymentIntent.status !== 'succeeded') { |
| 188 | throw new AutoTopupPaymentError('Payment failed or requires action') |
| 189 | } |
| 190 | |
| 191 | await processAndGrantCredit({ |
| 192 | ...params, |
| 193 | amount: amountToTopUp, |
| 194 | type: 'purchase', |
| 195 | description: `Auto top-up of ${amountToTopUp.toLocaleString()} credits`, |
| 196 | expiresAt: null, |
| 197 | operationId, |
| 198 | }) |
| 199 |
no test coverage detected