After the checkout is completed I want to get the promotion code that was used by the user (if any) and add it to my database.
In my stripe webhook I have the code below. If I remove the promotion code, then the order is added to my database correctly. With the promotion code, nothing is added.
I’ve gone through the docs and I can’t really figure out what i’m doing wrong?
The stripe webhook is delivered successfully and doesn’t show any errors. I appreciate any help 🙂
switch ($event->type) {
case 'checkout.session.completed':
$sessionMain = $event->data->object;
$checkoutID = $sessionMain->id;
try {
$session = StripeCheckoutSession::retrieve([
'id' => $checkoutID,
'expand' => ['total_details.breakdown'],
]);
$promotionCode = $session->total_details->breakdown->discounts->discount->coupon->name;
$sql = "INSERT INTO orders (customer_email, discount_code) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $customer_email, $promotionCode);
if ($stmt->execute()) {
http_response_code(200);
} else {
error_log('Database insert failed: ' . $stmt->error);
http_response_code(500);
}
$stmt->close();
} catch (Exception $e) {
// Log general errors
error_log('General error: ' . $e->getMessage());
http_response_code(500);
}
discounts
is an array here: https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-total_details-breakdown-discounts
So you either need to get the first index or loop over the discounts.