-
Notifications
You must be signed in to change notification settings - Fork 412
feat(stripe): webhook endpoint and one-off reconciliation #240
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
Tarunkumar0601
wants to merge
5
commits into
frappe:develop
Choose a base branch
from
aerele:feat/stripe-webhooks-reconciliation
base: develop
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
5 commits
Select commit
Hold shift + click to select a range
90eb56e
fix(stripe): remove unknown column payment_plan in field list
Tarunkumar0601 8f92e28
feat(stripe): shared infrastructure for the Stripe refactor
Tarunkumar0601 28f71f1
feat(stripe): modern PaymentIntents checkout (Hosted + Embedded)
Tarunkumar0601 b95fdef
feat(stripe): reuse customers and save cards for off-session reuse
Tarunkumar0601 27b0755
feat(stripe): webhook endpoint and one-off reconciliation
Tarunkumar0601 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| [pre_model_sync] | ||
|
|
||
| [post_model_sync] | ||
| payments.patches.add_stripe_custom_fields |
Empty file.
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 |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # Copyright (c) Frappe Technologies Pvt. Ltd. and contributors | ||
| # License: MIT. See LICENSE | ||
| # | ||
| # Installs the Stripe integration custom fields (Customer.stripe_customer_id, | ||
| # Subscription.stripe_subscription_id / stripe_customer_id, | ||
| # Payment Entry.stripe_payment_intent) on existing sites. make_custom_fields() | ||
| # is idempotent, so re-running is safe. | ||
|
|
||
| from payments.utils import make_custom_fields | ||
|
|
||
|
|
||
| def execute(): | ||
| make_custom_fields() |
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 |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| # Copyright (c) Frappe Technologies Pvt. Ltd. and contributors | ||
| # License: MIT. See LICENSE | ||
| # | ||
| # Stripe webhook endpoint; configure Stripe to POST here and set the signing secret. | ||
|
|
||
| import frappe | ||
|
|
||
| WEBHOOK_SECRET_CACHE_KEY = "stripe_webhook_secrets" | ||
|
|
||
|
|
||
| @frappe.whitelist(allow_guest=True) | ||
| def webhooks(): | ||
| r = frappe.request | ||
| if not r: | ||
| return | ||
|
|
||
| payload = r.get_data() | ||
| sig_header = frappe.get_request_header("Stripe-Signature") | ||
|
|
||
| event, settings = construct_event(payload, sig_header) | ||
| if event is None: | ||
| # Bad/absent signature — tell Stripe to stop, do not process. | ||
| frappe.local.response["http_status_code"] = 400 | ||
| return {"status": "invalid signature"} | ||
|
|
||
| return handle_event(event, settings) | ||
|
|
||
|
|
||
| def construct_event(payload, sig_header): | ||
| """Verify the signature against every configured Stripe account's secret. | ||
|
|
||
| Returns (event, settings_doc) on success, (None, None) on failure. | ||
| """ | ||
| import stripe | ||
|
|
||
| if not sig_header: | ||
| return None, None | ||
|
|
||
| for settings_name, secret in get_webhook_secrets(): | ||
| try: | ||
| event = stripe.Webhook.construct_event(payload, sig_header, secret) | ||
| return event, frappe.get_doc("Stripe Settings", settings_name) | ||
| except stripe.error.SignatureVerificationError: | ||
| continue | ||
| except frappe.DoesNotExistError: | ||
| # Settings deleted since the cache was populated; refresh and skip it. | ||
| clear_cache() | ||
| continue | ||
| except ValueError: | ||
| # Malformed payload — no point trying other secrets. | ||
| return None, None | ||
|
|
||
| return None, None | ||
|
|
||
|
|
||
| def handle_event(event, settings): | ||
| """Dedupe on the Stripe event id, then route to the reconciler. | ||
|
|
||
| A prior *Failed* attempt is allowed to reprocess (its log row is reused); any | ||
| other prior status is a genuine duplicate and is skipped. | ||
| """ | ||
| event_id = event["id"] | ||
| prior = frappe.db.get_value( | ||
| "Stripe Webhook Log", {"stripe_event_id": event_id}, ["name", "status"], as_dict=True | ||
| ) | ||
| if prior and prior.status != "Failed": | ||
| return {"status": "duplicate"} | ||
|
|
||
| if prior: | ||
| log = frappe.get_doc("Stripe Webhook Log", prior.name) | ||
| else: | ||
| obj = event["data"]["object"] | ||
| log = frappe.get_doc( | ||
| { | ||
| "doctype": "Stripe Webhook Log", | ||
| "stripe_event_id": event_id, | ||
| "event_type": event["type"], | ||
| "stripe_object_id": obj.get("id"), | ||
| "status": "Received", | ||
| "stripe_settings": settings.name if settings else None, | ||
| "payload": frappe.as_json(event), | ||
| } | ||
| ) | ||
| try: | ||
| log.insert(ignore_permissions=True) | ||
| frappe.db.commit() # persist the dedupe row before doing any work | ||
| except frappe.exceptions.DuplicateEntryError: | ||
| # Concurrent delivery already inserted it. | ||
| return {"status": "duplicate"} | ||
|
|
||
| try: | ||
| from payments.payment_gateways import stripe_reconcile | ||
|
|
||
| result = stripe_reconcile.route_event(event, settings) or {} | ||
| log.db_set("status", result.get("status_label", "Processed"), update_modified=False) | ||
| if result.get("reference_doctype"): | ||
| log.db_set("reference_doctype", result.get("reference_doctype"), update_modified=False) | ||
| log.db_set("reference_name", result.get("reference_name"), update_modified=False) | ||
| frappe.db.commit() | ||
| except Exception: | ||
| frappe.db.rollback() | ||
| log.db_set("status", "Failed", update_modified=False) | ||
| log.db_set("error", frappe.get_traceback(), update_modified=False) | ||
| frappe.db.commit() | ||
| frappe.log_error(frappe.get_traceback(), "Stripe webhook processing failed") | ||
| # Transient failure — ask Stripe to retry; the dedupe above reprocesses the Failed row. | ||
| frappe.local.response["http_status_code"] = 500 | ||
| return {"status": "error"} | ||
|
|
||
| return {"status": "ok"} | ||
|
|
||
|
|
||
| def get_webhook_secrets(): | ||
| def _load(): | ||
| secrets = [] | ||
| for name in frappe.get_all("Stripe Settings", pluck="name"): | ||
| doc = frappe.get_doc("Stripe Settings", name) | ||
| secret = doc.get_password("webhook_secret", raise_exception=False) | ||
| if secret: | ||
| secrets.append((name, secret)) | ||
| return secrets | ||
|
|
||
| return frappe.cache().get_value(WEBHOOK_SECRET_CACHE_KEY, _load) or [] | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def clear_cache(): | ||
| frappe.cache().delete_value(WEBHOOK_SECRET_CACHE_KEY) | ||
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.
Uh oh!
There was an error while loading. Please reload this page.