main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  2. import hashlib
  3. import hmac
  4. import json
  5. import logging
  6. import pprint
  7. from datetime import datetime
  8. from werkzeug.exceptions import Forbidden
  9. from odoo import http
  10. from odoo.exceptions import ValidationError
  11. from odoo.http import request
  12. from odoo.tools.misc import file_open
  13. from odoo.addons.payment import utils as payment_utils
  14. from odoo.addons.payment_stripe import utils as stripe_utils
  15. from odoo.addons.payment_stripe.const import HANDLED_WEBHOOK_EVENTS
  16. _logger = logging.getLogger(__name__)
  17. class StripeController(http.Controller):
  18. _checkout_return_url = '/payment/stripe/checkout_return'
  19. _validation_return_url = '/payment/stripe/validation_return'
  20. _webhook_url = '/payment/stripe/webhook'
  21. _apple_pay_domain_association_url = '/.well-known/apple-developer-merchantid-domain-association'
  22. WEBHOOK_AGE_TOLERANCE = 10*60 # seconds
  23. @http.route(_checkout_return_url, type='http', auth='public', csrf=False)
  24. def stripe_return_from_checkout(self, **data):
  25. """ Process the notification data sent by Stripe after redirection from checkout.
  26. :param dict data: The GET params appended to the URL in `_stripe_create_checkout_session`
  27. """
  28. # Retrieve the tx based on the tx reference included in the return url
  29. tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_notification_data(
  30. 'stripe', data
  31. )
  32. # Fetch the PaymentIntent, Charge and PaymentMethod objects from Stripe
  33. payment_intent = tx_sudo.provider_id._stripe_make_request(
  34. f'payment_intents/{tx_sudo.stripe_payment_intent}', method='GET'
  35. )
  36. _logger.info("received payment_intents response:\n%s", pprint.pformat(payment_intent))
  37. self._include_payment_intent_in_notification_data(payment_intent, data)
  38. # Handle the notification data crafted with Stripe API objects
  39. tx_sudo._handle_notification_data('stripe', data)
  40. # Redirect the user to the status page
  41. return request.redirect('/payment/status')
  42. @http.route(_validation_return_url, type='http', auth='public', csrf=False)
  43. def stripe_return_from_validation(self, **data):
  44. """ Process the notification data sent by Stripe after redirection for validation.
  45. :param dict data: The GET params appended to the URL in `_stripe_create_checkout_session`
  46. """
  47. # Retrieve the transaction based on the tx reference included in the return url
  48. tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_notification_data(
  49. 'stripe', data
  50. )
  51. # Fetch the Session, SetupIntent and PaymentMethod objects from Stripe
  52. checkout_session = tx_sudo.provider_id._stripe_make_request(
  53. f'checkout/sessions/{data.get("checkout_session_id")}',
  54. payload={'expand[]': 'setup_intent.payment_method'}, # Expand all required objects
  55. method='GET'
  56. )
  57. _logger.info("received checkout/session response:\n%s", pprint.pformat(checkout_session))
  58. self._include_setup_intent_in_notification_data(
  59. checkout_session.get('setup_intent', {}), data
  60. )
  61. # Handle the notification data crafted with Stripe API objects
  62. tx_sudo._handle_notification_data('stripe', data)
  63. # Redirect the user to the status page
  64. return request.redirect('/payment/status')
  65. @http.route(_webhook_url, type='json', auth='public')
  66. def stripe_webhook(self):
  67. """ Process the notification data sent by Stripe to the webhook.
  68. :return: An empty string to acknowledge the notification
  69. :rtype: str
  70. """
  71. event = json.loads(request.httprequest.data)
  72. _logger.info("notification received from Stripe with data:\n%s", pprint.pformat(event))
  73. try:
  74. if event['type'] in HANDLED_WEBHOOK_EVENTS:
  75. stripe_object = event['data']['object'] # {Payment,Setup}Intent, Charge, or Refund.
  76. # Check the integrity of the event.
  77. data = {
  78. 'reference': stripe_object.get('description'),
  79. 'event_type': event['type'],
  80. 'object_id': stripe_object['id'],
  81. }
  82. tx_sudo = request.env['payment.transaction'].sudo()._get_tx_from_notification_data(
  83. 'stripe', data
  84. )
  85. self._verify_notification_signature(tx_sudo)
  86. # Handle the notification data.
  87. if event['type'].startswith('payment_intent'): # Payment operation.
  88. self._include_payment_intent_in_notification_data(stripe_object, data)
  89. elif event['type'].startswith('setup_intent'): # Validation operation.
  90. # Fetch the missing PaymentMethod object.
  91. payment_method = tx_sudo.provider_id._stripe_make_request(
  92. f'payment_methods/{stripe_object["payment_method"]}', method='GET'
  93. )
  94. _logger.info(
  95. "received payment_methods response:\n%s", pprint.pformat(payment_method)
  96. )
  97. stripe_object['payment_method'] = payment_method
  98. self._include_setup_intent_in_notification_data(stripe_object, data)
  99. elif event['type'] == 'charge.refunded': # Refund operation (refund creation).
  100. refunds = stripe_object['refunds']['data']
  101. # The refunds linked to this charge are paginated, fetch the remaining refunds.
  102. has_more = stripe_object['refunds']['has_more']
  103. while has_more:
  104. payload = {
  105. 'charge': stripe_object['id'],
  106. 'starting_after': refunds[-1]['id'],
  107. 'limit': 100,
  108. }
  109. additional_refunds = tx_sudo.provider_id._stripe_make_request(
  110. 'refunds', payload=payload, method='GET'
  111. )
  112. refunds += additional_refunds['data']
  113. has_more = additional_refunds['has_more']
  114. # Process the refunds for which a refund transaction has not been created yet.
  115. processed_refund_ids = tx_sudo.child_transaction_ids.filtered(
  116. lambda tx: tx.operation == 'refund'
  117. ).mapped('provider_reference')
  118. for refund in filter(lambda r: r['id'] not in processed_refund_ids, refunds):
  119. refund_tx_sudo = self._create_refund_tx_from_refund(tx_sudo, refund)
  120. self._include_refund_in_notification_data(refund, data)
  121. refund_tx_sudo._handle_notification_data('stripe', data)
  122. return '' # Don't handle the notification data for the source transaction.
  123. elif event['type'] == 'charge.refund.updated': # Refund operation (with update).
  124. # A refund was updated by Stripe after it was already processed (possibly to
  125. # cancel it). This can happen when the customer's payment method can no longer
  126. # be topped up (card expired, account closed...). The `tx_sudo` record is the
  127. # refund transaction to update.
  128. self._include_refund_in_notification_data(stripe_object, data)
  129. # Handle the notification data crafted with Stripe API objects
  130. tx_sudo._handle_notification_data('stripe', data)
  131. except ValidationError: # Acknowledge the notification to avoid getting spammed
  132. _logger.exception("unable to handle the notification data; skipping to acknowledge")
  133. return ''
  134. @staticmethod
  135. def _include_payment_intent_in_notification_data(payment_intent, notification_data):
  136. notification_data.update({'payment_intent': payment_intent})
  137. if payment_intent.get('charges', {}).get('total_count', 0) > 0:
  138. charge = payment_intent['charges']['data'][0] # Use the latest charge object
  139. notification_data.update({
  140. 'charge': charge,
  141. 'payment_method': charge.get('payment_method_details'),
  142. })
  143. @staticmethod
  144. def _include_setup_intent_in_notification_data(setup_intent, notification_data):
  145. notification_data.update({
  146. 'setup_intent': setup_intent,
  147. 'payment_method': setup_intent.get('payment_method'),
  148. })
  149. @staticmethod
  150. def _include_refund_in_notification_data(refund, notification_data):
  151. notification_data.update(refund=refund)
  152. @staticmethod
  153. def _create_refund_tx_from_refund(source_tx_sudo, refund_object):
  154. """ Create a refund transaction based on Stripe data.
  155. :param recordset source_tx_sudo: The source transaction for which a refund is initiated, as
  156. a sudoed `payment.transaction` record.
  157. :param dict refund_object: The Stripe refund object to create the refund from.
  158. :return: The created refund transaction.
  159. :rtype: recordset of `payment.transaction`
  160. """
  161. amount_to_refund = refund_object['amount']
  162. converted_amount = payment_utils.to_major_currency_units(
  163. amount_to_refund, source_tx_sudo.currency_id
  164. )
  165. return source_tx_sudo._create_refund_transaction(amount_to_refund=converted_amount)
  166. def _verify_notification_signature(self, tx_sudo):
  167. """ Check that the received signature matches the expected one.
  168. See https://stripe.com/docs/webhooks/signatures#verify-manually.
  169. :param recordset tx_sudo: The sudoed transaction referenced by the notification data, as a
  170. `payment.transaction` record
  171. :return: None
  172. :raise: :class:`werkzeug.exceptions.Forbidden` if the timestamp is too old or if the
  173. signatures don't match
  174. """
  175. webhook_secret = stripe_utils.get_webhook_secret(tx_sudo.provider_id)
  176. if not webhook_secret:
  177. _logger.warning("ignored webhook event due to undefined webhook secret")
  178. return
  179. notification_payload = request.httprequest.data.decode('utf-8')
  180. signature_entries = request.httprequest.headers['Stripe-Signature'].split(',')
  181. signature_data = {k: v for k, v in [entry.split('=') for entry in signature_entries]}
  182. # Retrieve the timestamp from the data
  183. event_timestamp = int(signature_data.get('t', '0'))
  184. if not event_timestamp:
  185. _logger.warning("received notification with missing timestamp")
  186. raise Forbidden()
  187. # Check if the timestamp is not too old
  188. if datetime.utcnow().timestamp() - event_timestamp > self.WEBHOOK_AGE_TOLERANCE:
  189. _logger.warning("received notification with outdated timestamp: %s", event_timestamp)
  190. raise Forbidden()
  191. # Retrieve the received signature from the data
  192. received_signature = signature_data.get('v1')
  193. if not received_signature:
  194. _logger.warning("received notification with missing signature")
  195. raise Forbidden()
  196. # Compare the received signature with the expected signature computed from the data
  197. signed_payload = f'{event_timestamp}.{notification_payload}'
  198. expected_signature = hmac.new(
  199. webhook_secret.encode('utf-8'), signed_payload.encode('utf-8'), hashlib.sha256
  200. ).hexdigest()
  201. if not hmac.compare_digest(received_signature, expected_signature):
  202. _logger.warning("received notification with invalid signature")
  203. raise Forbidden()
  204. @http.route(_apple_pay_domain_association_url, type='http', auth='public', csrf=False)
  205. def stripe_apple_pay_get_domain_association_file(self):
  206. """ Get the domain association file for Stripe's Apple Pay.
  207. Stripe handles the process of "merchant validation" described in Apple's documentation for
  208. Apple Pay on the Web. Stripe and Apple will access this route to check the content of the
  209. file and verify that the web domain is registered.
  210. See https://stripe.com/docs/stripe-js/elements/payment-request-button#verifying-your-domain-with-apple-pay.
  211. :return: The content of the domain association file.
  212. :rtype: str
  213. """
  214. return file_open(
  215. 'payment_stripe/static/files/apple-developer-merchantid-domain-association'
  216. ).read()