Norgul
Norgul

Reputation: 4783

Laravel auth user on webhook

I am having trouble with authenticated user in my Laravel/Vue app. Once you log in, you can choose to make a purchase via Stripe which leads you off the page, and returns back upon payment.

Just to make sure, I've made an endpoint:

Route::get('test', function(){
    return Auth::user();
});

And before and after Stripe, when I hit it, I do get back the user. So authentication is in order.

What happens though is that Stripe upon payment event makes a webhook callback to my route:

Route::post('api/stripe/checkout-session-completed', 'StripeController@checkoutSessionCompleted');

Inside a hook, event is fired which should propagate number of credits purchased to the user who made the purchase, however I am always getting that Auth::user() is not defined.

use Illuminate\Support\Facades\Auth;
...

public function checkoutSessionCompleted()
{
    ...
    $this->handleCheckout($session); // this is Stripe session object
    ...
}

private function handleCheckout($session)
{
    ...
    event(new PaymentSuccessful($payment, Auth::user()));
    ...
}

Was this supposed to happen? How can I get the currently auth user if not like this?

Upvotes: 0

Views: 1133

Answers (1)

Norgul
Norgul

Reputation: 4783

Looks like sessions aren't shared when external source makes a POST request to your route. I made a workaround to include user ID within Stripe session metadata, so I can find user by that same ID when request returns via webhook.

$stripeSession = Session::create([
    'success_url'          => route('stripe.success') . '/?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url'           => route('stripe.cancel'),
    'payment_method_types' => ['card'],
    'mode'                 => 'payment',
    'line_items'           => [
        [
            'price_data'  => [
                'currency'    => 'eur',
                'product'     => env('STRIPE_PRODUCT_ID'),
                'unit_amount' => $price->stripe_price * 100,
            ],
            'description' => "Credits to receive: $price->quantity",
            'quantity'    => 1,
        ],
    ],
    'metadata'             => [
        'quantity' => $price->quantity,
        'user_id'  => Auth::user()->id,
    ],
    'customer_email'       => optional(Auth::user())->email ?? null,
    'client_reference_id'  => optional(Auth::user())->id ?? null,
]);

Upvotes: 1

Related Questions