__init__.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import logging
  4. import dicttoxml
  5. import six
  6. from django.utils.module_loading import import_string
  7. from typing import TYPE_CHECKING, Optional, cast, Union
  8. from apilib.systypes import IterConstant
  9. from apps.web.constant import AppPlatformType
  10. if TYPE_CHECKING:
  11. from apps.web.core.models import WechatPayApp, PayAppBase, EmbeddedApp
  12. logger = logging.getLogger(__name__)
  13. class PayAppType(IterConstant):
  14. # 资金池模式只使用ALIPAY,WECHAT,JD_AGGR三种支付方式
  15. ALIPAY = 'alipay'
  16. WECHAT = 'wechat'
  17. # 各经销商可使用的支付方式(包括JD_AGGR以及ALIPAY+WECHAT)
  18. PLATFORM_PROMOTION = "platform_promotion"
  19. PLATFORM_WALLET = 'platform_wallet'
  20. PLATFORM_RECONCILE ='platform_reconcile'
  21. JD_OPEN = 'jdopen'
  22. MANUAL = 'manual'
  23. SWAP = 'swap'
  24. LEDGER_CONSUME = "ledgerConsume"
  25. PAY_APP_TYPE_TRANSLATION = {
  26. AppPlatformType.ALIPAY: u'支付宝',
  27. AppPlatformType.WECHAT: u'微信',
  28. }
  29. PAY_APP_MAP = {
  30. PayAppType.ALIPAY: 'apps.web.core.models.AliApp',
  31. PayAppType.WECHAT: 'apps.web.core.models.WechatPayApp',
  32. PayAppType.PLATFORM_PROMOTION: 'apps.web.core.models.PlatformPromotionApp',
  33. PayAppType.PLATFORM_WALLET: 'app.web.core.models.PlatformWalletApp',
  34. PayAppType.PLATFORM_RECONCILE: 'app.web.core.models.PlatformReconcileApp',
  35. PayAppType.MANUAL: 'apps.web.core.models.ManualPayApp'
  36. }
  37. APP_KEY_DELIMITER = '-'
  38. wechat_bound_openid_key = lambda appid: APP_KEY_DELIMITER.join([AppPlatformType.WECHAT, appid])
  39. class BaseAppProxy(object):
  40. def __init__(self, app):
  41. # type: (Optional[EmbeddedApp, WechatPayApp])->None
  42. self._app = app # type: Optional[EmbeddedApp, WechatPayApp]
  43. @property
  44. def app(self):
  45. return self._app
  46. @property
  47. def client(self):
  48. if hasattr(self, '__client__'):
  49. return getattr(self, '__client__')
  50. else:
  51. raise AttributeError('no __client__ attribute')
  52. @property
  53. def occupantId(self):
  54. return self._app.occupantId
  55. @property
  56. def occupant(self):
  57. return self._app.occupant
  58. @property
  59. def bound_openid_key(self):
  60. if not hasattr(self, '__bound_openid_key__'):
  61. raise AttributeError('no __bound_openid_key__ attribute')
  62. return getattr(self, '__bound_openid_key__')
  63. @property
  64. def gateway_type(self):
  65. if not hasattr(self, '__gateway_type__'):
  66. raise AttributeError('no __gateway_type__ attribute')
  67. return getattr(self, '__gateway_type__')
  68. @property
  69. def debug(self):
  70. return self._app.debug
  71. @property
  72. def enable(self):
  73. return self._app.enable
  74. @property
  75. def valid(self):
  76. return self._app.valid
  77. class _BaseMixin(object):
  78. @property
  79. def __app_for_inner__(self):
  80. # type: ()->Union[cast(PayAppBase), EmbeddedApp]
  81. if not hasattr(self, 'app'):
  82. raise AttributeError('no app attribute')
  83. return getattr(self, 'app')
  84. @property
  85. def __client_for_inner__(self):
  86. if not hasattr(self, 'client'):
  87. raise AttributeError('no client attribute')
  88. return getattr(self, 'client')
  89. @property
  90. def __bound_openid_key__(self):
  91. raise AttributeError('no __bound_openid_key__ attribute')
  92. class WechatMixin(_BaseMixin):
  93. @property
  94. def appid(self):
  95. return self.__app_for_inner__.appid
  96. @property
  97. def secret(self):
  98. return self.__app_for_inner__.secret
  99. @classmethod
  100. def reply(cls, msg, ok):
  101. # type: (basestring, bool)->str
  102. response = {
  103. "return_code": "SUCCESS" if ok else "FAIL",
  104. "return_msg": msg
  105. }
  106. return cls.serialize_wechat_xml(response)
  107. def check(self, data, order = True, token = True):
  108. return self.__client_for_inner__.check_signature(data)
  109. @classmethod
  110. def serialize_wechat_xml(cls, payload):
  111. # type:(dict)->str
  112. return dicttoxml.dicttoxml(payload, attr_type = False, custom_root = 'xml', cdata = True)
  113. @property
  114. def __bound_openid_key__(self):
  115. return wechat_bound_openid_key(self.appid)
  116. # @property
  117. # def __gateway_type__(self):
  118. # return AppPlatformType.WECHAT
  119. class AlipayMixin(_BaseMixin):
  120. """
  121. Alipay 支付网关,扩展原库没有的接口 ``alipay.trade.create``
  122. """
  123. @property
  124. def appid(self):
  125. return self.__app_for_inner__.appid
  126. @property
  127. def app_private_key_string(self):
  128. return self.__app_for_inner__.app_private_key_string
  129. @property
  130. def public_key_string(self):
  131. return self.__app_for_inner__.public_key_string
  132. @property
  133. def public_key_cert_string(self):
  134. return self.__app_for_inner__.public_key_cert_string
  135. @property
  136. def root_cert_string(self):
  137. return self.__app_for_inner__.root_cert_string
  138. @property
  139. def app_public_key_cert_string(self):
  140. return self.__app_for_inner__.app_public_key_cert_string
  141. @property
  142. def aes_encrypt_key(self):
  143. return self.__app_for_inner__.aes_encrypt_key
  144. @property
  145. def signKeyType(self):
  146. return self.__app_for_inner__.signKeyType
  147. @property
  148. def __bound_openid_key__(self):
  149. # 支付宝用户ID是唯一的,直接以平台类型区分
  150. return AppPlatformType.ALIPAY
  151. @property
  152. def __client__(self):
  153. return self.__app_for_inner__.client
  154. def check(self, data, pop_sign_type = True):
  155. # type:(dict, bool)->bool
  156. sign = data.pop('sign')
  157. if not sign:
  158. logger.error('has no sign')
  159. return False
  160. return self.__client__.verify(data, sign, pop_sign_type)
  161. class ROLEMetaClass(type):
  162. def __setattr__(self, name, value):
  163. raise NotImplementedError()
  164. def __getattr__(self, item):
  165. if item in self.choices():
  166. return item
  167. else:
  168. raise KeyError()
  169. class ROLE(six.with_metaclass(ROLEMetaClass)):
  170. __role_map = {
  171. 'myuser': {
  172. 'module': 'apps.web.user.models.MyUser',
  173. 'sub_type': 'U'
  174. },
  175. 'dealer': {
  176. 'module': 'apps.web.dealer.models.Dealer',
  177. 'sub_type': 'D'
  178. },
  179. 'subaccount': {
  180. 'module': 'apps.web.dealer.models.SubAccount',
  181. 'sub_type': 'B'
  182. },
  183. 'agent': {
  184. 'module': 'apps.web.agent.models.Agent',
  185. 'sub_type': 'A'
  186. },
  187. 'manager': {
  188. 'module': 'apps.web.management.models.Manager',
  189. 'sub_type': 'M'
  190. },
  191. 'supermanager': {
  192. 'module': 'apps.web.superamdin.models.SuperManager',
  193. 'sub_type': 'S'
  194. },
  195. 'advertiser': {
  196. 'module': 'apps.web.ad.models.Advertiser',
  197. 'sub_type': 'V'
  198. },
  199. 'tester': {
  200. 'module': 'apps.web.test.models.Tester',
  201. 'sub_type': 'T'
  202. },
  203. 'advertisement': {
  204. 'module': 'apps.web.ad.models.Advertisement',
  205. 'sub_type': 'T'
  206. },
  207. 'anonymoususer': {
  208. 'module': 'django.contrib.auth.models.AnonymousUser',
  209. 'sub_type': 'N'
  210. },
  211. 'manufacturer': {
  212. 'module': 'apps.web.management.models.Manager',
  213. 'sub_type': 'M'
  214. }
  215. }
  216. def __init__(self):
  217. raise NotImplementedError()
  218. @classmethod
  219. def choices(cls):
  220. return cls.__role_map.keys()
  221. @classmethod
  222. def from_role_id(cls, role, id):
  223. if role == cls.anonymoususer:
  224. return import_string(cls.__role_map[role]['module'])()
  225. else:
  226. return import_string(cls.__role_map[role]['module']).objects(id = id).get()
  227. @classmethod
  228. def sub_type(cls, role):
  229. return cls.__role_map[role]['sub_type']
  230. @classmethod
  231. def sub_type_list(cls):
  232. return [item['sub_type'] for item in cls.__role_map.values()]