-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathCartController.php
More file actions
590 lines (486 loc) · 19.9 KB
/
CartController.php
File metadata and controls
590 lines (486 loc) · 19.9 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php
namespace App\Http\Controllers;
use App\Models\Cart;
use App\Models\Plugin;
use App\Models\PluginBundle;
use App\Models\PluginLicense;
use App\Models\Product;
use App\Services\CartService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Laravel\Cashier\Cashier;
use Stripe\Checkout\Session;
use Stripe\Exception\InvalidRequestException;
class CartController extends Controller
{
public function __construct(
protected CartService $cartService
) {}
public function show(Request $request): View
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
$cart->load('items.plugin.activePrice', 'items.plugin.user', 'items.pluginBundle.plugins', 'items.product.activePrice');
// Refresh prices and notify of changes
$priceChanges = $this->cartService->refreshPrices($cart);
$cart = $cart->fresh(['items.plugin.activePrice', 'items.plugin.user', 'items.pluginBundle.plugins', 'items.product.activePrice']);
// Get bundle IDs already in the cart
$cartBundleIds = $cart->items()
->whereNotNull('plugin_bundle_id')
->pluck('plugin_bundle_id')
->toArray();
// Check for available bundle upgrades based on cart items
$bundleUpgrades = $cart->getAvailableBundleUpgrades();
// If cart is empty or no matching bundles, show random bundles (excluding ones in cart)
$showingRandomBundles = false;
if ($cart->isEmpty() || $bundleUpgrades->isEmpty()) {
$bundleUpgrades = PluginBundle::query()
->active()
->whereNotIn('id', $cartBundleIds)
->with('plugins')
->inRandomOrder()
->limit(4)
->get();
$showingRandomBundles = true;
}
return view('cart.show', [
'cart' => $cart,
'priceChanges' => $priceChanges,
'bundleUpgrades' => $bundleUpgrades,
'showingRandomBundles' => $showingRandomBundles,
]);
}
public function add(Request $request, string $vendor, string $package): RedirectResponse|JsonResponse
{
$plugin = Plugin::findByVendorPackageOrFail($vendor, $package);
$user = Auth::user();
$cart = $this->cartService->getCart($user);
try {
$this->cartService->addPlugin($cart, $plugin);
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'message' => 'Plugin added to cart',
'cart_count' => $cart->itemCount(),
]);
}
// Store the added plugin ID to highlight it in the cart
session()->flash('just_added_plugin_id', $plugin->id);
return to_route('cart.show')
->with('success', '<strong>'.e($plugin->name).'</strong> has been added to your cart!');
} catch (\InvalidArgumentException $e) {
if ($request->wantsJson()) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 400);
}
return back()->with('error', $e->getMessage());
}
}
public function remove(Request $request, string $vendor, string $package): RedirectResponse|JsonResponse
{
$plugin = Plugin::findByVendorPackageOrFail($vendor, $package);
$user = Auth::user();
$cart = $this->cartService->getCart($user);
$this->cartService->removePlugin($cart, $plugin);
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'message' => 'Plugin removed from cart',
'cart_count' => $cart->itemCount(),
]);
}
return to_route('cart.show')->with('success', "{$plugin->name} removed from cart.");
}
public function addBundle(Request $request, PluginBundle $bundle): RedirectResponse|JsonResponse
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
try {
$this->cartService->addBundle($cart, $bundle);
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'message' => 'Bundle added to cart',
'cart_count' => $cart->itemCount(),
]);
}
session()->flash('just_added_bundle_id', $bundle->id);
return to_route('cart.show')
->with('success', '<strong>'.e($bundle->name).'</strong> has been added to your cart!');
} catch (\InvalidArgumentException $e) {
if ($request->wantsJson()) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 400);
}
return back()->with('error', $e->getMessage());
}
}
public function removeBundle(Request $request, PluginBundle $bundle): RedirectResponse|JsonResponse
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
$this->cartService->removeBundle($cart, $bundle);
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'message' => 'Bundle removed from cart',
'cart_count' => $cart->itemCount(),
]);
}
return to_route('cart.show')->with('success', "{$bundle->name} removed from cart.");
}
public function exchangeForBundle(Request $request, PluginBundle $bundle): RedirectResponse
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
try {
$this->cartService->exchangeForBundle($cart, $bundle);
return to_route('cart.show')
->with('success', 'Swapped individual plugins for <strong>'.e($bundle->name).'</strong> bundle and saved '.$bundle->formatted_savings.'!');
} catch (\InvalidArgumentException $e) {
return to_route('cart.show')->with('error', $e->getMessage());
}
}
public function addProduct(Request $request, Product $product): RedirectResponse|JsonResponse
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
try {
$this->cartService->addProduct($cart, $product);
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'message' => 'Product added to cart',
'cart_count' => $cart->itemCount(),
]);
}
session()->flash('just_added_product_id', $product->id);
return to_route('cart.show')
->with('success', '<strong>'.e($product->name).'</strong> has been added to your cart!');
} catch (\InvalidArgumentException $e) {
if ($request->wantsJson()) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 400);
}
return back()->with('error', $e->getMessage());
}
}
public function removeProduct(Request $request, Product $product): RedirectResponse|JsonResponse
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
$this->cartService->removeProduct($cart, $product);
if ($request->wantsJson()) {
return response()->json([
'success' => true,
'message' => 'Product removed from cart',
'cart_count' => $cart->itemCount(),
]);
}
return to_route('cart.show')->with('success', "{$product->name} removed from cart.");
}
public function clear(Request $request): RedirectResponse
{
$user = Auth::user();
$cart = $this->cartService->getCart($user);
$cart->clear();
return to_route('cart.show')->with('success', 'Cart cleared.');
}
public function checkout(Request $request): RedirectResponse
{
$user = Auth::user();
if (! $user) {
// Store intended URL and redirect to login
session(['url.intended' => route('cart.checkout')]);
return to_route('customer.login')
->with('message', 'Please log in or create an account to complete your purchase.');
}
$cart = $this->cartService->getCart($user);
if ($cart->isEmpty()) {
return to_route('cart.show')
->with('error', 'Your cart is empty.');
}
// Refresh prices
$this->cartService->refreshPrices($cart);
// If total is $0, skip Stripe entirely and create licenses directly
if ($cart->getSubtotal() === 0) {
return $this->processFreeCheckout($cart, $user);
}
try {
$session = $this->createMultiItemCheckoutSession($cart, $user);
$cart->update(['stripe_checkout_session_id' => $session->id]);
return redirect($session->url);
} catch (\Exception $e) {
Log::error('Cart checkout failed', [
'cart_id' => $cart->id,
'user_id' => $user->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return to_route('cart.show')
->with('error', 'Unable to start checkout. Please try again.');
}
}
public function success(Request $request): View|RedirectResponse
{
if ($request->query('free')) {
$user = Auth::user();
$cart = Cart::where('user_id', $user->id)
->whereNotNull('completed_at')
->latest('completed_at')
->with('items.plugin', 'items.pluginBundle.plugins', 'items.product')
->first();
return view('cart.success', [
'sessionId' => null,
'isFreeCheckout' => true,
'cart' => $cart,
]);
}
$sessionId = $request->query('session_id');
// Validate session ID exists and looks like a real Stripe session ID
if (! $sessionId || ! str_starts_with($sessionId, 'cs_')) {
return to_route('cart.show')
->with('error', 'Invalid checkout session. Please try again.');
}
// Cart will be marked as completed by the webhook after licenses are created
return view('cart.success', [
'sessionId' => $sessionId,
'isFreeCheckout' => false,
'cart' => null,
]);
}
protected function processFreeCheckout(Cart $cart, $user): RedirectResponse
{
$cart->load('items.plugin', 'items.pluginBundle.plugins', 'items.product');
foreach ($cart->items as $item) {
if ($item->isBundle()) {
foreach ($item->pluginBundle->plugins as $plugin) {
$this->createFreePluginLicense($user, $plugin);
}
} elseif (! $item->isProduct() && $item->plugin) {
$this->createFreePluginLicense($user, $item->plugin);
}
}
$cart->markAsCompleted();
$user->getPluginLicenseKey();
Log::info('Free checkout completed', [
'cart_id' => $cart->id,
'user_id' => $user->id,
'item_count' => $cart->items->count(),
]);
return to_route('cart.success', ['free' => 1]);
}
protected function createFreePluginLicense($user, Plugin $plugin): void
{
if ($user->pluginLicenses()->forPlugin($plugin)->active()->exists()) {
return;
}
PluginLicense::create([
'user_id' => $user->id,
'plugin_id' => $plugin->id,
'price_paid' => 0,
'currency' => 'USD',
'is_grandfathered' => false,
'purchased_at' => now(),
]);
}
public function status(Request $request, string $sessionId): JsonResponse
{
$user = Auth::user();
// Retrieve the checkout session to get the invoice ID
try {
$session = Cashier::stripe()->checkout->sessions->retrieve($sessionId);
$invoiceId = $session->invoice;
} catch (\Exception $e) {
return response()->json([
'status' => 'error',
'message' => 'Unable to verify purchase status.',
], 400);
}
if (! $invoiceId) {
return response()->json([
'status' => 'pending',
'message' => 'Processing your purchase...',
]);
}
// Check if licenses exist for this invoice
$pluginLicenses = $user->pluginLicenses()
->where('stripe_invoice_id', $invoiceId)
->with('plugin')
->get();
$productLicenses = $user->productLicenses()
->where('stripe_invoice_id', $invoiceId)
->with('product')
->get();
if ($pluginLicenses->isEmpty() && $productLicenses->isEmpty()) {
return response()->json([
'status' => 'pending',
'message' => 'Processing your purchase...',
]);
}
// Check if any products grant GitHub repo access
$productsWithRepoAccess = $productLicenses->filter(fn ($license) => $license->product->github_repo !== null);
$hasGitHubConnected = $user->hasGitHubToken();
return response()->json([
'status' => 'complete',
'message' => 'Purchase complete!',
'licenses' => $pluginLicenses->map(fn ($license) => [
'id' => $license->id,
'plugin_id' => $license->plugin->id,
'plugin_name' => $license->plugin->name,
'plugin_display_name' => $license->plugin->display_name,
'plugin_slug' => $license->plugin->slug,
]),
'products' => $productLicenses->map(fn ($license) => [
'id' => $license->id,
'product_name' => $license->product->name,
'product_slug' => $license->product->slug,
'github_repo' => $license->product->github_repo,
]),
'has_github_connected' => $hasGitHubConnected,
'needs_github_connection' => $productsWithRepoAccess->isNotEmpty() && ! $hasGitHubConnected,
]);
}
public function cancel(): RedirectResponse
{
return to_route('cart.show')
->with('message', 'Checkout cancelled. Your cart items are still saved.');
}
public function count(Request $request): JsonResponse
{
$user = Auth::user();
$count = $this->cartService->getCartItemCount($user);
return response()->json(['count' => $count]);
}
protected function createMultiItemCheckoutSession($cart, $user): Session
{
// Eager load items with plugins, bundles, and products to avoid any stale data issues
$cart->load('items.plugin', 'items.pluginBundle.plugins', 'items.product');
$lineItems = [];
Log::info('Creating multi-item checkout session', [
'cart_id' => $cart->id,
'user_id' => $user->id,
'item_count' => $cart->items->count(),
]);
foreach ($cart->items as $item) {
if ($item->isBundle()) {
$bundle = $item->pluginBundle;
$pluginNames = $bundle->plugins->pluck('name')->take(3)->implode(', ');
if ($bundle->plugins->count() > 3) {
$pluginNames .= ' and '.($bundle->plugins->count() - 3).' more';
}
$lineItems[] = [
'price_data' => [
'currency' => strtolower($item->currency),
'unit_amount' => $item->bundle_price_at_addition,
'product_data' => [
'name' => $bundle->name.' (Bundle)',
'description' => 'Includes: '.$pluginNames,
],
],
'quantity' => 1,
];
} elseif ($item->isProduct()) {
$product = $item->product;
$lineItems[] = [
'price_data' => [
'currency' => strtolower($item->currency),
'unit_amount' => $item->product_price_at_addition,
'product_data' => [
'name' => $product->name,
'description' => $product->description ?? 'NativePHP Product',
],
],
'quantity' => 1,
];
} else {
$plugin = $item->plugin;
$lineItems[] = [
'price_data' => [
'currency' => strtolower($item->currency),
'unit_amount' => $item->price_at_addition,
'product_data' => [
'name' => $plugin->name,
'description' => $plugin->description ?? 'NativePHP Plugin',
],
],
'quantity' => 1,
];
}
}
// Ensure the user has a valid Stripe customer ID
$this->ensureValidStripeCustomer($user);
// Metadata only needs cart_id - we'll look up items from the cart
$metadata = [
'cart_id' => (string) $cart->id,
];
$session = Cashier::stripe()->checkout->sessions->create([
'mode' => 'payment',
'line_items' => $lineItems,
'success_url' => route('cart.success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('cart.cancel'),
'customer' => $user->stripe_id,
'customer_update' => [
'name' => 'auto',
'address' => 'auto',
],
'metadata' => $metadata,
'allow_promotion_codes' => true,
'billing_address_collection' => 'required',
'tax_id_collection' => ['enabled' => true],
'invoice_creation' => [
'enabled' => true,
'invoice_data' => [
'description' => 'NativePHP Plugin Purchase',
'footer' => 'Thank you for your purchase!',
'metadata' => $metadata,
],
],
]);
// Store the Stripe checkout session ID on the cart
$cart->update(['stripe_checkout_session_id' => $session->id]);
Log::info('Checkout session created', [
'cart_id' => $cart->id,
'session_id' => $session->id,
]);
return $session;
}
/**
* Ensure the user has a valid Stripe customer ID.
* Creates a new customer if none exists or if the existing one is invalid.
*/
protected function ensureValidStripeCustomer($user): void
{
if (! $user->stripe_id) {
$user->createAsStripeCustomer();
return;
}
// Verify the customer exists in Stripe
try {
Cashier::stripe()->customers->retrieve($user->stripe_id);
} catch (InvalidRequestException $e) {
// Customer doesn't exist in Stripe, create a new one
if (str_contains($e->getMessage(), 'No such customer')) {
Log::warning('Stripe customer not found, creating new customer', [
'user_id' => $user->id,
'old_stripe_id' => $user->stripe_id,
]);
$user->stripe_id = null;
$user->save();
$user->createAsStripeCustomer();
} else {
throw $e;
}
}
}
}