1+ <?php
2+
3+ namespace App \Http \Controllers ;
4+
5+ use Illuminate \Http \Request ;
6+ use Illuminate \Support \Facades \Http ;
7+ use Stripe \StripeClient ;
8+
9+ class CheckoutController extends Controller
10+ {
11+ private function userId (Request $ request ): int
12+ {
13+ return (int ) $ request ->attributes ->get ('user_id ' );
14+ }
15+
16+ public function create (Request $ request )
17+ {
18+ $ data = $ request ->validate ([
19+ 'order_id ' => ['required ' , 'integer ' , 'min:1 ' ],
20+ ]);
21+
22+ $ orderId = (int ) $ data ['order_id ' ];
23+
24+ // 1) Fetch order from order-service as the user (so ownership is enforced)
25+ $ ordersBase = rtrim ((string ) config ('services.orders.base_url ' ), '/ ' ); // http://web/api/orders
26+ $ orderUrl = $ ordersBase . '/items/ ' . $ orderId ;
27+
28+ $ authHeader = (string ) $ request ->header ('Authorization ' ); // reuse same user token
29+ $ orderResp = Http::acceptJson ()
30+ ->withHeaders (['Authorization ' => $ authHeader ])
31+ ->get ($ orderUrl );
32+
33+ if (!$ orderResp ->successful ()) {
34+ return response ()->json (['message ' => 'Order not found ' ], 404 );
35+ }
36+
37+ $ order = $ orderResp ->json ('data ' );
38+ if (!$ order || !isset ($ order ['id ' ], $ order ['total_price ' ], $ order ['status ' ])) {
39+ return response ()->json (['message ' => 'Invalid order response ' ], 500 );
40+ }
41+
42+ if ((string ) $ order ['status ' ] === 'paid ' ) {
43+ return response ()->json (['message ' => 'Order already paid ' ], 422 );
44+ }
45+
46+ $ amount = (int ) $ order ['total_price ' ]; // cents
47+ if ($ amount <= 0 ) {
48+ return response ()->json (['message ' => 'Invalid order amount ' ], 422 );
49+ }
50+
51+ // 2) Create Stripe Checkout Session
52+ $ stripe = new StripeClient ((string ) config ('services.stripe.secret ' ));
53+
54+ $ frontend = rtrim ((string ) config ('services.frontend.base_url ' ), '/ ' ); // http://app.localhost
55+ $ currency = (string ) config ('services.stripe.currency ' );
56+
57+ $ session = $ stripe ->checkout ->sessions ->create ([
58+ 'mode ' => 'payment ' ,
59+ 'success_url ' => $ frontend . '/checkout/success?order_id= ' . $ orderId . '&session_id={CHECKOUT_SESSION_ID} ' ,
60+ 'cancel_url ' => $ frontend . '/checkout/cancel?order_id= ' . $ orderId ,
61+ 'line_items ' => [[
62+ 'quantity ' => 1 ,
63+ 'price_data ' => [
64+ 'currency ' => $ currency ,
65+ 'unit_amount ' => $ amount ,
66+ 'product_data ' => [
67+ 'name ' => 'Order # ' . $ orderId ,
68+ ],
69+ ],
70+ ]],
71+ 'metadata ' => [
72+ 'order_id ' => (string ) $ orderId ,
73+ 'user_id ' => (string ) $ this ->userId ($ request ),
74+ ],
75+ ]);
76+
77+ return response ()->json ([
78+ 'url ' => $ session ->url ,
79+ 'session_id ' => $ session ->id ,
80+ ]);
81+ }
82+ }
0 commit comments