/
Stripe.swift
369 lines (307 loc) 路 10.9 KB
/
Stripe.swift
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import Either
import Foundation
import HttpPipeline
import Prelude
import Optics
import UrlFormEncoding
public struct Stripe {
public var cancelSubscription: (Subscription.Id) -> EitherIO<Prelude.Unit, Subscription>
public var createCustomer: (Database.User, Token.Id) -> EitherIO<Prelude.Unit, Customer>
public var createSubscription: (Customer.Id, Plan.Id, Int, Coupon.Id?) -> EitherIO<Prelude.Unit, Subscription>
public var fetchCustomer: (Customer.Id) -> EitherIO<Prelude.Unit, Customer>
public var fetchPlans: EitherIO<Prelude.Unit, ListEnvelope<Plan>>
public var fetchPlan: (Plan.Id) -> EitherIO<Prelude.Unit, Plan>
public var fetchSubscription: (Subscription.Id) -> EitherIO<Prelude.Unit, Subscription>
public var invoiceCustomer: (Customer) -> EitherIO<Prelude.Unit, Invoice>
public var updateCustomer: (Customer, Token.Id) -> EitherIO<Prelude.Unit, Customer>
public var updateSubscription: (Subscription, Plan.Id, Int, Coupon.Id?) -> EitherIO<Prelude.Unit, Subscription>
public var js: String
public static let live = Stripe(
cancelSubscription: PointFree.cancelSubscription,
createCustomer: PointFree.createCustomer,
createSubscription: PointFree.createSubscription,
fetchCustomer: PointFree.fetchCustomer,
fetchPlans: PointFree.fetchPlans,
fetchPlan: PointFree.fetchPlan,
fetchSubscription: PointFree.fetchSubscription,
invoiceCustomer: PointFree.invoiceCustomer,
updateCustomer: PointFree.updateCustomer,
updateSubscription: PointFree.updateSubscription,
js: "https://js.stripe.com/v3/"
)
public struct Card: Codable {
public private(set) var brand: Brand
public private(set) var customer: Customer.Id
public private(set) var expMonth: Int
public private(set) var expYear: Int
public private(set) var id: Id
public private(set) var last4: String
public typealias Id = Tagged<Card, String>
public enum Brand: String, Codable {
case visa = "Visa"
case americanExpress = "American Express"
case masterCard = "MasterCard"
case discover = "Discover"
case jcb = "JCB"
case dinersClub = "Diners Club"
case unknown = "Unknown"
}
public enum Funding: String, Codable {
case credit
case debit
case prepaid
case unknown
}
private enum CodingKeys: String, CodingKey {
case brand
case customer
case expMonth = "exp_month"
case expYear = "exp_year"
case id
case last4
}
}
public typealias Cents = Tagged<Stripe, Int>
public struct Coupon: Codable {
public private(set) var id: Id
public private(set) var percentOff: Int?
public typealias Id = Tagged<Coupon, String>
private enum CodingKeys: String, CodingKey {
case id
case percentOff = "percent_off"
}
}
public struct Customer: Codable {
public private(set) var defaultSource: Card.Id
public private(set) var id: Id
public private(set) var sources: ListEnvelope<Card>
public typealias Id = Tagged<Customer, String>
private enum CodingKeys: String, CodingKey {
case defaultSource = "default_source"
case id
case sources
}
}
public struct Discount: Codable {
public private(set) var coupon: Coupon
}
public struct Invoice: Codable {
public private(set) var id: Id
public typealias Id = Tagged<Invoice, String>
}
public struct ListEnvelope<A: Codable>: Codable {
private(set) var data: [A]
private(set) var hasMore: Bool
private(set) var totalCount: Int
private enum CodingKeys: String, CodingKey {
case data
case hasMore = "has_more"
case totalCount = "total_count"
}
}
public struct Plan: Codable {
public private(set) var amount: Cents
public private(set) var created: Date
public private(set) var currency: Currency
public private(set) var id: Id
public private(set) var interval: Interval
public private(set) var metadata: [String: String]
public private(set) var name: String
public private(set) var statementDescriptor: String?
private enum CodingKeys: String, CodingKey {
case amount
case created
case currency
case id
case interval
case metadata
case name
case statementDescriptor = "statement_descriptor"
}
public typealias Id = Tagged<Plan, String>
public enum Currency: String, Codable {
case usd
}
public enum Interval: String, Codable {
case month
case year
}
}
public struct Subscription: Codable {
public private(set) var canceledAt: Date?
public private(set) var cancelAtPeriodEnd: Bool
public private(set) var created: Date
public private(set) var currentPeriodStart: Date? // TODO: Audit nullability
public private(set) var currentPeriodEnd: Date? // TODO: Audit nullability
public private(set) var customer: Customer
public private(set) var discount: Discount?
public private(set) var endedAt: Date?
public private(set) var id: Id
public private(set) var items: ListEnvelope<Item>
public private(set) var plan: Plan
public private(set) var quantity: Int
public private(set) var start: Date
public private(set) var status: Status
public var isRenewing: Bool {
return self.status != .canceled && !self.cancelAtPeriodEnd
}
private enum CodingKeys: String, CodingKey {
case canceledAt = "canceled_at"
case cancelAtPeriodEnd = "cancel_at_period_end"
case customer
case created
case currentPeriodEnd = "current_period_end"
case currentPeriodStart = "current_period_start"
case discount
case endedAt = "ended_at"
case id
case items
case plan
case quantity
case start
case status
}
public typealias Id = Tagged<Subscription, String>
public struct Item: Codable {
public private(set) var created: Date
public private(set) var id: Id
public private(set) var plan: Plan
public private(set) var quantity: Int
public typealias Id = Tagged<Item, String>
}
public enum Status: String, Codable {
case active
case canceled
case pastDue = "past_due"
case trialing
case unpaid
}
}
public struct Token: Codable {
public private(set) var id: Id
public typealias Id = Tagged<Token, String>
}
}
extension Tagged where Tag == Stripe.Plan, A == String {
static var individualMonthly: Stripe.Plan.Id {
return .init(unwrap: "individual-monthly")
}
static var individualYearly: Stripe.Plan.Id {
return .init(unwrap: "individual-yearly")
}
static var teamYearly: Stripe.Plan.Id {
return .init(unwrap: "team-yearly")
}
}
//private let subscriptionPlans = fetchPlans
// .map(^\.data >>> filter(StripeSubscriptionPlan.Id.all.contains <<< ^\.id))
private func cancelSubscription(id: Stripe.Subscription.Id) -> EitherIO<Prelude.Unit, Stripe.Subscription> {
return stripeDataTask("subscriptions/" + id.rawValue, .delete(["at_period_end": "true"]))
}
private func createCustomer(user: Database.User, token: Stripe.Token.Id)
-> EitherIO<Prelude.Unit, Stripe.Customer> {
return stripeDataTask("customers", .post([
"description": user.id.unwrap.uuidString,
"email": user.email.unwrap,
"source": token.unwrap,
]))
}
private func createSubscription(
customer: Stripe.Customer.Id,
plan: Stripe.Plan.Id,
quantity: Int,
coupon: Stripe.Coupon.Id?
)
-> EitherIO<Prelude.Unit, Stripe.Subscription> {
return stripeDataTask("subscriptions?expand[]=customer", .post([
"coupon": coupon?.unwrap,
"customer": customer.unwrap,
"items[0][plan]": plan.unwrap,
"items[0][quantity]": String(quantity),
] |> filteredValues))
}
private func fetchCustomer(id: Stripe.Customer.Id) -> EitherIO<Prelude.Unit, Stripe.Customer> {
return stripeDataTask("customers/" + id.unwrap)
}
private let fetchPlans: EitherIO<Prelude.Unit, Stripe.ListEnvelope<Stripe.Plan>> =
stripeDataTask("plans")
private func fetchPlan(id: Stripe.Plan.Id) -> EitherIO<Prelude.Unit, Stripe.Plan> {
return stripeDataTask("plans/" + id.rawValue)
}
private func fetchSubscription(id: Stripe.Subscription.Id) -> EitherIO<Prelude.Unit, Stripe.Subscription> {
return stripeDataTask("subscriptions/" + id.unwrap + "?expand[]=customer")
}
private func invoiceCustomer(_ customer: Stripe.Customer)
-> EitherIO<Prelude.Unit, Stripe.Invoice> {
return stripeDataTask("invoices", .post([
"customer": customer.id.unwrap,
]))
}
private func updateCustomer(_ customer: Stripe.Customer, _ token: Stripe.Token.Id)
-> EitherIO<Prelude.Unit, Stripe.Customer> {
return stripeDataTask("customers/" + customer.id.unwrap, .post([
"source": token.unwrap,
]))
}
private func updateSubscription(
_ subscription: Stripe.Subscription,
_ plan: Stripe.Plan.Id,
_ quantity: Int,
_ coupon: Stripe.Coupon.Id?
)
-> EitherIO<Prelude.Unit, Stripe.Subscription> {
guard let item = subscription.items.data.first else { return throwE(unit) }
return stripeDataTask("subscriptions/" + subscription.id.unwrap + "?expand[]=customer", .post([
"coupon": coupon?.unwrap,
"items[0][id]": item.id.unwrap,
"items[0][plan]": plan.unwrap,
"items[0][quantity]": String(quantity),
] |> filteredValues))
}
private let stripeJsonDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}()
private enum Method {
case get
case post([String: String])
case delete([String: String])
}
private func stripeUrlRequest(_ path: String, _ method: Method = .get) -> URLRequest {
var request = URLRequest(url: URL(string: "https://api.stripe.com/v1/" + path)!)
switch method {
case .get:
request.httpMethod = "GET"
case let .post(params):
request.httpMethod = "POST"
request.httpBody = Data(urlFormEncode(value: params).utf8)
case let .delete(params):
request.httpMethod = "DELETE"
request.httpBody = Data(urlFormEncode(value: params).utf8)
}
return request
}
private func stripeDataTask<A>(_ path: String, _ method: Method = .get)
-> EitherIO<Prelude.Unit, A>
where A: Decodable {
return pure(stripeUrlRequest(path, method))
.flatMap { jsonDataTask(with: auth <| $0, decoder: stripeJsonDecoder) }
.map(tap(AppEnvironment.current.logger.debug))
.withExcept(tap(AppEnvironment.current.logger.error) >>> const(unit))
}
private func auth(_ request: URLRequest) -> URLRequest {
return request |> \.allHTTPHeaderFields %~ attachStripeAuthorization
}
private func attachStripeAuthorization(_ headers: [String: String]?) -> [String: String] {
let secret = Data("\(AppEnvironment.current.envVars.stripe.secretKey):".utf8).base64EncodedString()
return (headers ?? [:])
|> key("Authorization") .~ ("Basic " + secret) // TODO: Use key path subscript
}
// FIXME???
func tap<A>(_ f: @autoclosure @escaping () -> (@autoclosure () -> (A)) -> Void) -> (A) -> A {
return {
f()($0)
return $0
}
}