Skip to content

Instantly share code, notes, and snippets.

@EduardoIbarra
Created March 15, 2024 12:20
Show Gist options
  • Select an option

  • Save EduardoIbarra/f3c6fecaaeddb0e2ce23c11092c81e31 to your computer and use it in GitHub Desktop.

Select an option

Save EduardoIbarra/f3c6fecaaeddb0e2ce23c11092c81e31 to your computer and use it in GitHub Desktop.
Example of stripe integration with webhooks
public function handle_webhookOwnAccounts(Request $request)
{
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
// Retrieve the request body and signature header
$payload = $request->getContent();
$sigHeader = $request->header('Stripe-Signature');
$endpointSecret = env('STRIPE_WEBHOOK_OWN_SECRET');
try {
// Construct the event
$event = \Stripe\Webhook::constructEvent(
$payload,
$sigHeader,
$endpointSecret
);
} catch (\UnexpectedValueException $e) {
// Invalid payload
return response()->json(['error' => 'Invalid payload'], 400);
} catch (\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
return response()->json(['error' => 'Invalid signature'], 400);
}
// Handle the event
switch ($event->type) {
case 'checkout.session.completed':
// Extract required data from the event
$stripeId = $event->data->object->id;
$eventProfileId = $event->data->object->client_reference_id;
$eventId = $event->id;
$status = $event->data->object->payment_status;
$paymentIntentId = $event->data->object->payment_intent;
// Perform necessary actions based on the event
$this->validateExternalPayment($stripeId, $eventProfileId, $eventId, $status, $paymentIntentId);
break;
case 'charge.refunded':
// Extract required data from the event
$stripeId = $event->data->object->id;
$paymentIntent = $event->data->object->payment_intent;
$status = $event->data->object->payment_status;
$isRefunded = $event->data->object->refunded;
if ($isRefunded) {
// Log the refunded event details
\Log::info('refund.refunded', [
'stripeId' => $stripeId,
'paymentIntent' => $paymentIntent,
'status' => $status
]);
// Update the event_profile table with payment_status and set participant_number to null
\DB::table('event_profile')
->where('payment_intent', $paymentIntent)
->update([
'payment_status' => 'refunded',
'participant_number' => null
]);
} else {
// Log that the refunded property was not set to true
\Log::info('Refunded property was not set to true for event ID: ' . $event->id);
}
break;
default:
// Handle other types of events if needed
break;
}
// Respond with success
return response()->json(['success' => true]);
}
private function validateExternalPayment($stripe_id, $eventProfileId, $stripe_event_id, $status, $paymentIntentId)
{
// Log a message to the Laravel log file
\Log::info('Validating external payment', [
'stripe_id' => $stripe_id,
'eventProfileId' => $eventProfileId,
'stripe_event_id' => $stripe_event_id,
'status' => $status,
'paymentIntentId' => $paymentIntentId,
]);
$eventProfile = EventProfile::find($eventProfileId);
// Retrieve the route_id for the given event profile
$routeId = DB::table('event_profile')
->where('id', $eventProfileId)
->value('route_id');
if ($status == 'unpaid') {
// Update the eventProfile on the database
DB::table('event_profile')
->where('id', $eventProfileId)
->update([
'stripe_checkout_id' => $stripe_id,
'payment_status' => $status,
'payment_intent' => $paymentIntentId,
]);
return;
}
// Increment participant_number for the given route_id
$participantNumber = DB::table('event_profile')
->where('route_id', $routeId)
->max('participant_number') + 1;
\Log::info('Participant number: ' . $participantNumber);
// Update the eventProfile on the database
DB::table('event_profile')
->where('id', $eventProfileId)
->update([
'stripe_checkout_id' => $stripe_id,
'payment_status' => $status,
'participant_number' => $participantNumber,
'payment_intent' => $paymentIntentId,
]);
$participantNumberPadded = str_pad($participantNumber, 3, "0", STR_PAD_LEFT);
// Prepare data for SendGrid template
$emailData = [
'participant_number' => $participantNumberPadded,
'event_profile_id' => $eventProfileId,
];
// Send confirmation email using SendGrid template
// Replace 'YOUR_SENDGRID_API_KEY' with your actual SendGrid API key
// Replace 'YOUR_TEMPLATE_ID' with your SendGrid template ID
$email = new \SendGrid\Mail\Mail();
$email->setFrom("john@smith.com", "John Smith");
$email->setTemplateId("d-070db3xxxxxxxxxxxxxxxxxxxxxxxxxx"); // Set SendGrid template ID
$email->addTo($eventProfile->stripe_webhook_email_notification, $eventProfile->full_name);
\Log::info('Email to: ' . $eventProfile->stripe_webhook_email_notification);
// Add dynamic template data
foreach ($emailData as $key => $value) {
$email->addDynamicTemplateData($key, $value);
}
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($email);
\Log::info('Email sent successfully.');
} catch (Exception $e) {
\Log::error('Failed to send email: ' . $e->getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment