< go back to home

Stripe Webhooks in PHP Tutorial

November 23, 2019

This is a continuation of Stripe tutorial where we tackled the basics of setting up. Check it first here if you haven't done so as there are references from that.

We will now show how Stripe webhooks are implemented. Webhooks are a way to receive response from Stripe events like checkout. An example of a common used case is when after your customer made a successful payment from Checkout page, you may want to record or update your database like changing order status.

It is easy to think that this is done in the "success_url" value that is defined in "Session::create". That is discourage however with the following reason from Stripe itself:

"Do not rely on the redirect to the success_url alone for fulfilling purchases as: Malicious users could directly access the success_url without paying and gain access to your goods or services. Customers may not always reach the success_url after a successful payment. It is possible they close their browser tab before the redirect occurs."

As mentioned, we will use Stripe webhooks to achive this instead, to be able to process customer data after a successful payment.

First, we'll create the webhook endpoint in URL route "/checkout-completed".

Add the following in "routes/web.php".

Create "CheckoutCompleteController" controller in "app/Http/Controllers".

Notice nothing is happenign in the store function. We will get back to that. For now, we will first setup the webhook route in Stripe dashboard.

In the dashboard, click "Developers" then "Webhooks" in the left navigation panel. It will redirect the page in webhooks page. Click the "Add endpoint" button in the main page. Fill up the forms as shown by the screenshot below. For "Endpoint URL", add your target production or stage website's URL for the webhook that was created, in our case, it was "https://yourwebsite.com/checkout-completed". For the "Events to send", select "checkout.session.completed" as the event. Make sure to be as specific when selecting events. For this demo, "checkout.session.completed" is enough for our use case. Click "Add endpoint".



Next is to add the generated "Signing secret" to ".env" file. Refer to the screenshot below for its location. Add the key to the end of the .env file as "STRIPE_SIGNING_SECRET".