message.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. import json
  3. from odoo import http
  4. from odoo.http import request
  5. from odoo import fields
  6. from .. import defs
  7. from .base import BaseController
  8. from .tools import get_wx_session_info, get_wx_user_info
  9. from weixin import WeixinMpAPI
  10. # from werobot.client import Client2, ClientException2
  11. from .client import Client2, ClientException2
  12. from openerp import exceptions
  13. import logging
  14. _logger = logging.getLogger(__name__)
  15. class WxappMessage(http.Controller, BaseController):
  16. @http.route('/<string:sub_domain>/check', auth='public', methods=['GET'])
  17. def check_message_setting(self, sub_domain, **kwargs): # 已经没用了?
  18. try:
  19. config = request.env['wxapp.config'].sudo()
  20. app_id = config.get_config('app_id', sub_domain)
  21. secret = config.get_config('secret', sub_domain)
  22. message_token = config.get_config('message_token', sub_domain)
  23. if not app_id or not secret or not message_token:
  24. return self.res_err(404)
  25. # message_token = '5598d9jr1spbyikc3xdh2fnouj3ubs7c'
  26. api = WeixinMpAPI(appid=app_id, app_secret=secret, **kwargs)
  27. api.mp_token = message_token # 这个类应该并不是用于小程序消息的,所以这里需要专门赋值
  28. success = api.validate_signature()
  29. if success:
  30. return api.echostr
  31. return self.res_err(-1)
  32. except Exception as e:
  33. _logger.exception(e)
  34. return self.res_err(-1, e.name)
  35. @http.route('/<string:sub_domain>/send-message', auth='public', methods=['POST'], csrf=False)
  36. def send_message(self, sub_domain, **kwargs): # 已经没用了?
  37. try:
  38. config = request.env['wxapp.config'].sudo()
  39. app_id = config.get_config('app_id', sub_domain)
  40. secret = config.get_config('secret', sub_domain)
  41. client = Client2(app_id, secret)
  42. encrypt_type = request.params.get('encrypt_type', 'raw')
  43. if encrypt_type == 'raw':
  44. dic = json.loads(request.httprequest.data)
  45. client.user_token = dic.get('token', '')
  46. client.page = dic.get('page', '')
  47. client.emphasis_keyword = dic.get('emphasis_keyword', '')
  48. client.template_id = dic.get('template_id', '')
  49. client.data = dic.get('data', '')
  50. else:
  51. raise exceptions.UserError(u'未处理的请求类型')
  52. access_token = request.env(user=1)['wxapp.access_token'].search([
  53. ('token', '=', client.user_token),
  54. ])
  55. if not access_token:
  56. return self.res_err(10000)
  57. client.send_text_message(access_token.open_id)
  58. except Exception as e:
  59. raise exceptions.UserError(u'发送失败 %s' % e)
  60. return