-
Notifications
You must be signed in to change notification settings - Fork 4
Implement stripe webhook #136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shahzaib-ali-khan
wants to merge
20
commits into
sajanv88:main
Choose a base branch
from
shahzaib-ali-khan:feature/stripe-webhook
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
c5f13d6
Fix pydantic validation error
shahzaib-ali-khan 8cc1633
Create OS independent temp file for AuditLogs
shahzaib-ali-khan e67da80
Fix typo in variables name
shahzaib-ali-khan 8825c73
Fix Invoice field name
shahzaib-ali-khan 2f02603
Revrt back last commit
shahzaib-ali-khan 93823c8
Add invoice.paid Stripe webhook
shahzaib-ali-khan 241ec53
Remove /webhooks/stripe from cache
shahzaib-ali-khan bedc6ec
Use BillingRecord class
shahzaib-ali-khan 453ac68
Merge branch 'sajanv88:main' into feature/stripe-webhook
shahzaib-ali-khan 54b2bf6
Merge branch 'sajanv88:main' into main
shahzaib-ali-khan d5309d5
Check scope early
shahzaib-ali-khan 6d6d9ad
Remove tenant check inside billing_record_service
shahzaib-ali-khan 3ad65f5
Move Webhook to stripe_endpoint file
shahzaib-ali-khan 43acd1d
Add stripe_webhook_secret to config and check scope in /webhooks
shahzaib-ali-khan 3846ba4
Add missing env varible in example file
shahzaib-ali-khan 05ee1a9
Merge branch 'main' into feature/stripe-webhook
shahzaib-ali-khan 5b33553
Remove stale import
shahzaib-ali-khan 739c2bb
Update endpoint url
shahzaib-ali-khan 5582720
Merge branch 'sajanv88:main' into feature/stripe-webhook
shahzaib-ali-khan 86fcbdd
Merge branch 'main' into feature/stripe-webhook
shahzaib-ali-khan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 131 additions & 13 deletions
144
backend/api/interfaces/api_controllers/stripe_endpoint.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,39 +1,157 @@ | ||
| from fastapi import APIRouter, Depends, status | ||
| from typing import Any | ||
|
|
||
| import stripe | ||
| from api.common.exceptions import InvalidOperationException | ||
| from api.core.container import get_stripe_setting_service | ||
| from api.common.utils import get_logger | ||
| from api.core.container import get_billing_record_service, get_stripe_setting_service | ||
| from api.domain.dtos.stripe_setting_dto import CreateStripeSettingDto, StripeSettingDto | ||
| from api.domain.enum.feature import Feature as FeatureEnum | ||
| from api.domain.enum.permission import Permission | ||
| from api.domain.security.feature_access_management import check_feature_access | ||
| from api.infrastructure.security.current_user import CurrentUser | ||
| from api.interfaces.security.role_checker import check_permissions_for_current_role | ||
| from api.usecases.billing_record_service import BillingRecordService | ||
| from api.usecases.stripe_setting_service import StripeSettingService | ||
| from api.domain.enum.feature import Feature as FeatureEnum | ||
| from fastapi import APIRouter, Depends, HTTPException, Request, status | ||
| from fastapi.responses import JSONResponse | ||
| from api.core.config import settings | ||
|
|
||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
| router = APIRouter(prefix="/configurations", dependencies=[ | ||
| Depends(check_permissions_for_current_role(required_permissions=[Permission.MANAGE_PAYMENTS_SETTINGS])), | ||
| Depends(check_feature_access(FeatureEnum.STRIPE)) | ||
| ]) | ||
|
|
||
| router = APIRouter( | ||
| prefix="/configurations", | ||
| dependencies=[ | ||
| Depends( | ||
| check_permissions_for_current_role( | ||
| required_permissions=[Permission.MANAGE_PAYMENTS_SETTINGS] | ||
| ) | ||
| ), | ||
| Depends(check_feature_access(FeatureEnum.STRIPE)), | ||
| ], | ||
| ) | ||
| router.tags = ["Stripe"] | ||
|
|
||
|
|
||
| @router.post("/stripe", status_code=status.HTTP_201_CREATED) | ||
| async def configure_stripe_setting( | ||
| configuration: CreateStripeSettingDto, | ||
| current_user: CurrentUser, | ||
| stripe_setting_service: StripeSettingService = Depends(get_stripe_setting_service) | ||
| stripe_setting_service: StripeSettingService = Depends(get_stripe_setting_service), | ||
| ): | ||
| if not current_user.tenant_id: | ||
| raise InvalidOperationException("Tenant context is required to configure Stripe settings.") | ||
| raise InvalidOperationException( | ||
| "Tenant context is required to configure Stripe settings." | ||
| ) | ||
|
|
||
| await stripe_setting_service.configure_stripe_settings(settings=configuration, tenant_id=str(current_user.tenant_id)) | ||
| await stripe_setting_service.configure_stripe_settings( | ||
| settings=configuration, tenant_id=str(current_user.tenant_id) | ||
| ) | ||
| return status.HTTP_201_CREATED | ||
|
|
||
|
|
||
| @router.get("/stripe", response_model=StripeSettingDto, status_code=status.HTTP_200_OK) | ||
| async def get_stripe_settings( | ||
| current_user: CurrentUser, | ||
| stripe_setting_service: StripeSettingService = Depends(get_stripe_setting_service) | ||
| stripe_setting_service: StripeSettingService = Depends(get_stripe_setting_service), | ||
| ): | ||
| if not current_user.tenant_id: | ||
| raise InvalidOperationException("Tenant context is required to get Stripe settings.") | ||
| return await stripe_setting_service.get_stripe_settings() | ||
| raise InvalidOperationException( | ||
| "Tenant context is required to get Stripe settings." | ||
| ) | ||
| return await stripe_setting_service.get_stripe_settings() | ||
|
|
||
|
|
||
| SUPPORTED_EVENTS = { | ||
| "invoice.paid": lambda obj, svc: handle_invoice_paid(obj, svc), | ||
| } | ||
|
|
||
|
|
||
| @router.post("/stripe/webhooks", status_code=status.HTTP_200_OK) | ||
| async def stripe_webhook( | ||
| request: Request, | ||
| stripe_setting_service: StripeSettingService = Depends(get_stripe_setting_service), | ||
| billing_record_service: BillingRecordService = Depends(get_billing_record_service), | ||
| ): | ||
| event = None | ||
| stripe_webhook_secret = None | ||
| payload = await request.body() | ||
| stripe_settings = await stripe_setting_service.get_stripe_secret() | ||
|
|
||
| # Check the request context for tenant or host. If tenant then get tenant webhook secret otherwise use host from env | ||
| if request.state.tenant_id: | ||
| # Tenant-scoped webhook | ||
| if not stripe_settings or not stripe_settings.stripe_webhook_secret: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail="Tenant webhook secret not configured", | ||
| ) | ||
| stripe_webhook_secret = stripe_settings.stripe_webhook_secret | ||
| else: | ||
| # Host-scoped webhook | ||
| stripe_webhook_secret = settings.stripe_webhook_secret | ||
|
|
||
| try: | ||
| sig_header = request.headers.get("stripe-signature") | ||
|
|
||
| event = stripe.Webhook.construct_event( | ||
| payload=payload, | ||
| sig_header=sig_header, | ||
| secret=stripe_webhook_secret, | ||
| ) | ||
| except ValueError: | ||
| # Invalid payload | ||
| logger.error("Invalid payload") | ||
| raise HTTPException(status_code=400, detail="Invalid payload") | ||
| except stripe.error.SignatureVerificationError as e: | ||
| logger.error(f"Webhook signature verification failed: {e}") | ||
| raise HTTPException(status_code=400, detail="Invalid signature") | ||
| except Exception as e: | ||
| logger.error(f"Unexpected error constructing event: {e}") | ||
| raise HTTPException(status_code=400, detail="Webhook error") | ||
|
|
||
| # Extract the event type and object | ||
| event_type = event["type"] | ||
| data_object = event["data"]["object"] | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Handle relevant Stripe events | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| if event_type not in SUPPORTED_EVENTS: | ||
| logger.error(f"Unhandled event type: {event_type}") | ||
| return JSONResponse( | ||
| status_code=404, content={"message": "Unhandled event type"} | ||
| ) | ||
|
|
||
| await SUPPORTED_EVENTS.get(event_type, None)(data_object, billing_record_service) | ||
|
|
||
| return JSONResponse(status_code=200, content={"status": "success"}) | ||
|
|
||
|
|
||
| async def handle_invoice_paid( | ||
| invoice: dict[str, Any], | ||
| billing_record_service: BillingRecordService, | ||
| ) -> None: | ||
| tenant_id = invoice.get("metadata", {}).get("tenant_id") | ||
|
|
||
| billing_record = await billing_record_service.from_stripe_invoice_paid( | ||
| invoice=invoice, scope="tenant" if tenant_id else "host", tenant_id=tenant_id | ||
| ) | ||
|
|
||
| if not billing_record: | ||
| logger.warning( | ||
| f"Could not convert invoice to BillingRecordDto: {invoice['id']}" | ||
| ) | ||
| return | ||
|
|
||
| try: | ||
| await billing_record_service.create_billing_record(billing_record) | ||
| logger.info( | ||
| f"BillingRecord created for tenant {tenant_id} – invoice {invoice['id']}" | ||
| ) | ||
| except Exception as e: | ||
| logger.exception( | ||
| f"Failed to save BillingRecord for invoice {invoice['id']}: {e}" | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
/api/v1/configurations/stripe/webhooks