-
Notifications
You must be signed in to change notification settings - Fork 0
/
StripeService.ts
73 lines (63 loc) · 1.94 KB
/
StripeService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import {
GenezioDeploy,
GenezioHttpRequest,
GenezioHttpResponse,
GenezioMethod,
} from "@genezio/types";
import Stripe from "stripe";
import pg from "pg";
const { Pool } = pg;
// Use the Stripe API Key clientSecret to initialize the Stripe Object
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
@GenezioDeploy()
export class StripeService {
pool = new Pool({
connectionString: process.env["SOLVEIT_DATABASE_URL"],
ssl: true,
});
async createCheckoutSession(userId: string): Promise<string> {
const stripePromise = await stripe.checkout.sessions.create({
line_items: [
{
price_data: {
currency: "RON",
product_data: {
name: "Tokens",
},
unit_amount: 1000, // 20.00 USD
},
quantity: 1,
},
],
mode: "payment",
success_url: `${process.env.FRONTEND_URL}?success=true`,
cancel_url: `${process.env.FRONTEND_URL}?canceled=true`,
});
await this.pool.query(
"update credits set credits = credits + 10 where userId = $1",
[userId]
);
return stripePromise.url || "";
}
@GenezioMethod({ type: "http" })
async webhook(req: GenezioHttpRequest): Promise<GenezioHttpResponse> {
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
req.rawBody,
req.headers["stripe-signature"],
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
return { statusCode: "400", body: "Webhook Error" };
}
// Handle the checkout.session.completed event
if (event.type === "checkout.session.completed") {
const session = event.data.object;
console.log("Fulfilling order", session);
console.log("Order fulfilled successfully"); // Log when the order is fulfilled successfully
return { statusCode: "200", body: "Order fulfilled" };
}
return { statusCode: "200", body: "Success" };
}
}