· 4 years ago · Sep 02, 2021, 07:22 AM
1// ... Sign up API ...
2
3const subscription = await createPendingSubscription({
4 subscription: {
5 handle: Date.now().toString(),
6 plan: process.env.REEPAY_SUBSCRIPTION!,
7 },
8 customer: existingCustomer
9 ? existingCustomer.handle
10 : {
11 first_name: firstName,
12 last_name: lastName,
13 email,
14 handle: customerHandle,
15 },
16 coupon,
17});
18
19const session = await createSubscriptionSession({
20 buttonText: "Start abonnement",
21 subscriptionHandle: subscription.handle,
22 acceptUrl: "",
23 cancelUrl: "",
24 withDiscount: !!coupon,
25});
26
27return res.json({
28 status: "success",
29 subscriptionSessionId: session.id,
30 firstLoginToken,
31});
32
33// ... /Sign up API ...
34
35
36
37export async function createPendingSubscription(args: {
38 subscription: {
39 plan: string;
40 handle: string;
41 };
42 customer:
43 | {
44 handle: string;
45 email: string;
46 first_name: string;
47 last_name: string;
48 }
49 | string;
50 coupon?: string;
51}): Promise<Subscription> {
52 const body: { [key: string]: any } = {
53 plan: args.subscription.plan,
54 handle: args.subscription.handle,
55 coupon_codes: args.coupon ? [args.coupon] : [],
56 };
57 if (typeof args.customer === "string") {
58 body.customer = args.customer;
59 } else {
60 body.create_customer = {
61 handle: args.customer.handle,
62 email: args.customer.email,
63 first_name: args.customer.first_name,
64 last_name: args.customer.last_name,
65 };
66 }
67 return (await wrapReepayRequest(
68 fetch("https://api.reepay.com/v1/subscription/prepare", {
69 body: JSON.stringify(body),
70 headers: {
71 Authorization: `Basic ${base64(process.env.REEPAY_PRIVKEY!)}`,
72 "Content-Type": "application/json",
73 },
74 method: "POST",
75 })
76 )) as Subscription;
77}
78
79export async function createSubscriptionSession(args: {
80 buttonText: string;
81 subscriptionHandle: string;
82 acceptUrl: string;
83 cancelUrl: string;
84 withDiscount: boolean;
85}): Promise<{ id: string; url: string }> {
86 return (await wrapReepayRequest(
87 fetch("https://checkout-api.reepay.com/v1/session/subscription", {
88 body: JSON.stringify({
89 button_text: args.buttonText,
90 subscription: args.subscriptionHandle,
91 accept_url: args.acceptUrl,
92 cancel_url: args.cancelUrl,
93 session_data: {
94 // TODO: Actually look up the coupon
95 mps_amount: !args.withDiscount
96 ? undefined
97 : (SUBSCRIPTION_COST_DKK - DISCOUNT_DKK) * 100,
98 mps_description: !args.withDiscount
99 ? undefined
100 : `SoundWheel til ${
101 SUBSCRIPTION_COST_DKK - DISCOUNT_DKK
102 } kr/måned i et år. Herefter ${SUBSCRIPTION_COST_DKK} kr/måned.`.substring(
103 0,
104 60
105 ),
106 mps_plan: !args.withDiscount
107 ? undefined
108 : `SoundWheel Betatester Rabat`.substring(0, 30),
109 },
110 }),
111 headers: {
112 Authorization: `Basic ${base64(process.env.REEPAY_PRIVKEY!)}`,
113 "Content-Type": "application/json",
114 },
115 method: "POST",
116 })
117 )) as SubscriptionSession;
118}