mardi 5 mai 2020

Laravel: How to access controller function from webhook I created to catch Stripe events?

For new credit cards, I used to tokenize the card and then charge it. I had a function inside my CheckoutController.php that trigger the flow:

public function checkoutWithNewCard(Request $request) {
  $total = $request->input('total');
  $customer = $request->user();
  $customer->checkout()->createOrder($request->input('total')
}

createOrder() also create the order on my backend and clears the cart so it needs to run.

I have no switched to using Stripe's new hosted Checkout so a customer is now sent to stripe's own checkout form and upon success, sent back to my site and I am using a webhook to catch checkout.session.completed event.
I have a StripeController.php for my webhooks and tested this properly. I had a log statement inside checkout.session.completed upon checkout and it fires properly.

StripeController.php

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Jobs\CompleteStripeCheckoutWithNewCardJob;


class StripeController extends Controller

{
    public $payload;

    public $event;

    public function __construct()
    {
        $this->payload = @file_get_contents('php://input');
        $this->event = null;
    }

    public function incoming(Request $request)
    {

        try {
            $event = \Stripe\Event::constructFrom(
                json_decode($this->payload, true), $request->all()
            );

        } catch(\UnexpectedValueException $e) {
            // Invalid payload
            return response()->json(['status' => 0, 'message' => 'error']);
        }

        // Handle the event
        switch ($event->type) {
            case 'checkout.session.completed':
                dispatch(new CompleteStripeCheckoutWithNewCardJob();
            default:
                // Unexpected event type

        }
        return response()->json(['success' => "1"], 200);
    }
}

I removed my log statement and created a placehold Job called CompleteStripeCheckoutWithNewCardJob() because I now need to run the logic that was inside my CheckoutController.php to create the order (createOrder()) but I don't know how I can fire those off from inside the Job, a different context.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire