bwh-payments-core 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. bwh_payments_core-0.1.1/PKG-INFO +18 -0
  2. bwh_payments_core-0.1.1/README.md +3 -0
  3. bwh_payments_core-0.1.1/bwh_payments_core/__init__.py +1 -0
  4. bwh_payments_core-0.1.1/bwh_payments_core/connectors/__init__.py +12 -0
  5. bwh_payments_core-0.1.1/bwh_payments_core/connectors/razorpay/__init__.py +0 -0
  6. bwh_payments_core-0.1.1/bwh_payments_core/connectors/razorpay/base.py +42 -0
  7. bwh_payments_core-0.1.1/bwh_payments_core/connectors/razorpay/gateway.py +251 -0
  8. bwh_payments_core-0.1.1/bwh_payments_core/connectors/razorpay/live.py +99 -0
  9. bwh_payments_core-0.1.1/bwh_payments_core/connectors/razorpay/stub.py +131 -0
  10. bwh_payments_core-0.1.1/bwh_payments_core/connectors/stripe/__init__.py +0 -0
  11. bwh_payments_core-0.1.1/bwh_payments_core/connectors/stripe/base.py +40 -0
  12. bwh_payments_core-0.1.1/bwh_payments_core/connectors/stripe/gateway.py +164 -0
  13. bwh_payments_core-0.1.1/bwh_payments_core/connectors/stripe/live.py +29 -0
  14. bwh_payments_core-0.1.1/bwh_payments_core/connectors/stripe/stub.py +129 -0
  15. bwh_payments_core-0.1.1/bwh_payments_core/connectors/tabby/__init__.py +0 -0
  16. bwh_payments_core-0.1.1/bwh_payments_core/connectors/tabby/base.py +62 -0
  17. bwh_payments_core-0.1.1/bwh_payments_core/connectors/tabby/gateway.py +281 -0
  18. bwh_payments_core-0.1.1/bwh_payments_core/connectors/tabby/live.py +101 -0
  19. bwh_payments_core-0.1.1/bwh_payments_core/connectors/tabby/stub.py +100 -0
  20. bwh_payments_core-0.1.1/bwh_payments_core/connectors/telr/__init__.py +0 -0
  21. bwh_payments_core-0.1.1/bwh_payments_core/connectors/telr/base.py +45 -0
  22. bwh_payments_core-0.1.1/bwh_payments_core/connectors/telr/gateway.py +141 -0
  23. bwh_payments_core-0.1.1/bwh_payments_core/connectors/telr/live.py +145 -0
  24. bwh_payments_core-0.1.1/bwh_payments_core/connectors/telr/stub.py +71 -0
  25. bwh_payments_core-0.1.1/bwh_payments_core/contract.py +65 -0
  26. bwh_payments_core-0.1.1/bwh_payments_core/currency.py +56 -0
  27. bwh_payments_core-0.1.1/bwh_payments_core/engine/__init__.py +11 -0
  28. bwh_payments_core-0.1.1/bwh_payments_core/engine/checkout.py +34 -0
  29. bwh_payments_core-0.1.1/bwh_payments_core/engine/payment_request.py +355 -0
  30. bwh_payments_core-0.1.1/bwh_payments_core/engine/refund.py +76 -0
  31. bwh_payments_core-0.1.1/bwh_payments_core/engine/webhook.py +186 -0
  32. bwh_payments_core-0.1.1/bwh_payments_core/logos/__init__.py +10 -0
  33. bwh_payments_core-0.1.1/bwh_payments_core/logos/razorpay-dark.svg +21 -0
  34. bwh_payments_core-0.1.1/bwh_payments_core/logos/razorpay.svg +21 -0
  35. bwh_payments_core-0.1.1/bwh_payments_core/models.py +45 -0
  36. bwh_payments_core-0.1.1/bwh_payments_core/testing.py +134 -0
  37. bwh_payments_core-0.1.1/bwh_payments_core/utils.py +48 -0
  38. bwh_payments_core-0.1.1/license.txt +21 -0
  39. bwh_payments_core-0.1.1/pyproject.toml +74 -0
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: bwh-payments-core
3
+ Version: 0.1.1
4
+ Summary: Payment gateway connectors and the payment engine for Frappe apps
5
+ Author-email: "developers@buildwithhussain.com" <developers@buildwithhussain.com>
6
+ Requires-Python: >=3.14
7
+ Description-Content-Type: text/markdown
8
+ License-File: license.txt
9
+ Requires-Dist: stripe>=12.5,<16
10
+ Requires-Dist: pydantic>=2,<3
11
+ Requires-Dist: pytest>=8 ; extra == "test"
12
+ Project-URL: Source, https://github.com/bwhtech/bwh_payments_core
13
+ Provides-Extra: test
14
+
15
+ # bwh_payments_core
16
+
17
+ Payment gateway connectors (Stripe, Razorpay, Telr, Tabby) and the payment engine for Frappe apps, as a plain Python package. A host app keeps the doctypes and whitelisted endpoints; this package holds the gateway code they call. It is not a Frappe app and is never installed on a site. Install it from PyPI: `pip install bwh-payments-core`.
18
+
@@ -0,0 +1,3 @@
1
+ # bwh_payments_core
2
+
3
+ Payment gateway connectors (Stripe, Razorpay, Telr, Tabby) and the payment engine for Frappe apps, as a plain Python package. A host app keeps the doctypes and whitelisted endpoints; this package holds the gateway code they call. It is not a Frappe app and is never installed on a site. Install it from PyPI: `pip install bwh-payments-core`.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.1"
@@ -0,0 +1,12 @@
1
+ import frappe
2
+ from pydantic import BaseModel, ConfigDict
3
+
4
+
5
+ class GatewayUnavailableError(frappe.ValidationError):
6
+ """The gateway could not answer (a 5xx, a rate limit or a dropped connection), so a retry may work."""
7
+
8
+
9
+ class GatewayModel(BaseModel):
10
+ """Gateways sometimes send ids or amounts as bare numbers; read them as strings."""
11
+
12
+ model_config = ConfigDict(coerce_numbers_to_str=True)
@@ -0,0 +1,42 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from bwh_payments_core.connectors import GatewayModel
4
+
5
+
6
+ class RazorpayPayment(GatewayModel):
7
+ payment_id: str
8
+ status: str | None = None
9
+
10
+
11
+ class RazorpayPaymentLink(GatewayModel):
12
+ id: str
13
+ status: str | None = None
14
+ short_url: str | None = None
15
+ payments: list[RazorpayPayment] | None = None
16
+
17
+
18
+ class RazorpayRefund(GatewayModel):
19
+ id: str | None = None
20
+ status: str | None = None
21
+ # Minor units, as Razorpay echoes it.
22
+ amount: int | None = None
23
+
24
+
25
+ class BaseRazorpayClient(ABC):
26
+ """Razorpay's Payment Links and Refunds APIs. A rejected call raises `frappe.ValidationError`."""
27
+
28
+ @abstractmethod
29
+ def create_payment_link(self, payload: dict) -> RazorpayPaymentLink: ...
30
+
31
+ @abstractmethod
32
+ def get_payment_link(self, link_id: str) -> RazorpayPaymentLink: ...
33
+
34
+ @abstractmethod
35
+ def cancel_payment_link(self, link_id: str) -> RazorpayPaymentLink: ...
36
+
37
+ @abstractmethod
38
+ def create_refund(self, payment_id: str, amount: int) -> RazorpayRefund:
39
+ """Refund `amount` minor units of a captured payment."""
40
+
41
+ @abstractmethod
42
+ def get_refund(self, refund_id: str) -> RazorpayRefund: ...
@@ -0,0 +1,251 @@
1
+ # Copyright (c) 2026, Build With Hussain and contributors
2
+ # For license information, please see license.txt
3
+
4
+ import hashlib
5
+ import hmac
6
+
7
+ import frappe
8
+ from frappe import _
9
+ from frappe.utils import validate_email_address
10
+ from frappe.utils.data import flt
11
+
12
+ from bwh_payments_core.connectors.razorpay.base import BaseRazorpayClient, RazorpayPaymentLink
13
+ from bwh_payments_core.connectors.razorpay.live import LiveRazorpayClient
14
+ from bwh_payments_core.connectors.razorpay.stub import StubRazorpayClient
15
+ from bwh_payments_core.contract import PaymentGatewayBase
16
+ from bwh_payments_core.currency import from_minor_units, to_minor_units, validate_transaction_currency
17
+ from bwh_payments_core.models import CheckoutSession, RefundResult, WebhookEvent
18
+ from bwh_payments_core.utils import add_reference_id, get_localised_url
19
+
20
+ # Unmapped states stay Pending.
21
+ RAZORPAY_LINK_STATUS_MAP = {
22
+ "paid": "Paid",
23
+ "created": "Pending",
24
+ "partially_paid": "Pending",
25
+ "expired": "Expired",
26
+ "cancelled": "Cancelled",
27
+ }
28
+
29
+ RAZORPAY_AUTHORISED_STATUS = "authorized"
30
+ RAZORPAY_CANCELLED_STATUS = "cancelled"
31
+ RAZORPAY_CAPTURED_STATUS = "captured"
32
+ RAZORPAY_PAID_EVENT = "payment_link.paid"
33
+ RAZORPAY_REFUND_EVENTS = ("refund.created", "refund.processed", "refund.failed")
34
+ # Payments taken before Payment Links (e.g. imported from frappe/payments) are keyed on the payment id.
35
+ RAZORPAY_PAYMENT_ID_PREFIX = "pay_"
36
+ RAZORPAY_ACCEPTED_REFUND_STATUSES = ("processed", "pending")
37
+
38
+ # Title case: `dict(frappe.request.headers)` drops werkzeug's case-insensitivity.
39
+ RAZORPAY_SIGNATURE_HEADER = "X-Razorpay-Signature"
40
+ RAZORPAY_EVENT_ID_HEADER = "X-Razorpay-Event-Id"
41
+
42
+
43
+ class RazorpayGateway(PaymentGatewayBase):
44
+ label = "Razorpay"
45
+ credential_fields = (
46
+ "key_id",
47
+ "key_secret",
48
+ "webhook_secret",
49
+ "currency",
50
+ "treat_authorised_as_paid",
51
+ "send_razorpay_notifications",
52
+ "success_url",
53
+ "failure_url",
54
+ "cancelled_url",
55
+ )
56
+ logo_file = "razorpay.svg"
57
+ logo_dark_file = "razorpay-dark.svg"
58
+ description = "Cards, UPI, netbanking and wallets. India."
59
+ docs_url = "https://dashboard.razorpay.com/app/website-app-settings/webhooks"
60
+
61
+ def get_gateway_name(self) -> str:
62
+ return "Razorpay"
63
+
64
+ def get_client(self) -> BaseRazorpayClient:
65
+ if frappe.in_test:
66
+ return StubRazorpayClient()
67
+
68
+ return LiveRazorpayClient(self.key_id, self.get_password("key_secret"))
69
+
70
+ def create_session(
71
+ self,
72
+ amount: float,
73
+ currency: str,
74
+ reference: str | None = None,
75
+ customer: dict | None = None,
76
+ return_url: str | None = None,
77
+ ) -> CheckoutSession:
78
+ currency = currency or self.currency
79
+ validate_transaction_currency(currency)
80
+
81
+ notify = bool(self.send_razorpay_notifications)
82
+ payload = {
83
+ "amount": to_minor_units(amount, currency),
84
+ "currency": currency.upper(),
85
+ "reference_id": reference,
86
+ "description": _("Online order payment"),
87
+ "callback_url": return_url or self.build_success_url(reference),
88
+ "callback_method": "get",
89
+ # Explicit, so the account's billable SMS/email defaults do not apply.
90
+ "notify": {"sms": notify, "email": notify},
91
+ "reminder_enable": notify,
92
+ "notes": {"reference_id": reference or ""},
93
+ }
94
+ if customer_details := get_customer_details(customer or {}):
95
+ payload["customer"] = customer_details
96
+
97
+ link = self.get_client().create_payment_link(payload)
98
+ # A Payment Link has one callback; cancel and failure URLs are only for the storefront.
99
+ return CheckoutSession(
100
+ session_id=link.id,
101
+ redirect_url=link.short_url,
102
+ success_url=payload["callback_url"],
103
+ cancel_url=return_url or get_localised_url(self.cancelled_url),
104
+ failure_url=return_url or get_localised_url(self.failure_url),
105
+ )
106
+
107
+ def build_success_url(self, reference: str | None) -> str:
108
+ """Razorpay sends `razorpay_payment_link_reference_id`; the storefront reads `reference_id`."""
109
+ if not self.success_url:
110
+ frappe.throw(_("Please set the Success URL in Razorpay Gateway Settings"))
111
+ return add_reference_id(self.success_url, reference)
112
+
113
+ def get_payment_status(self, session_id: str) -> str:
114
+ payment_link = self.get_client().get_payment_link(session_id)
115
+ link_status = (payment_link.status or "").strip().casefold()
116
+ status = RAZORPAY_LINK_STATUS_MAP.get(link_status, "Pending")
117
+ if status != "Pending":
118
+ return status
119
+
120
+ # The link does not say whether the account auto-captures, hence the opt-in switch.
121
+ # `partially_paid` also maps to Pending, so only an open link qualifies.
122
+ if (
123
+ link_status == "created"
124
+ and self.treat_authorised_as_paid
125
+ and has_authorised_payment(payment_link)
126
+ ):
127
+ return "Paid"
128
+
129
+ return status
130
+
131
+ def handle_webhook(self, payload: bytes, headers: dict) -> WebhookEvent | None:
132
+ webhook_secret = self.get_password("webhook_secret")
133
+ if not webhook_secret:
134
+ frappe.throw(_("Webhook secret is not configured in Razorpay Gateway Settings"))
135
+
136
+ signature = headers.get(RAZORPAY_SIGNATURE_HEADER)
137
+ if not signature:
138
+ frappe.throw(_("Missing {0} header").format(RAZORPAY_SIGNATURE_HEADER))
139
+
140
+ # Replay protection rests on this header; the body has no event id.
141
+ event_id = headers.get(RAZORPAY_EVENT_ID_HEADER)
142
+ if not event_id:
143
+ frappe.throw(_("Missing {0} header").format(RAZORPAY_EVENT_ID_HEADER))
144
+
145
+ # Signed over the raw bytes with the webhook secret, not `key_secret`.
146
+ expected_signature = hmac.new(webhook_secret.encode(), payload, hashlib.sha256).hexdigest()
147
+ # compare_digest raises TypeError on a non-ASCII str.
148
+ if not signature.isascii() or not hmac.compare_digest(expected_signature, signature):
149
+ frappe.throw(_("Razorpay webhook signature does not match"))
150
+
151
+ # parse_json passes bytes through untouched.
152
+ event = frappe.parse_json(payload.decode())
153
+ if event.get("event") in RAZORPAY_REFUND_EVENTS:
154
+ return read_refund_event(event, event_id)
155
+ if event.get("event") != RAZORPAY_PAID_EVENT:
156
+ return None
157
+
158
+ payment_link = ((event.get("payload") or {}).get("payment_link") or {}).get("entity") or {}
159
+ session_id = payment_link.get("id")
160
+ status = RAZORPAY_LINK_STATUS_MAP.get(
161
+ (payment_link.get("status") or "").strip().casefold(), "Pending"
162
+ )
163
+ # This event means paid, so an unreadable entity must 400 and be retried, not 200 and lost.
164
+ if not session_id or status != "Paid":
165
+ frappe.throw(_("Unreadable payment link entity on a {0} event").format(RAZORPAY_PAID_EVENT))
166
+
167
+ # The link id, not the payment id: `order_ref` holds the link id.
168
+ return WebhookEvent(session_id=session_id, status=status, event_id=event_id)
169
+
170
+ def cancel_session(self, session_id: str) -> bool:
171
+ try:
172
+ link = self.get_client().cancel_payment_link(session_id)
173
+ except frappe.ValidationError:
174
+ return False
175
+
176
+ return (link.status or "").strip().casefold() == RAZORPAY_CANCELLED_STATUS
177
+
178
+ def get_refund_status(self, session_id: str, refund_id: str) -> RefundResult:
179
+ refund = self.get_client().get_refund(refund_id)
180
+ return RefundResult(refund_id=refund.id, status=refund.status)
181
+
182
+ def get_transaction_ref(self, session_id: str) -> str | None:
183
+ payments = self.get_client().get_payment_link(session_id).payments or []
184
+ for wanted in (RAZORPAY_CAPTURED_STATUS, RAZORPAY_AUTHORISED_STATUS):
185
+ for payment in payments:
186
+ if (payment.status or "").strip().casefold() == wanted:
187
+ return payment.payment_id
188
+ return None
189
+
190
+ def refund_payment(self, session_id: str, amount: float, currency: str | None = None) -> RefundResult:
191
+ currency = currency or self.currency
192
+ client = self.get_client()
193
+ if session_id.startswith(RAZORPAY_PAYMENT_ID_PREFIX):
194
+ payment_id = session_id
195
+ else:
196
+ payment_id = get_captured_payment_id(client.get_payment_link(session_id))
197
+
198
+ refund = client.create_refund(payment_id, to_minor_units(amount, currency))
199
+ if refund.status not in RAZORPAY_ACCEPTED_REFUND_STATUSES:
200
+ frappe.throw(_("Refund failed with status: {0}").format(refund.status))
201
+
202
+ if refund.amount is not None:
203
+ amount = flt(from_minor_units(refund.amount, currency))
204
+ return RefundResult(refund_id=refund.id, status=refund.status, amount=amount)
205
+
206
+
207
+ def read_refund_event(event: dict, event_id: str) -> WebhookEvent:
208
+ refund = ((event.get("payload") or {}).get("refund") or {}).get("entity") or {}
209
+ currency = refund.get("currency") or "INR"
210
+ return WebhookEvent(
211
+ refund_id=refund.get("id"),
212
+ status=refund.get("status") or "",
213
+ refund_amount=from_minor_units(refund.get("amount") or 0, currency),
214
+ transaction_ref=refund.get("payment_id"),
215
+ event_id=event_id,
216
+ )
217
+
218
+
219
+ def get_customer_details(customer: dict) -> dict:
220
+ """Razorpay rejects a blank `contact` or `email`, so empty values are dropped."""
221
+ details = {
222
+ "name": get_customer_name(customer),
223
+ "email": validate_email_address(customer.get("email") or "", throw=False),
224
+ "contact": customer.get("phone"),
225
+ }
226
+ return {key: value for key, value in details.items() if value}
227
+
228
+
229
+ def get_customer_name(customer: dict) -> str:
230
+ name = customer.get("name") or {}
231
+ return " ".join(part for part in (name.get("forenames"), name.get("surname")) if part)
232
+
233
+
234
+ def has_authorised_payment(payment_link: RazorpayPaymentLink) -> bool:
235
+ return any(
236
+ (payment.status or "").strip().casefold() == RAZORPAY_AUTHORISED_STATUS
237
+ for payment in payment_link.payments or []
238
+ )
239
+
240
+
241
+ def get_captured_payment_id(payment_link: RazorpayPaymentLink) -> str:
242
+ for payment in payment_link.payments or []:
243
+ if (payment.status or "").strip().casefold() == RAZORPAY_CAPTURED_STATUS:
244
+ return payment.payment_id
245
+
246
+ frappe.throw(
247
+ _(
248
+ "Razorpay has no captured payment for this link. An authorised but uncaptured payment has to be"
249
+ " refunded from the Razorpay dashboard."
250
+ )
251
+ )
@@ -0,0 +1,99 @@
1
+ from typing import NoReturn
2
+
3
+ import frappe
4
+ from frappe import _
5
+ from frappe.integrations.utils import create_request_log, make_get_request, make_post_request
6
+
7
+ from bwh_payments_core.connectors.razorpay.base import (
8
+ BaseRazorpayClient,
9
+ RazorpayPaymentLink,
10
+ RazorpayRefund,
11
+ )
12
+
13
+ RAZORPAY_BASE_URL = "https://api.razorpay.com/v1"
14
+ RAZORPAY_HEADERS = {"accept": "application/json", "Content-Type": "application/json"}
15
+ SETTINGS_DOCTYPE = "Razorpay Gateway Settings"
16
+
17
+
18
+ class LiveRazorpayClient(BaseRazorpayClient):
19
+ def __init__(self, key_id: str, key_secret: str):
20
+ self.auth = (key_id, key_secret)
21
+
22
+ def create_payment_link(self, payload: dict) -> RazorpayPaymentLink:
23
+ return RazorpayPaymentLink.model_validate(self.post("/payment_links", payload))
24
+
25
+ def get_payment_link(self, link_id: str) -> RazorpayPaymentLink:
26
+ return RazorpayPaymentLink.model_validate(self.get(f"/payment_links/{link_id}"))
27
+
28
+ def cancel_payment_link(self, link_id: str) -> RazorpayPaymentLink:
29
+ return RazorpayPaymentLink.model_validate(self.post(f"/payment_links/{link_id}/cancel", {}))
30
+
31
+ def create_refund(self, payment_id: str, amount: int) -> RazorpayRefund:
32
+ return RazorpayRefund.model_validate(self.post(f"/payments/{payment_id}/refund", {"amount": amount}))
33
+
34
+ def get_refund(self, refund_id: str) -> RazorpayRefund:
35
+ return RazorpayRefund.model_validate(self.get(f"/refunds/{refund_id}"))
36
+
37
+ def post(self, endpoint: str, payload: dict) -> dict:
38
+ url = f"{RAZORPAY_BASE_URL}{endpoint}"
39
+ try:
40
+ response = make_post_request(url, auth=self.auth, json=payload, headers=RAZORPAY_HEADERS)
41
+ except Exception as exception:
42
+ throw_request_error(url, exception)
43
+ return read_response(url, response)
44
+
45
+ def get(self, endpoint: str) -> dict:
46
+ url = f"{RAZORPAY_BASE_URL}{endpoint}"
47
+ try:
48
+ response = make_get_request(url, auth=self.auth, headers=RAZORPAY_HEADERS)
49
+ except Exception as exception:
50
+ throw_request_error(url, exception)
51
+ return read_response(url, response)
52
+
53
+
54
+ def throw_request_error(url: str, exception: Exception) -> NoReturn:
55
+ description = read_razorpay_error(exception)
56
+ log_request(url, error=description or exception)
57
+ frappe.throw(_("Razorpay rejected the request: {0}").format(description or _("unknown error")))
58
+
59
+
60
+ def read_response(url: str, response) -> dict:
61
+ if not isinstance(response, dict):
62
+ log_request(url, error="Razorpay returned a non-JSON body")
63
+ frappe.throw(_("Razorpay returned an unreadable response"))
64
+
65
+ if error := response.get("error"):
66
+ log_request(url, error=error.get("description") or error.get("code"))
67
+ frappe.throw(_("Razorpay rejected the request: {0}").format(error.get("description")))
68
+
69
+ log_request(url, output=summarise_razorpay_entity(response))
70
+ return response
71
+
72
+
73
+ def log_request(url: str, output=None, error=None):
74
+ # The payload carries the API key and shopper details, so only the endpoint is logged.
75
+ create_request_log(
76
+ {"endpoint": url},
77
+ service_name="Razorpay",
78
+ is_remote_request=True,
79
+ reference_doctype=SETTINGS_DOCTYPE,
80
+ reference_docname=SETTINGS_DOCTYPE,
81
+ output=output,
82
+ error=error,
83
+ status="Failed" if error else "Completed",
84
+ )
85
+
86
+
87
+ def summarise_razorpay_entity(response: dict) -> dict:
88
+ return {"id": response.get("id"), "status": response.get("status")}
89
+
90
+
91
+ def read_razorpay_error(exception: Exception) -> str | None:
92
+ response = getattr(exception, "response", None)
93
+ if response is None:
94
+ return None
95
+ try:
96
+ body = response.json()
97
+ except ValueError:
98
+ return None
99
+ return ((body or {}).get("error") or {}).get("description")
@@ -0,0 +1,131 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ from typing import ClassVar
5
+
6
+ import frappe
7
+ from frappe import _
8
+
9
+ from bwh_payments_core.connectors.razorpay.base import (
10
+ BaseRazorpayClient,
11
+ RazorpayPayment,
12
+ RazorpayPaymentLink,
13
+ RazorpayRefund,
14
+ )
15
+
16
+
17
+ class StubRazorpayClient(BaseRazorpayClient):
18
+ """In-memory Razorpay for tests. Call reset() in setUp."""
19
+
20
+ links: ClassVar[dict[str, RazorpayPaymentLink]] = {}
21
+ created_links: ClassVar[list[dict]] = []
22
+ created_refunds: ClassVar[list[dict]] = []
23
+ refunds: ClassVar[dict[str, RazorpayRefund]] = {}
24
+ next_refund_status: ClassVar[str] = "processed"
25
+
26
+ @classmethod
27
+ def reset(cls):
28
+ cls.links = {}
29
+ cls.created_links = []
30
+ cls.created_refunds = []
31
+ cls.refunds = {}
32
+ cls.next_refund_status = "processed"
33
+
34
+ @classmethod
35
+ def set_refund_status(cls, refund_id: str, status: str):
36
+ cls.refunds[refund_id].status = status
37
+
38
+ @classmethod
39
+ def add_link(cls, status: str = "created") -> str:
40
+ # Unique per call: the doctype enforces a unique order_ref and rows outlive a single test.
41
+ link_id = f"plink_{frappe.generate_hash(length=12)}"
42
+ cls.links[link_id] = RazorpayPaymentLink(
43
+ id=link_id, status=status, short_url=f"https://rzp.io/i/{link_id}", payments=[]
44
+ )
45
+ return link_id
46
+
47
+ @classmethod
48
+ def set_status(cls, link_id: str, status: str):
49
+ cls.links[link_id].status = status
50
+
51
+ @classmethod
52
+ def add_payment(cls, link_id: str, status: str) -> str:
53
+ payment_id = f"pay_{frappe.generate_hash(length=12)}"
54
+ cls.links[link_id].payments.append(RazorpayPayment(payment_id=payment_id, status=status))
55
+ return payment_id
56
+
57
+ @classmethod
58
+ def pay(cls, link_id: str) -> str:
59
+ """Capture a payment and close the link."""
60
+ cls.set_status(link_id, "paid")
61
+ return cls.add_payment(link_id, "captured")
62
+
63
+ def create_payment_link(self, payload: dict) -> RazorpayPaymentLink:
64
+ self.created_links.append(payload)
65
+ return self.get_payment_link(self.add_link())
66
+
67
+ def get_payment_link(self, link_id: str) -> RazorpayPaymentLink:
68
+ if link_id not in self.links:
69
+ frappe.throw(_("Razorpay rejected the request: {0}").format("payment link not found"))
70
+ return self.links[link_id].model_copy(deep=True)
71
+
72
+ def cancel_payment_link(self, link_id: str) -> RazorpayPaymentLink:
73
+ link = self.get_payment_link(link_id)
74
+ if link.status != "created":
75
+ frappe.throw(
76
+ _("Razorpay rejected the request: {0}").format(
77
+ f"payment link is not cancellable in state {link.status}"
78
+ )
79
+ )
80
+ self.set_status(link_id, "cancelled")
81
+ return self.get_payment_link(link_id)
82
+
83
+ def create_refund(self, payment_id: str, amount: int) -> RazorpayRefund:
84
+ self.created_refunds.append({"payment_id": payment_id, "amount": amount})
85
+ refund = RazorpayRefund(
86
+ id=f"rfnd_{frappe.generate_hash(length=12)}", status=self.next_refund_status, amount=amount
87
+ )
88
+ self.refunds[refund.id] = refund
89
+ return refund.model_copy()
90
+
91
+ def get_refund(self, refund_id: str) -> RazorpayRefund:
92
+ if refund_id not in self.refunds:
93
+ frappe.throw(_("Razorpay rejected the request: {0}").format("refund not found"))
94
+ return self.refunds[refund_id].model_copy()
95
+
96
+
97
+ def sign_payload(payload: bytes, secret: str) -> str:
98
+ return hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
99
+
100
+
101
+ def build_payment_link_event(link_id: str, status: str = "paid", event: str = "payment_link.paid") -> bytes:
102
+ return json.dumps(
103
+ {
104
+ "entity": "event",
105
+ "event": event,
106
+ "payload": {"payment_link": {"entity": {"id": link_id, "status": status}}},
107
+ }
108
+ ).encode()
109
+
110
+
111
+ def build_refund_event(
112
+ refund_id: str, payment_id: str, status: str, amount: int, currency: str = "INR"
113
+ ) -> bytes:
114
+ return json.dumps(
115
+ {
116
+ "entity": "event",
117
+ # Razorpay announces a refund that is still pending as refund.created.
118
+ "event": "refund.created" if status == "pending" else f"refund.{status}",
119
+ "payload": {
120
+ "refund": {
121
+ "entity": {
122
+ "id": refund_id,
123
+ "payment_id": payment_id,
124
+ "status": status,
125
+ "amount": amount,
126
+ "currency": currency,
127
+ }
128
+ }
129
+ },
130
+ }
131
+ ).encode()
@@ -0,0 +1,40 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from bwh_payments_core.connectors import GatewayModel
4
+
5
+
6
+ class StripeCheckoutSession(GatewayModel):
7
+ id: str
8
+ url: str | None = None
9
+ status: str | None = None
10
+ payment_status: str | None = None
11
+ payment_intent: str | None = None
12
+ currency: str | None = None
13
+ success_url: str | None = None
14
+ cancel_url: str | None = None
15
+
16
+
17
+ class StripeRefund(GatewayModel):
18
+ id: str | None = None
19
+ status: str | None = None
20
+ # Minor units, as Stripe echoes it.
21
+ amount: int | None = None
22
+
23
+
24
+ class BaseStripeClient(ABC):
25
+ """Stripe Checkout Sessions and Refunds. A refusal raises the SDK's own `stripe.StripeError`."""
26
+
27
+ @abstractmethod
28
+ def create_checkout_session(self, params: dict) -> StripeCheckoutSession: ...
29
+
30
+ @abstractmethod
31
+ def retrieve_checkout_session(self, session_id: str) -> StripeCheckoutSession: ...
32
+
33
+ @abstractmethod
34
+ def expire_checkout_session(self, session_id: str) -> StripeCheckoutSession: ...
35
+
36
+ @abstractmethod
37
+ def create_refund(self, params: dict) -> StripeRefund: ...
38
+
39
+ @abstractmethod
40
+ def retrieve_refund(self, refund_id: str) -> StripeRefund: ...