I have a webhook that sends out an email to new customers based on invoice.paid
whenever a new customer signs up.
I also have an email that goes out when customers update their payment method, using customer.updated
.
Now, since a new customer sign-up also tiggers the customer.updated
event, I have to filter somehow that the ‘payment method change’ email only goes out to existing customers. I do this by checking for a previous payment method.
Here is how I’m trying to do this, but the payment method email is still triggered by every new customer. Why?
Is there a better way to trigger the ‘payment method change’ email only for existing customers?
case 'customer.updated':
$customer = $event->data->object;
$customerId = $customer->id;
$previousAttributes = $event->data->previous_attributes;
// Check if invoice_settings.default_payment_method OR default_source has changed
$newDefaultPaymentMethodId = $customer->invoice_settings->default_payment_method ?? null;
$newDefaultSourceId = $customer->default_source ?? null;
// Check if there was a previous default payment method or source
$hadPreviousPaymentMethod = isset($previousAttributes['invoice_settings']['default_payment_method']) || isset($previousAttributes['default_source']);
// Only proceed if there was a previous payment method or source
if ($hadPreviousPaymentMethod) {
$oldDefaultPaymentMethodId = $previousAttributes['invoice_settings']['default_payment_method'] ?? null;
$oldDefaultSourceId = $previousAttributes['default_source'] ?? null;
if ($newDefaultPaymentMethodId !== $oldDefaultPaymentMethodId || $newDefaultSourceId !== $oldDefaultSourceId) {
// Retrieve the new default payment method or source details
$paymentMethodId = $newDefaultPaymentMethodId ?: $newDefaultSourceId;
try {
$paymentMethod = StripePaymentMethod::retrieve($paymentMethodId);
$paymentMethodType = $paymentMethod->type;
$brand = '';
$last4 = '';
$exp_month = '';
$exp_year = '';
// Handle card payment method
if ($paymentMethodType === 'card') {
$last4 = $paymentMethod->card->last4;
$exp_month = sprintf("%02d", $paymentMethod->card->exp_month);
$exp_year = $paymentMethod->card->exp_year;
$brand = ucwords($paymentMethod->card->brand);
}
// Handle LINK payment method (or any other)
elseif ($paymentMethodType === 'link') {
$brand = 'LINK account';
}
// You can add more conditions for other payment types here
} catch (StripeExceptionApiErrorException $e) {
logError('Error retrieving payment method.' . $e->getMessage());
}
// Notify user
SEND EMAIL
}
}
break;
2