| 1 | import Stripe from "stripe"; |
| 2 | import type { WebhookContext, |
| 3 | |
| 4 | export interface StripeTopupOptions |
| 5 | userId: string; |
| 6 | amountCents: number; |
| 7 | currency: string; |
| 8 | successUrl: string; |
| 9 | cancelUrl: string; |
| 10 | gatewayId: string; |
| 11 | } |
| 12 | |
| 13 | export async function createStripeTopupSession |
| 14 | config: { |
| 15 | opts: StripeTopupOptions |
| 16 | ): Promise<{ |
| 17 | const stripe = |
| 18 | const session = |
| 19 | mode: "payment", |
| 20 | line_items: [ |
| 21 | { |
| 22 | price_data: { |
| 23 | currency: opts.currency |
| 24 | product_data: { name: " |
| 25 | unit_amount: opts.amountCents |
| 26 | }, |
| 27 | quantity: 1, |
| 28 | }, |
| 29 | ], |
| 30 | success_url: opts.successUrl |
| 31 | cancel_url: opts.cancelUrl |
| 32 | metadata: { |
| 33 | userId: opts.userId |
| 34 | gatewayId: opts.gatewayId |
| 35 | type: "wallet_topup", |
| 36 | }, |
| 37 | }); |
| 38 | if (!session.url |
| 39 | return { sessionId: |
| 40 | } |
| 41 | |
| 42 | export async function handleStripeWebhook |
| 43 | const sig = |
| 44 | if (!ctx.config |
| 45 | |
| 46 | let event: |
| 47 | try { |
| 48 | event = Stripe. |
| 49 | } catch { |
| 50 | return null; |
| 51 | } |
| 52 | |
| 53 | if (event.type |
| 54 | const session = |
| 55 | if ( |
| 56 | session.metadata?.type |
| 57 | session.payment_status === |
| 58 | session.metadata.userId |
| 59 | session.metadata.gatewayId |
| 60 | ) { |
| 61 | if (!session.amount_total |
| 62 | return { |
| 63 | type: "topup.succeeded", |
| 64 | userId: session.metadata |
| 65 | amountCents: session.amount_total |
| 66 | currency: (session.currency |
| 67 | providerTransactionId: typeof session. |
| 68 | gatewayId: session.metadata |
| 69 | }; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | return null; |
| 74 | } |