中国本土应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
3.0KB

  1. # -*- coding: utf-8 -*-
  2. import json
  3. import requests
  4. from datetime import datetime, timedelta
  5. from odoo import api, fields, models, SUPERUSER_ID, _
  6. # from .wecom_abstract_api import ApiException
  7. class WecomServerApi(models.TransientModel):
  8. _inherit = "wecom.abstract_api"
  9. _name = "wecom.service_api"
  10. _description = "Wecom Server API"
  11. _table = "wecom_service_api"
  12. corpid = fields.Char(string="Corp Id", readonly=True)
  13. secret = fields.Char(string="Secret", readonly=True)
  14. access_token = fields.Char(string="Access Token", readonly=True, default=None)
  15. token_expiration_time = fields.Datetime(
  16. string="Token Expiration Time", readonly=True
  17. )
  18. @api.model
  19. def InitServiceApi(self, corpid, secret):
  20. """
  21. 初始化企业微信API 对象
  22. :param corpid : 企业ID
  23. :param secret : 应用密钥
  24. :returns 模型"wecom.service_api"对象
  25. """
  26. api = self.search(
  27. [
  28. ("corpid", "=", corpid),
  29. ("secret", "=", secret),
  30. ],
  31. limit=1,
  32. )
  33. if not api:
  34. # 创建API令牌记录
  35. api = self.sudo().create(
  36. {
  37. "corpid": corpid,
  38. "secret": secret,
  39. }
  40. )
  41. if api["access_token"] is False or api["access_token"] == "":
  42. # token为空,刷新API令牌记录
  43. api.refreshAccessToken()
  44. if (
  45. api["token_expiration_time"] is False
  46. or api["token_expiration_time"] < datetime.now()
  47. ):
  48. # token过期,刷新API令牌记录
  49. api.refreshAccessToken()
  50. return api
  51. def getAccessToken(self):
  52. """
  53. 获取令牌
  54. """
  55. if self.access_token is None:
  56. self.refreshAccessToken()
  57. return self.access_token
  58. def refreshAccessToken(self):
  59. """
  60. 刷新模型 'wecom.service_api' 的令牌
  61. 同时刷新发起请求的模型 'wecom.apps' 的令牌
  62. """
  63. response = self.httpCall(
  64. self.env["wecom.service_api_list"].get_server_api_call("GET_ACCESS_TOKEN"),
  65. {"corpid": self.corpid, "corpsecret": self.secret},
  66. )
  67. expiration_second = timedelta(seconds=response["expires_in"])
  68. dict = {
  69. "access_token": response.get("access_token"),
  70. "token_expiration_time": datetime.now() + expiration_second,
  71. }
  72. self.sudo().write(dict)
  73. # 写对应的应用的值
  74. compay_id = self.env["res.company"].search(
  75. [("corpid", "=", self.corpid)], limit=1
  76. )
  77. app_id = self.env["wecom.apps"].search(
  78. [("company_id", "=", compay_id.id), ("secret", "=", self.secret)], limit=1
  79. )
  80. app_id.sudo().write(dict)
  81. def get_api_debug(self):
  82. """
  83. 获取 API 调试模式
  84. """
  85. ir_config = self.env["ir.config_parameter"].sudo()
  86. return True if ir_config.get_param("wecom.debug_enabled") == "True" else False
上海开阖软件有限公司 沪ICP备12045867号-1