In this episode, we focus on how to store sales whenever someone checks out with a product. We start off by creating a new Sale
model and the corresponding migration. In our migration, we carefully design the sales table: it includes a reference to the product being purchased (with a nullable foreign key that won't cascade on delete, so sales records stick around even if products are deleted), a unique and random token (used for security in URLs), the buyer's email address, the price at the time of purchase, the Stripe session ID, and a paid_at
timestamp to note when the payment actually comes through (which might not always be instant if you're waiting on Stripe's webhook).
Once the migration is set, we set up Eloquent relationships between products and sales. We also make sure that the Sale
model auto-generates its token and properly handles the paid_at
timestamp as a Carbon date. We borrow the money accessor from our Product model for consistent formatting of currency values.
Then, the main event: we jump into the Stripe Webhook controller and hook in the logic to create a Sale
whenever Stripe sends back a payment event. We dig into the webhook payload to extract all the info we need, like the product ID (from Stripe metadata), buyer email, session ID, price in cents, and whether the payment was successful. We then save this data in our fresh sales
table.
Finally, we run through an actual test purchase to see it all in action and confirm everything is being logged: unique token, buyer's email, price at checkout, session ID, and the payment date all safely stored. This sets us up nicely for future steps, like sending downloads to customers or displaying purchase history.