Skip to content

Commit

Permalink
api: stripe invoice.paid events update admin subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredh159 committed Oct 28, 2023
1 parent 0448100 commit 4b6e3b0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
4 changes: 4 additions & 0 deletions api/Sources/Api/Environment/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ extension UUID {
static let mock = UUID(uuidString: "deadbeef-dead-beef-dead-beefdeadbeef")!
}

func unexpected(_ id: String, detail: String = "") {
unexpected(id, nil, detail)
}

func unexpected(_ id: String, _ adminId: Admin.Id? = nil, _ detail: String = "") {
Current.logger.error("Unexpected event `\(id)`, \(detail)")
Current.sendGrid.fireAndForget(.unexpected(id, detail))
Expand Down
32 changes: 26 additions & 6 deletions api/Sources/Api/Routes/StripeEvents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,33 @@ enum StripeEventsRoute {
return Response(status: .badRequest)
}

try await Current.db.create(StripeEvent(json: json))
let stripeEvent = try await Current.db.create(StripeEvent(json: json))
let event = try? JSON.decode(json, as: EventInfo.self)
if event?.type == "invoice.paid",
let email = event?.data?.object?.customer_email {

let admin = try? await Admin.query()
.where(.email == email.lowercased())
.first()

if let admin {
admin.subscriptionStatus = .paid
admin.subscriptionStatusExpiration = event?.data?.object?.period_end
.map { Date(timeIntervalSince1970: TimeInterval($0)).advanced(by: .days(2)) }
?? Current.date().advanced(by: .days(33))
if admin.subscriptionId == nil {
unexpected("d63aab05", admin.id, "event: \(stripeEvent.id)")
}
} else {
unexpected("b3aaf12c", detail: "email: \(email), event: \(stripeEvent.id)")
}
}

Task {
let eventInfo = try? JSON.decode(json, as: EventInfo.self)
await Current.slack.sysLog("""
*Received Gertrude Stripe Event:*
- type: `\(eventInfo?.type ?? "(nil)")`
- customer email: `\(eventInfo?.data?.object?.customer_email ?? "(nil)")`
- type: `\(event?.type ?? "(nil)")`
- customer email: `\(event?.data?.object?.customer_email ?? "(nil)")`
""")
}

Expand All @@ -26,11 +45,12 @@ enum StripeEventsRoute {

private struct EventInfo: Decodable {
struct Data: Decodable {
struct Object: Decodable {
struct InvoiceObject: Decodable {
var customer_email: String?
var period_end: Int?
}

var object: Object?
var object: InvoiceObject?
}

var type: String?
Expand Down

0 comments on commit 4b6e3b0

Please sign in to comment.