base.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # coding=utf-8
  2. import logging
  3. from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
  4. from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
  5. from typing import TYPE_CHECKING
  6. from library.alipay import AliException
  7. if TYPE_CHECKING:
  8. from apps.web.core.models import AliApp
  9. logger = logging.getLogger(__name__)
  10. class AliApiProxy(object):
  11. URL = "https://openapi.alipay.com/gateway.do"
  12. URL_DEBUG = "https://openapi.alipaydev.com/gateway.do"
  13. def __init__(self, provider, debug=False): # type:(AliApp, bool) -> None
  14. self._url = self.URL if not debug else self.URL_DEBUG
  15. self._appid = str(provider.appid)
  16. self._app_private_key = provider.app_private_key_string
  17. self._alipay_public_key = provider.public_key_string
  18. self._client = None
  19. def __str__(self):
  20. return "AliApiProxy <{}_{}>".format(self.__class__.__name__, self._appid)
  21. @property
  22. def client(self):
  23. if not self._client:
  24. _config = AlipayClientConfig()
  25. _config.server_url = self._url
  26. _config.app_id = self._appid
  27. _config.app_private_key, _config.alipay_public_key = self._app_private_key, self._alipay_public_key
  28. self._client = DefaultAlipayClient(_config, logger=logger)
  29. return self._client
  30. def request(self, request, response):
  31. try:
  32. responseContent = self.client.execute(request)
  33. except Exception as e:
  34. logger.error(e.message)
  35. raise AliException(errCode="", errMsg=e.message)
  36. response.parse_response_content(responseContent)
  37. if not response.is_success():
  38. raise AliException(errCode=response.code, errMsg=response.msg)
  39. return response