__init__.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*- coding: utf-8 -*-
  2. from .msg import WeixinMsg
  3. from .pay import WeixinPay
  4. from .login import WeixinLogin
  5. from .mp import WeixinMP
  6. from .base import WeixinError, Map
  7. from collections import namedtuple
  8. __all__ = ("Weixin")
  9. __author__ = "Weicheng Zou <zwczou@gmail.com>"
  10. StandaloneApplication = namedtuple("StandaloneApplication", ["config"])
  11. class Weixin(WeixinLogin, WeixinPay, WeixinMP, WeixinMsg):
  12. """
  13. 微信SDK
  14. :param app 如果非flask,传入字典配置,如果是flask直接传入app实例
  15. """
  16. def __init__(self, app=None):
  17. if app is not None:
  18. if isinstance(app, dict):
  19. app = StandaloneApplication(config=app)
  20. self.init_app(app)
  21. self.app = app
  22. def init_app(self, app):
  23. if isinstance(app, dict):
  24. app = StandaloneApplication(config=app)
  25. token = app.config.get("WEIXIN_TOKEN")
  26. sender = app.config.get('WEIXIN_SENDER', None)
  27. expires_in = app.config.get('WEIXIN_EXPIRES_IN', 0)
  28. mch_id = app.config.get("WEIXIN_MCH_ID")
  29. mch_key = app.config.get("WEIXIN_MCH_KEY")
  30. notify_url = app.config.get("WEIXIN_NOTIFY_URL")
  31. mch_key_file = app.config.get("WEIXIN_MCH_KEY_FILE")
  32. mch_cert_file = app.config.get("WEIXIN_MCH_CERT_FILE")
  33. app_id = app.config.get("WEIXIN_APP_ID")
  34. app_secret = app.config.get("WEIXIN_APP_SECRET")
  35. if token:
  36. WeixinMsg.__init__(self, token, sender, expires_in)
  37. if app_id and mch_id and mch_key and notify_url:
  38. WeixinPay.__init__(self, app_id, mch_id, mch_key, notify_url, mch_key_file, mch_cert_file)
  39. if app_id and app_secret:
  40. WeixinLogin.__init__(self, app_id, app_secret)
  41. WeixinMP.__init__(self, app_id, app_secret)
  42. # 兼容老版本
  43. if app_id and mch_id and mch_key and notify_url:
  44. self.pay = WeixinPay(app_id, mch_id, mch_key, notify_url, mch_key_file, mch_cert_file)
  45. if token:
  46. self.msg = WeixinMsg(token, sender, expires_in)
  47. if app_id and app_secret:
  48. self.login = WeixinLogin(app_id, app_secret)
  49. self.mp = WeixinMP(app_id, app_secret)