In this episode, we focus on connecting up subscriptions with referral codes so we can track which subscriptions come from which referrals. This is super important because if a user keeps paying month after month, we need to know which referral code is responsible—especially if we're giving payouts based on ongoing subscription payments.
We'll start by setting up a new database pivot table to make this connection, including storing things like a multiplier (the commission percentage for the referral) so it can be customized later. This helps us avoid issues if we ever want to update the commission rate for new referrals. We walk through creating the migration, then talk through what the table will look like with example data.
After that's set up, we move on to handling the subscription_created
event from Stripe. We'll listen for this webhook event, look up the referral code from metadata sent during checkout, and make sure to reliably connect the new subscription to the correct referral. Because sometimes subscriptions aren't in the database when the webhook comes in, we'll use Laravel's retry
helper to keep trying until it works.
Once everything is hooked up, we'll create a relationship in our ReferralCode model to easily access related subscriptions, making sure we avoid duplicate records if the webhook fires multiple times. At the end, we confirm our new system works by stepping through a fresh subscription sign-up and checking our database.
All set! With this in place, we can now accurately track referral-linked subscriptions and set ourselves up to show referral stats later on the dashboard.