This repository was archived by the owner on Oct 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPurchaseFlowScreen.swift
More file actions
321 lines (279 loc) · 10.1 KB
/
PurchaseFlowScreen.swift
File metadata and controls
321 lines (279 loc) · 10.1 KB
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
import SwiftUI
import OpenIAP
@available(iOS 15.0, *)
struct PurchaseFlowScreen: View {
@StateObject private var iapStore = OpenIapStore()
// UI State
@State private var showPurchaseResult = false
@State private var purchaseResultMessage = ""
@State private var showError = false
@State private var errorMessage = ""
// Product IDs configured in App Store Connect
private let productIds: [String] = [
"dev.hyo.martie.10bulbs",
"dev.hyo.martie.30bulbs",
"dev.hyo.martie.premium"
]
var body: some View {
ScrollView(.vertical, showsIndicators: true) {
VStack(spacing: 20) {
HeaderCardView()
ProductsSection()
if showPurchaseResult {
PurchaseResultSection()
}
InstructionsCard()
Spacer(minLength: 20)
}
.padding(.vertical)
}
.background(AppColors.background)
.navigationTitle("Purchase Flow")
.navigationBarTitleDisplayMode(.large)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: loadProducts) {
Image(systemName: "arrow.clockwise")
}
.disabled(iapStore.status.isLoading)
}
}
.onAppear {
setupIapProvider()
}
.onDisappear {
teardownConnection()
}
.alert("Error", isPresented: $showError) {
Button("OK") { }
} message: {
Text(errorMessage)
}
}
@ViewBuilder
private func HeaderCardView() -> some View {
VStack(alignment: .leading, spacing: 16) {
HStack {
Image(systemName: "cart.fill")
.font(.largeTitle)
.foregroundColor(AppColors.primary)
VStack(alignment: .leading, spacing: 4) {
Text("Purchase Flow")
.font(.headline)
Text("Test product purchases")
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
}
Text("Purchase consumable and non-consumable iapStore.products. Events are handled through OpenIapStore callbacks.")
.font(.subheadline)
.foregroundColor(.secondary)
}
.padding()
.background(AppColors.cardBackground)
.cornerRadius(12)
.shadow(radius: 2)
.padding(.horizontal)
}
@ViewBuilder
private func ProductsSection() -> some View {
LazyVStack(spacing: 16) {
ForEach(iapStore.products, id: \.id) { product in
ProductCard(
product: product,
isPurchasing: iapStore.status.isPurchasing(product.id)
) {
purchaseProduct(product)
}
}
}
.padding(.horizontal)
}
// moved ProductCard to Screens/uis/ProductCard.swift
@ViewBuilder
private func PurchaseResultSection() -> some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(AppColors.success)
Text("Purchase Result")
.font(.headline)
Spacer()
Button("Dismiss") {
showPurchaseResult = false
purchaseResultMessage = ""
}
.font(.caption)
.foregroundColor(AppColors.primary)
}
Text(purchaseResultMessage)
.font(.system(.caption, design: .monospaced))
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(8)
}
.padding()
.background(AppColors.cardBackground)
.cornerRadius(12)
.shadow(radius: 2)
.padding(.horizontal)
}
@ViewBuilder
private func InstructionsCard() -> some View {
VStack(alignment: .leading, spacing: 16) {
HStack {
Image(systemName: "info.circle.fill")
.foregroundColor(AppColors.primary)
Text("Instructions")
.font(.headline)
Spacer()
}
VStack(alignment: .leading, spacing: 8) {
InstructionRow(
number: "1",
text: "Products are loaded from App Store Connect"
)
InstructionRow(
number: "2",
text: "Tap Purchase to initiate transaction"
)
InstructionRow(
number: "3",
text: "Events are handled via OpenIapStore callbacks"
)
InstructionRow(
number: "4",
text: "Receipt validation should be done server-side"
)
}
}
.padding()
.background(AppColors.cardBackground)
.cornerRadius(12)
.shadow(radius: 2)
.padding(.horizontal)
}
// using shared InstructionRow in Screens/uis/InstructionRow.swift
// MARK: - OpenIapStore Setup
private func setupIapProvider() {
print("🔷 [PurchaseFlow] Setting up OpenIapStore...")
// Setup callbacks
iapStore.onPurchaseSuccess = { purchase in
Task { @MainActor in
self.handlePurchaseSuccess(purchase)
}
}
iapStore.onPurchaseError = { error in
Task { @MainActor in
self.handlePurchaseError(error)
}
}
Task {
do {
try await iapStore.initConnection()
print("✅ [PurchaseFlow] Connection initialized")
loadProducts()
} catch {
await MainActor.run {
errorMessage = "Failed to initialize connection: \(error.localizedDescription)"
showError = true
}
}
}
}
private func teardownConnection() {
print("🔷 [PurchaseFlow] Tearing down connection...")
Task {
try await iapStore.endConnection()
print("✅ [PurchaseFlow] Connection ended")
}
}
// MARK: - Product Loading
private func loadProducts() {
Task {
do {
try await iapStore.fetchProducts(skus: productIds, type: .inapp)
await MainActor.run {
if iapStore.products.isEmpty {
errorMessage = "No products found. Please check your App Store Connect configuration."
showError = true
}
}
} catch {
await MainActor.run {
errorMessage = "Failed to load products: \(error.localizedDescription)"
showError = true
}
}
}
}
// MARK: - Purchase Flow
private func purchaseProduct(_ product: OpenIapProduct) {
print("🛒 [PurchaseFlow] Starting purchase for: \(product.id)")
Task {
do {
let params = RequestPurchaseProps(
sku: product.id,
andDangerouslyFinishTransactionAutomatically: false,
appAccountToken: nil,
quantity: 1
)
_ = try await iapStore.requestPurchase(params)
} catch {
// Error is already handled by OpenIapStore internally
print("❌ [PurchaseFlow] Purchase failed: \(error.localizedDescription)")
}
}
}
// MARK: - Event Handlers
private func handlePurchaseSuccess(_ purchase: OpenIapPurchase) {
print("✅ [PurchaseFlow] Purchase successful: \(purchase.productId)")
// Update UI state
let transactionDate = Date(timeIntervalSince1970: purchase.transactionDate / 1000)
purchaseResultMessage = """
✅ Purchase successful
Product: \(purchase.productId)
Transaction ID: \(purchase.id)
Date: \(DateFormatter.localizedString(from: transactionDate, dateStyle: .short, timeStyle: .short))
"""
showPurchaseResult = true
// In production, validate receipt on your server before finishing
Task {
await finishPurchase(purchase)
}
}
private func handlePurchaseError(_ error: OpenIapError) {
print("❌ [PurchaseFlow] Purchase error: \(error.message)")
// Update UI state
purchaseResultMessage = "❌ Purchase failed: \(error.message)"
showPurchaseResult = true
// Show error alert for non-cancellation errors
if error.code != OpenIapError.E_USER_CANCELLED {
errorMessage = error.message
showError = true
}
}
private func finishPurchase(_ purchase: OpenIapPurchase) async {
do {
_ = try await iapStore.finishTransaction(purchase: purchase)
print("✅ [PurchaseFlow] Transaction finished: \(purchase.id)")
} catch {
print("❌ [PurchaseFlow] Failed to finish transaction: \(error)")
await MainActor.run {
errorMessage = "Failed to finish transaction: \(error.localizedDescription)"
showError = true
}
}
}
}
#Preview {
NavigationView {
if #available(iOS 15.0, *) {
PurchaseFlowScreen()
} else {
Text("iOS 15.0+ Required")
}
}
}