summaryrefslogtreecommitdiff
path: root/backend/api/src/stripe.zig
blob: 87cef10f04112d72cfd54e33214ff0d74a9930d8 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
const z = @import( "std" );
const db = @import( "db.zig" );
const req = @import( "req.zig" );
const net = @import( "net-util.zig" );
const zap = @import( "zap" );
const jwt = @import( "jwt" );
const mail = @import( "mail.zig" );
const config = @import( "config.zig" );

const u = struct {
  usingnamespace @import( "util.zig" );
  usingnamespace @import( "userdefs.zig" );
  usingnamespace @import( "user.zig" );
};

const ArenaAllocator = z.heap.ArenaAllocator;
const ErrorRes = net.ErrorResponse;
const Status = zap.StatusCode;
const ArrayList = z.ArrayList;
const OkRes = net.OkResponse;
const Request = zap.Request;
const JWT = jwt.JWT;

const alloc = u.alloc;
const memeql = z.mem.eql;

pub const routes = .{
  .@"create-payment-intent" = createPaymentIntent
};

pub const SubLength = enum(u32) {
  week = 1,
  month = 2,
  year = 3,

  pub fn getTime( self: SubLength ) i64 {
    switch( self ) {
      .week => return 7 * 24 * 60 * 60 * 1000,
      .month => return 30 * 24 * 60 * 60 * 1000,
      .year => return 365 * 24 * 60 * 60 * 1000
    }
  }

  pub fn getCostAmount( self: SubLength ) u32 {
    switch( self ) {
      .week => return 270,
      .month => return 1000,
      .year => return 10000
    }
  }
};

const StripeUrlParams = struct {
  amount: u32 = 1000,
  currency: []const u8 = "usd",
  description: []const u8 = "Axonbox premium subscription",
  payment_method: []const u8,
  confirm: []const u8 = "true",
  uuid: []const u8,
  return_url: []const u8
};

const StripeRequestParams = struct {
  paymentMethodId: []const u8,
  subLength: SubLength = .month,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const StripeResponse = struct {
  status: []const u8,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

///freed by caller
fn formatStripeParams( params: StripeUrlParams ) []const u8 {
  const ret = z.fmt.allocPrint( alloc,
    "amount={d}&currency={s}&description={s}&payment_method={s}&confirm={s}&metadata%5Buuid%5D={s}&return_url={s}",
    .{
      params.amount,
      params.currency,
      params.description,
      params.payment_method,
      params.confirm,
      params.uuid,
      params.return_url
    }
  ) catch return "";

  return ret;
}

fn formatReturnUrl( buf: []u8 ) []const u8 {
  return z.fmt.bufPrintZ( buf, "{s}/payment-success.html", .{
    config.server_url
  } ) catch return "";
}

fn getStripeKeyBearer() ![]const u8 {
  const file = try u.readFile( "../data/stripe_key.txt" );
  defer alloc.free( file );

  const buf = try z.fmt.allocPrint( alloc, "Bearer {s}", .{ file } );
  return buf;
}

pub fn handleStripeResponse( user: *u.UserEntry, res: StripeResponse, r: zap.Request, length: SubLength ) void {
  const status = res.status;
  if( memeql( u8, status, "succeeded" ) ) {
    user.subscription_data = u.SubData{
      .plan = "paid",
      .endTime = z.time.milliTimestamp() + length.getTime(),
      .reminded = false
    };

    u.updateEntry( user.* ) catch {
      return net.sendJson( r, .internal_server_error, ErrorRes{ .msg = "failed to update user" } );
    };
    return net.sendJson( r, .ok, OkRes( .{ .msg = "success", .paymentIntent = res } ) );
  }

  net.sendJson( r, .bad_request, ErrorRes{ .msg = "failed" } );
}


///route @/create-payment-intent
pub fn createPaymentIntent( r: zap.Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  var token = u.tokenFromPostReq( r ) catch return;
  defer token.deinit();

  const params = u.jsonParse( StripeRequestParams, r.body.? ) catch {
    return net.sendJson( r, .bad_request, ErrorRes{ .msg = "invalid request format" } );
  }; defer params.deinit();

  var user = u.getEntry( token.claims.uuid ) catch {
    return net.sendJson( r, .unauthorized, ErrorRes{ .msg = "user not found" } );
  }; defer user.db_entry.?.deinit();

  if( !memeql( u8, user.subscription_data.plan, "free" ) ) {
    return net.sendJson( r, .bad_request, ErrorRes{ .msg = "user already subscribed" } );
  }

  const stripe_key = getStripeKeyBearer() catch {
    return net.sendJson( r, .internal_server_error, ErrorRes{ .msg = "internal server error" } );
  }; defer alloc.free( stripe_key );

  const headers = [_]z.http.Header{
    .{ .name = "Authorization", .value = stripe_key }
  };

  var buf: [2048]u8 = undefined;
  const body = formatStripeParams( .{
    .amount = params.v.subLength.getCostAmount(),
    .payment_method = params.v.paymentMethodId,
    .uuid = user.uuid,
    .return_url = formatReturnUrl( &buf )
  } ); defer alloc.free( body );

  var res = req.send( .{
    .url = "https://api.stripe.com/v1/payment_intents",
    .method = .POST,
    .headers = &headers,
    .body = body
  }, alloc );
  defer res.deinit();

  if( !res.ok ) {
    z.debug.print( "failed to create payment intent: {s}\n", .{ res.body.? } );
    return net.sendJson( r, .internal_server_error, ErrorRes{ .msg = "failed to create payment intent" } );
  }

  const stripe_json = u.jsonParse( StripeResponse, res.body.? ) catch {
    return net.sendJson( r, .internal_server_error, ErrorRes{ .msg = "failed to parse provider response" } );
  }; defer stripe_json.deinit();

  handleStripeResponse( &user, stripe_json.v, r, params.v.subLength );
}